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.