[第一行代码(第三版)]第七章总结

[第一行代码(第三版)]第七章总结

1. 数据持久化

1.1 概念

将一些临时数据存储到本地。可以分为三类:

  1. 文件存储
  2. SharedPreference
  3. 数据库存储

接下来对这三类分别进行详细介绍。

1.2 文件存储

1.2.1 介绍

文件存储是最基本的存储方式,不对存储内容进行任何格式化处理,所有数据都是原封不动存储到本地文件中,因此适合存储一些简单文本或者二进制数据,如果需要存储一些复杂数据,可以使用Json或XML格式先规范后再进行存储。文件存储位置在data/data/[包名]/[文件名]

1.2.2 写入

写入代码:

 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文件夹中找到上述文件,里面就是存储的数据。

1.2.3 读取

读取代码:

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();
    }
}

1.3 SharedPreference存储

1.3.1 介绍

SharedPreference是使用键值对来存储数据的,并且支持多种基本类型,比文件存储要更加方便。存储位置为/data/data//shared_prefs

1.3.2 写入

private void SaveData() {
    SharedPreferences.Editor dataFile = this.getSharedPreferences("dataFile", 0).edit();
    dataFile.putString("name","Tom");
    dataFile.apply();
}

1.3.3 读取

private void ReadData()  {
    SharedPreferences dataFile = this.getSharedPreferences("dataFile", 0);
    String name = dataFile.getString("name", "");
    Log.d(TAG, "ReadData: value is "+name);
}

1.4 数据库存储

1.4.1 SQLite数据库介绍

SQLite是一款轻量级的数据库,安卓自带,运算速度快,占用内存少。

1.4.2 创建数据库

安卓提供了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

1.4.3 升级数据库

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();
}

1.4.4 插入数据

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);
}

1.4.5 更新数据

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"});
}

1.4.6 删除数据

private void DeleteData() {
    BookDB book = new BookDB(this, "Book", null, 2);
    SQLiteDatabase writableDatabase = book.getWritableDatabase();
    writableDatabase.delete("Book","pages>?",new String[]{"500"});
}

1.4.7 查询数据

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());
    }
}

1.4.8 事务

事务可以保证多个操作都完成或者都不完成。示例如下:

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();
}

你可能感兴趣的:(第一行代码(第三版))