Android系统中主要提供了三种方式用于简单的实现数据持久化功能:
1,文件存储
特点:手机自带的内存,只能供当前应用程序访问,其他应用程序访问不了,程序卸载这些数据也会随着消失
- private void save(String inputText ) {
- FileOutputStream fos = null;
- BufferedWriter writer = null;
- try {
- fos = openFileOutput( "data", Context.MODE_PRIVATE);
- writer = new BufferedWriter( new OutputStreamWriter(fos));
- writer.write( inputText);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- try {
- if( writer != null)
- writer.close();
- }catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //帮助我们返回一个目录
- //context.getCacheDir ()的话就是保存到cache缓存文件夹下面
- File file=new File(context.getFilesDir(), "userinfo.txt");
- FileOutputStream fos= new FileOutputStream( file);
- //zhangsan 123
- fos.write(( username+ "##"+ password).getBytes());
- fos.close();
2、sharedpreference 存储(一般用于保存用户设置偏好);
特点如下:
@1以键值对的形式保存到data/data/应用程序包名/shared_prefs目录的XXX.xml文件中
@2目前支持的数据类型有String int float boolean long
@3不支持自定义的Object
@4通常用来存储App上的用户配置信息.如:是否震动,是否打开背景音乐 小游戏积分 用户账号密码信息
@5 在一些需要缓存的页面数据的情况在,比如一个首页的列表数据,在不需要对列表数据进行增删改的情况下(一般app的页面数据缓存仅需要查询功能),可以取巧使用sp来保存json数据,再利用fastjson,gson等格式化工具来恢复数据。
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- SharedPreferences.Editor editor=getSharedPreferences( "data", MODE_PRIVATE).edit();
- editor.putString( "name", "HuaAn");
- editor.putInt( "id", 9527);
- editor.putBoolean( "婚否", false );
- editor.commit();
- }
- });
- restore_button .setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- SharedPreferences pref=getSharedPreferences( "data", MODE_PRIVATE);
- String name= pref.getString( "name", "HuaAn");
- int id= pref.getInt( "id", 9527);
- boolean married= pref.getBoolean( "婚否", false );
- }
- });
- }
3 ,SQLite数据库存储
实现步骤如下:
- public class MyDatabaseHelper extends SQLiteOpenHelper {
- /*
- 补充一下建表的一些类型
- integer ---整型
- real-----浮点类型
- text---文本类型
- blob---二进制类型
- */
- public static final String CREATE_BOOK= "create table book(id integer primary key autoincrement,"
- + "author text"
- + "price real"
- + "pages integer"
- + "name text)";
- private Context mContext ;
- public MyDatabaseHelper(Context context, String name,
- CursorFactory factory, int version) {
- super( context, name, factory, version);
- // TODO Auto-generated constructor stub
- mContext= context;
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- // TODO Auto-generated method stub
- //执行建表语句
- db.execSQL(CREATE_BOOK);
- Toast.makeText(mContext , "数据库创建成功" , Toast.LENGTH_SHORT).show();
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- // TODO Auto-generated method stub
- }
- }
- dbHelper= new MyDatabaseHelper( this, "BookStore.db", null, 1);
- Button createDatabase=(Button) findViewById(R.id.create_database );
- createDatabase.setOnClickListener( new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- dbHelper. getWritableDatabase();
- }
- });
public long insert (String table, String nullColumnHack, ContentValues values)
Convenience method for inserting a row into the database.
Parameters
table | the table to insert the row into |
---|---|
nullColumnHack | optional; may be null . SQL doesn't allow inserting a completely empty row without naming at least one column name. If your provided values is empty, no column names are known and an empty row can't be inserted. If not set to null, thenullColumnHack parameter provides the name of nullable column name to explicitly insert a NULL into in the case where your values is empty. |
values | this map contains the initial column values for the row. The keys should be the column names and the values the column values |
public int update (String table, ContentValues values, String whereClause, String[]whereArgs)
Convenience method for updating rows in the database.
Parameters
table | the table to update in |
---|---|
values | a map from column names to new column values. null is a valid value that will be translated to NULL. |
whereClause | the optional WHERE clause to apply when updating. Passing null will update all rows. |
whereArgs | You may include ?s in the where clause, which will be replaced by the values from whereArgs. The values will be bound as Strings. |
public int delete (String table, String whereClause, String[] whereArgs)
Convenience method for deleting rows in the database.
查询语句
public Cursor query (String table, String[] columns, String selection, String[]selectionArgs, String groupBy, String having, String orderBy)
Query the given table, returning a Cursor
over the result set.
Parameters
table | The table name to compile the query against. |
---|---|
columns | A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used. |
selection | A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table. |
selectionArgs | You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings. |
groupBy | A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped. |
having | A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used. |
orderBy | How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered. |
public abstract int getColumnIndex (String columnName)
Returns the zero-based index for the given column name, or -1 if the column doesn't exist. If you expect the column to exist use getColumnIndexOrThrow(String)
instead, which will make the error more clear.
Returns
- the zero-based column index for the given column name, or -1 if the column name does not exist.