Android基础——数据持久化存储
- 數據持久化存儲
- 文件存儲
- 數據保存
- 數據讀取
- 鍵值對存儲
- 數據保存
- 數據讀取
- 數據庫存儲
- 數據庫創建
- 增加數據
- 更新數據
- 刪除數據
- 查詢數據
- 使用事物
- 升級數據庫
- 文件存儲
內容來自于第一行代碼中數據持久化存儲這一章
數據持久化存儲
文件存儲
數據保存
Context.openFileOutput( )方法 用于文件輸出
第一個參數:文件名 默認保存到 /data/data/包名/files/
第二個參數:文件操作方式 Context.MODE_PRIVATE(覆蓋方式) Context.MODE_APPEND(附加方式,沒有就創建文件)
Android4.2中廢棄了MODE_WORLD_READABLE MODE_WORLD_WRITEABLE
數據讀取
Context.openFileInput( )方法 用于文件輸入
public class MainActivity extends Activity {private EditText edit;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);edit = (EditText) findViewById(R.id.edit);String inputText = load();if (!TextUtils.isEmpty(inputText)) {edit.setText(inputText);edit.setSelection(inputText.length());Toast.makeText(this, "Restoring succeeded",Toast.LENGTH_SHORT).show();}}……public String load() {FileInputStream in = null;BufferedReader reader = null;StringBuilder content = new StringBuilder();try {in = openFileInput("data");reader = new BufferedReader(new InputStreamReader(in));String line = "";while ((line = reader.readLine()) != null) {content.append(line);}} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}return content.toString();} }注意:
1、TextUitls.isEmpty( )一次檢查字符串兩種空值 “”與null
2、StringBuffer與StringBuilder的區別
StringBuffer不是線程同步的,所以不是線程安全的,但比StringBuilder速度快
StringBuilder是線程同步的,所以是線程安全的
鍵值對存儲
SharedPreferences使用鍵值對的方式來存儲數據,當保存一條數據的時候,需要給這條數據提供一個對應的鍵,這樣在讀取數據的時候可以通過這個鍵把相應的值取出來。
Context類提供getSharedPreferences( )方法
文件存儲在 /data/data/share_prefs/目錄下
Context.getSharedPreferences( )
第一個參數:文件名
第二個參數:存儲模式 Context.MODE_PRIVATE Context.MODE_MULTI_PROCESS
Android4.2版本中廢棄了Context.MODE_WORLD_READABLE Context.MODE_WORLD_WIRTEABLE
Activity類提供getPreferences( )方法
只有一個參數,即操作模式。保存的文件名即Activity的類名
PreferenceManager類提供getDefaultSharedPreferences( )
只接收一個Context參數,靜態方法,保存的文件名即應用程序的包名
數據保存
public class MainActivity extends Activity {private Button saveData;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);saveData = (Button) findViewById(R.id.save_data);saveData.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();editor.putString("name", "Tom");editor.putInt("age", 28);editor.putBoolean("married", false);editor.commit();}});} }數據讀取
public class MainActivity extends Activity {private Button saveData;private Button restoreData;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);saveData = (Button) findViewById(R.id.save_data);restoreData = (Button) findViewById(R.id.restore_data);……restoreData.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE);String name = pref.getString("name", "");int age = pref.getInt("age", 0);boolean married = pref.getBoolean("married", false);Log.d("MainActivity", "name is " + name);Log.d("MainActivity", "age is " + age);Log.d("MainActivity", "married is " + married);}});} }數據庫存儲
數據庫創建
public class MyDatabaseHelper extends SQLiteOpenHelper {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);mContext = context;}@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL(CREATE_BOOK);Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {} }public class MainActivity extends Activity {private MyDatabaseHelper dbHelper;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);Button createDatabase = (Button) findViewById(R.id.create_database);createDatabase.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {dbHelper.getWritableDatabase();} });} }增加數據
public class MainActivity extends Activity {private MyDatabaseHelper dbHelper;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);……Button addData = (Button) findViewById(R.id.add_data);addData.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {SQLiteDatabase db = dbHelper.getWritableDatabase();ContentValues values = new ContentValues();// 開始組裝第一條數據values.put("name", "The Da Vinci Code");values.put("author", "Dan Brown");values.put("pages", 454);values.put("price", 16.96);db.insert("Book", null, values); // 插入第一條數據values.clear();// 開始組裝第二條數據values.put("name", "The Lost Symbol");values.put("author", "Dan Brown");values.put("pages", 510);values.put("price", 19.95);db.insert("Book", null, values); // 插入第二條數據}});} }更新數據
public class MainActivity extends Activity {private MyDatabaseHelper dbHelper;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);……Button updateData = (Button) findViewById(R.id.update_data);updateData.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {SQLiteDatabase db = dbHelper.getWritableDatabase();ContentValues values = new ContentValues();values.put("price", 10.99);db.update("Book", values, "name = ?", new String[] { "The DaVinci Code" });}});} }刪除數據
public class MainActivity extends Activity {private MyDatabaseHelper dbHelper;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);……Button deleteButton = (Button) findViewById(R.id.delete_data);deleteButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {SQLiteDatabase db = dbHelper.getWritableDatabase();db.delete("Book", "pages > ?", new String[] { "500" });}});} }查詢數據
public class MainActivity extends Activity {private MyDatabaseHelper dbHelper;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);……Button queryButton = (Button) findViewById(R.id.query_data);queryButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {SQLiteDatabase db = dbHelper.getWritableDatabase();// 查詢Book表中所有的數據Cursor cursor = db.query("Book", null, null, null, null, null, null);if (cursor.moveToFirst()) {do {// 遍歷Cursor對象,取出數據并打印String name = cursor.getString(cursor.getColumnIndex("name"));String author = cursor.getString(cursor.getColumnIndex("author"));int pages = cursor.getInt(cursor.getColumnIndex("pages"));double price = cursor.getDouble(cursor.getColumnIndex("price"));Log.d("MainActivity", "book name is " + name);Log.d("MainActivity", "book author is " + author);Log.d("MainActivity", "book pages is " + pages);Log.d("MainActivity", "book price is " + price);} while (cursor.moveToNext());}cursor.close();}});} }使用事物
public class MainActivity extends Activity {private MyDatabaseHelper dbHelper;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);……Button replaceData = (Button) findViewById(R.id.replace_data);replaceData.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {SQLiteDatabase db = dbHelper.getWritableDatabase();db.beginTransaction(); // 開啟事務try {db.delete("Book", null, null);if (true) {// 在這里手動拋出一個異常,讓事務失敗throw new NullPointerException();}ContentValues values = new ContentValues();values.put("name", "Game of Thrones");values.put("author", "George Martin");values.put("pages", 720);values.put("price", 20.85);db.insert("Book", null, values);db.setTransactionSuccessful(); // 事務已經執行成功} catch (Exception e) {e.printStackTrace();} finally {db.endTransaction(); // 結束事務}}});} }升級數據庫
public class MyDatabaseHelper extends SQLiteOpenHelper {public static final String CREATE_BOOK = "create table Book ("+ "id integer primary key autoincrement, "+ "author text, "+ "price real, "+ "pages integer, "+ "name text, "+ "category_id integer)";public static final String CREATE_CATEGORY = "create table Category ("+ "id integer primary key autoincrement, "+ "category_name text, "+ "category_code integer)";public MyDatabaseHelper(Context context, String name,CursorFactory factory, int version) {super(context, name, factory, version);}@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL(CREATE_BOOK);db.execSQL(CREATE_CATEGORY);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {switch (oldVersion) {case 1:db.execSQL(CREATE_CATEGORY);case 2:db.execSQL("alter table Book add column category_id integer");default:}} } 《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Android基础——数据持久化存储的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网易云音乐Android版使用的开源组件
- 下一篇: 自己使用的Android框架