数据持久化就是指将那些内存中的瞬时数据保存到存储设备中,保证即使在手机或电脑关机的情况下,这些数据也不会丢失。保存在内存中的数据是处于瞬时状态的,而保存在存储设备中的数据是处于持久状态的,持久化技术则提供了一种机制可以让数据在瞬时状态和持久状态之间进行转换
文件存储
文件存储流程:
- 写:使用openFileOutput("",Context.MODE_PRIVATE)方法返回一个FileOutputStream,得到此对象就可以使用Java流的方式将数据写入到文件中了。
- 读:使用openFileInput("")方法方辉一个FileInputStream对象,得到这个通过Java流的方式就可以将数据读出来了。
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);
//活动创建时从文件中读取数据
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)方法第一个参数为文件名,第二个参数为文件操作模式:MODE_PRIVATE指同名文件覆盖,MODE_APPEND指同名文件追加。
//所有文件默认存储在这条路径下/data/data//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"只有一个参数"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对象添加数据,或用getXX()方法得到数据
仅在添加数据时,调用apply()方法将添加的数据提交,从而完成数据存储操作
//布局也很简单,加两个按钮就行了
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)方法参数:
//"data"为文件名,MODE_PRIVATE为唯一参数表示只有当前应用才可以对这个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数据库存储
SQLite是Android内置的数据库
- 定义一个SQLiteOpenHelper帮助类(此类的实例有两个方法
getReadableDatabase()
、getWritableDatabase()
这两个方法都可以打开数据库,不同的是当数据库不可写入时,getReadableDatabase()
方法返回的对象将以只读的方式去打开数据库,而getWritableDatabase()
方法则会出现异常) - 在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) {
//执行SQL语句,创建表
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) {//此方法用于更新数据库
//执行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的三个参数:
//context;数据库名;允许我们在查询数据的时候返回一个自定义的Cursor,一般都是null;当前数据库版本号,可用于对数据库进行升级
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传入相应数据
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);//插入第二条数据
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表中所有的数据
Cursor cursor = dbSelect.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(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;
}
}
}