數(shù)據(jù)持久化就是指將那些內存中的瞬時數(shù)據(jù)保存到存儲設備中按脚,保證即使在手機或電腦關機的情況下,這些數(shù)據(jù)也不會丟失敦冬。保存在內存中的數(shù)據(jù)是處于瞬時狀態(tài)的辅搬,而保存在存儲設備中的數(shù)據(jù)是處于持久狀態(tài)的,持久化技術則提供了一種機制可以讓數(shù)據(jù)在瞬時狀態(tài)和持久狀態(tài)之間進行轉換
文件存儲
文件存儲流程:
- 寫:使用openFileOutput(""脖旱,Context.MODE_PRIVATE)方法返回一個FileOutputStream堪遂,得到此對象就可以使用Java流的方式將數(shù)據(jù)寫入到文件中了。
- 讀:使用openFileInput("")方法方輝一個FileInputStream對象萌庆,得到這個通過Java流的方式就可以將數(shù)據(jù)讀出來了溶褪。
public class MainActivity extends AppCompatActivity {
//布局文件很簡單,只需要一個EditText組件
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.edit);
//活動創(chuàng)建時從文件中讀取數(shù)據(jù)
String inputText = load();
if (!TextUtils.isEmpty(inputText)){//檢測傳入的字符串是否為null或為空字符串
edit.setSelection(inputText.length());//設置光標位于末尾
edit.setText(inputText);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
String inputText = edit.getText().toString();
//活動銷毀時寫入文件
save(inputText);
}
public void save(String inputText){
FileOutputStream out = null;
BufferedWriter writer = null;
try {
//openFileOutput("data", Context.MODE_PRIVATE)方法第一個參數(shù)為文件名践险,第二個參數(shù)為文件操作模式:MODE_PRIVATE指同名文件覆蓋猿妈,MODE_APPEND指同名文件追加。
//所有文件默認存儲在這條路徑下/data/data/<package name>/files/data
out = openFileOutput("data", Context.MODE_PRIVATE);
//java流操作
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputText);
}catch (IOException e){
e.printStackTrace();
}finally {
try{
if (writer != null){
writer.close();
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
public String load(){
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try{
//openFileInput("data"只有一個參數(shù)"data"巍虫,即文件名
in = openFileInput("data");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
//reader.readLine()讀取一個文本行彭则,此方法是按行讀即一行一行的讀
while ((line = reader.readLine())!= null){
content.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
return content.toString();
}
}
SharedPreferences
SharedPreferences存儲流程:
獲取SharedPrecences對象:
方法一:Context類的getSharedPreferences()
方法二:Activity類的getPreference()
方法三:PreferenceManager類的getDefultSharedPreferences()調用SharedPreferences對象的edit()方法來獲取一個SharedPrefences.Editor對象
使用putXX()向Editor對象添加數(shù)據(jù),或用getXX()方法得到數(shù)據(jù)
僅在添加數(shù)據(jù)時占遥,調用apply()方法將添加的數(shù)據(jù)提交俯抖,從而完成數(shù)據(jù)存儲操作
//布局也很簡單,加兩個按鈕就行了
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private String TAG = "MainActivity";
private Button save_btn;
private Button restore_btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save_btn = (Button) findViewById(R.id.save_btn);
restore_btn = (Button) findViewById(R.id.restore_data);
save_btn.setOnClickListener(this);
restore_btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.save_btn:
//getSharedPreferences("data",MODE_PRIVATE)方法參數(shù):
//"data"為文件名瓦胎,MODE_PRIVATE為唯一參數(shù)表示只有當前應用才可以對這個SharedPrefences文件進行讀寫芬萍。
SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
editor.putString("name","Tom");
editor.putInt("age",23);
editor.putBoolean("married",false);
editor.apply();
break;
case R.id.restore_data:
SharedPreferences preferences = getSharedPreferences("data",MODE_PRIVATE);
String name = preferences.getString("name","data is bull");
int age = preferences.getInt("age",-1);
boolean married = preferences.getBoolean("married",false);
Log.d(TAG,"name is " + name);
Log.d(TAG, "age is " + age);
Log.d(TAG, "married is " + married);
break;
default:
break;
}
}
}
SQLite數(shù)據(jù)庫存儲
SQLite是Android內置的數(shù)據(jù)庫
- 定義一個SQLiteOpenHelper幫助類(此類的實例有兩個方法
getReadableDatabase()
、getWritableDatabase()
這兩個方法都可以打開數(shù)據(jù)庫凛捏,不同的是當數(shù)據(jù)庫不可寫入時担忧,getReadableDatabase()
方法返回的對象將以只讀的方式去打開數(shù)據(jù)庫芹缔,而getWritableDatabase()
方法則會出現(xiàn)異常) - 在Activity中實例化SQLiteOpenHelper對象
- 調用
getReadableDatabase()
或getWritableDatabase()
方法
//定義一個SQLiteOpenHelper
public class MyDatabaseHelper extends SQLiteOpenHelper{
//SQL語句
public static final String CREATE_BOOK = "create table Book ("
+"id integer primary key autoincrement, "
+"author text, "
+"price real, "
+"pages integer, "
+"name text)";
public String DROP_BOOK = "drop table if exists Book";
public String CREATE_CATEGORY = "create table Category ("
+"id integer primary key autoincrement, "
+"category_name text, "
+"category_code integer)";
public String DROP_CATEGORY = "drop table if exists Category";
private Context mContext;
public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
//執(zhí)行SQL語句坯癣,創(chuàng)建表
db.execSQL(CREATE_BOOK);
db.execSQL(CREATE_CATEGORY);
Toast.makeText(mContext,"Create succeeded",Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//此方法用于更新數(shù)據(jù)庫
//執(zhí)行SQL語句,刪除表
db.execSQL(DROP_BOOK);
db.execSQL(DROP_CATEGORY);
onCreate(db);
}
}
//布局就是添加5個相應的button
public class MainActivity extends AppCompatActivity {
//使用ButterKnife
@BindView(R.id.create_database)
Button createDatabase;
@BindView(R.id.add_data)
Button addData;
@BindView(R.id.updata_data)
Button updataData;
private MyDatabaseHelper databaseHelper;
private String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//實例化MyDatabaseHelper的三個參數(shù):
//context最欠;數(shù)據(jù)庫名示罗;允許我們在查詢數(shù)據(jù)的時候返回一個自定義的Cursor惩猫,一般都是null;當前數(shù)據(jù)庫版本號蚜点,可用于對數(shù)據(jù)庫進行升級
databaseHelper = new MyDatabaseHelper(this,"BookStore.db",null,3);
ButterKnife.bind(this);
}
@OnClick({R.id.create_database,R.id.add_data,R.id.updata_data,R.id.delete_data,R.id.select_data})
public void onClick(View v){
switch (v.getId()){
case R.id.create_database:
databaseHelper.getWritableDatabase();
break;
case R.id.add_data:
SQLiteDatabase db = databaseHelper.getWritableDatabase();
// 使用ContentValues傳入相應數(shù)據(jù)
ContentValues values = new ContentValues();
// 開始組裝第一條數(shù)據(jù)
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);//插入第一條數(shù)據(jù)
values.clear();
//開始組裝第二條數(shù)據(jù)
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);//插入第二條數(shù)據(jù)
break;
case R.id.updata_data:
SQLiteDatabase dbUpdata = databaseHelper.getWritableDatabase();
ContentValues valuesUpdata = new ContentValues();
valuesUpdata.put("price",10.99);
dbUpdata.update("Book",valuesUpdata,"name = ?",new String[]{
"The Da Vinci Code"
});
break;
case R.id.delete_data:
SQLiteDatabase dbDelete = databaseHelper.getWritableDatabase();
dbDelete.delete("Book","pages > ?", new String[]{"500"});
break;
case R.id.select_data:
SQLiteDatabase dbSelect = databaseHelper.getWritableDatabase();
//查詢Book表中所有的數(shù)據(jù)
Cursor cursor = dbSelect.query("Book",null,null,null,null,null,null);
if (cursor.moveToFirst()){
do {
//遍歷Cursor對象,取出數(shù)據(jù)并打印
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(TAG, "book name is " + name);
Log.d(TAG, "book author is " + author);
Log.d(TAG, "book price is " + price);
}while (cursor.moveToNext());
}
cursor.close();
break;
}
}
}