将一些临时数据存储到本地。可以分为三类:
接下来对这三类分别进行详细介绍。
文件存储是最基本的存储方式,不对存储内容进行任何格式化处理,所有数据都是原封不动存储到本地文件中,因此适合存储一些简单文本或者二进制数据,如果需要存储一些复杂数据,可以使用Json或XML格式先规范后再进行存储。文件存储位置在data/data/[包名]/[文件名]
。
写入代码:
private void SaveData() {
try {
FileOutputStream dataFile = openFileOutput("dataFile", Context.MODE_PRIVATE);
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(dataFile));
bufferedWriter.write("hello world,存储了数据");
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
打开AndroidStudio,在右下角侧边栏找到Device File Explorer
,搜索你的包名,如com.example.test.testapp
,在该目录下的files
文件夹中找到上述文件,里面就是存储的数据。
读取代码:
private void ReadData() {
try {
FileInputStream dataFile = openFileInput("dataFile");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataFile));
String str=bufferedReader.readLine();
Log.d(TAG, "ReadData: str is "+str);
} catch (IOException e) {
e.printStackTrace();
}
}
SharedPreference是使用键值对来存储数据的,并且支持多种基本类型,比文件存储要更加方便。存储位置为/data/data/
。
private void SaveData() {
SharedPreferences.Editor dataFile = this.getSharedPreferences("dataFile", 0).edit();
dataFile.putString("name","Tom");
dataFile.apply();
}
private void ReadData() {
SharedPreferences dataFile = this.getSharedPreferences("dataFile", 0);
String name = dataFile.getString("name", "");
Log.d(TAG, "ReadData: value is "+name);
}
SQLite是一款轻量级的数据库,安卓自带,运算速度快,占用内存少。
安卓提供了SQLiteOpenHelper
类用于对数据库进行创建和升级。SQLiteOpenHelper类有两个重要的实例方法,getReadableDatabase()
和getWriteableDatabase()
,两种方法都可以打开一个数据库并返回一个可读写的对象,区别在于在数据库不可写入的时候,第一种方法会以只读的方式打开,第二种会抛出异常。数据库会存放在/data/data/[包名]/[databases]
下。下面是创建数据库的代码:
public class BookDB extends SQLiteOpenHelper {
private static final String createSQL="create table book("+
" id integer primary key autoincrement,"+
" author text,"+
" price real,"+
" pages integer,"+
" name text)";
public BookDB(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createSQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
如果想要查看数据库文件,可以在市场中下载插件
Database Navigator
。
BookDB.java:
public class BookDB extends SQLiteOpenHelper {
private static final String createSQL="create table book("+
" id integer primary key autoincrement,"+
" author text,"+
" price real,"+
" pages integer,"+
" name text)";
private static final String createSQL2="create table Category("+
" id integer primary key autoincrement,"+
" category_name text,"+
" category_code integer)";
public BookDB(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createSQL);
db.execSQL(createSQL2);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists Book");
db.execSQL("drop table if exists Category");
onCreate(db);
}
}
MainActivity.java:
private void SaveData() {
BookDB book = new BookDB(this, "Book", null, 2);//这里的版本号设置为2表示我们升级了数据库.
book.getWritableDatabase();
}
private void SaveData() {
BookDB book = new BookDB(this, "Book", null, 2);
SQLiteDatabase writableDatabase = book.getWritableDatabase();
// ContentValues类用于组合多个数据
ContentValues contentValues = new ContentValues();
contentValues.put("name","Tom");
contentValues.put("author","Jac");
contentValues.put("pages","17");
contentValues.put("prices","171");
writableDatabase.insert("Book",null,contentValues);
}
private void UpdateData() {
BookDB book = new BookDB(this, "Book", null, 2);
SQLiteDatabase writableDatabase = book.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("price","1000");
writableDatabase.update("Book",contentValues,"name=?",new String[]{"Love"});
}
private void DeleteData() {
BookDB book = new BookDB(this, "Book", null, 2);
SQLiteDatabase writableDatabase = book.getWritableDatabase();
writableDatabase.delete("Book","pages>?",new String[]{"500"});
}
private void QueryData() {
BookDB book = new BookDB(this, "Book", null, 2);
SQLiteDatabase writableDatabase = book.getWritableDatabase();
Cursor book1 = writableDatabase.query("Book", null, null, null, null, null, null);
if(book1.moveToFirst())
{
do {
String name=book1.getString(book1.getColumnIndex("name"));
String author=book1.getString(book1.getColumnIndex("name"));
String page=book1.getString(book1.getColumnIndex("name"));
String price=book1.getString(book1.getColumnIndex("name"));
}while (book1.moveToNext());
}
}
事务可以保证多个操作都完成或者都不完成。示例如下:
BookDB book = new BookDB(this, "Book", null, 2);
SQLiteDatabase writableDatabase = book.getWritableDatabase();
writableDatabase.beginTransaction();
try {
//在这里执行多个操作
writableDatabase.setTransactionSuccessful();
}catch (Exception ex)
{
Log.d(TAG, "QueryData: Exception");
}finally {
writableDatabase.endTransaction();
}