Android应用开发之持久化存储笔记

date: 2016.09.12; modification:2016.09.13

目录:

1 文件

写文件:


    FileOutputStream fileOut = null;
    try {
        fileOut = openFileOutput("test_file", Context.MODE_PRIVATE);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fileOut));
        writer.write("This is data to write.\n");
        writer.write("This is anther data to write.\n");
        writer.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileOut != null) {
                fileOut.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    String strTest = null;
    FileInputStream fileIn = null;
    try {
        fileIn = openFileInput("test_file");
        BufferedReader reader = new BufferedReader(new InputStreamReader(fileIn));
        strTest = reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileIn != null) {
                fileIn.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Log.d(TAG, "onClick: test: " + strTest);
    

2 SharedPreferences

写:


        SharedPreferences.Editor prefEditor = getSharedPreferences("pref", MODE_PRIVATE).edit();
        prefEditor.putString("name", "Tom");
        prefEditor.putInt("age", 28);
        prefEditor.putBoolean("married", false);
        prefEditor.commit();
    

读:


    SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
    String name = pref.getString("name", "");
    int age = pref.getInt("age", 0);
    boolean married = pref.getBoolean("married", false);
    Log.d(TAG, "name is " + name);
    Log.d(TAG, "age is " + age);
    Log.d(TAG, "married is " + married);

3 SQLite

3.1 打开(创建)数据库


    SQLiteDatabase db = openOrCreateDatabase("stu.db", MODE_PRIVATE, null);

3.2 创建表


    db.execSQL("create table if not exists book ("
            + "id integer primary key autoincrement, "
            + "price real, "
            + "name text)");

3.3 删除表


    db.execSQL("DROP TABLE IF EXISTS book");

3.4 添加数据


    ContentValues values = new ContentValues();
    // 开始组装第一条数据
    values.put("name", "The Da Vinci Code");
    values.put("price", 16.96);
    db.insert("Book", null, values); // 插入第一条数据
    values.clear();
    // 开始组装第二条数据
    values.put("name", "The Lost Symbol");
    values.put("price", 19.95);
    db.insert("Book", null, values); // 插入第二条数据

3.5 删除数据


    db.delete("Book", "name = ?", new String[] { "The Lost Symbol" });

3.6 更新数据


    values = new ContentValues();
    values.put("price", 10.99);
    db.update("Book", values, "name = ?", new String[] { "The Lost Symbol" });

3.7 查询数据


    Cursor cursor = db.query("Book", null, null, null, null, null, null);
    if (cursor.moveToFirst()) {
        do {
            // 遍历Cursor对象,取出数据并打印
            String name   = cursor.getString(cursor.getColumnIndex("name"));
            double price  = cursor.getDouble(cursor.getColumnIndex("price"));
            Log.d(TAG, "book name is " + name);
            Log.d(TAG, "book price is " + price + "\n\n");
            Log.d(TAG, "-------------");
        } while (cursor.moveToNext());
    }
    cursor.close();

Cursor提供的方法为:

方法名称 方法描述
getCount() 获得总的数据项数
isFirst() 判断是否第一条记录
isLast() 判断是否最后一条记录
moveToFirst() 移动到第一条记录
moveToLast() 移动到最后一条记录
move(int offset) 移动到指定记录
moveToNext() 移动到下一条记录
moveToPrevious() 移动到上一条记录
getColumnIndexOrThrow(String columnName) 根据列名称获得列索引
getInt(int columnIndex) 获得指定列索引的int类型值
getString(int columnIndex) 获得指定列缩影的String类型值

3.8 SQL语句方式执行



    //添加数据的方法如下:
    db.execSQL("insert into Book (name, price) values(?, ?)",
            new String[] { "The Da Vinci Code", "16.96" });
    db.execSQL("insert into Book (name, price) values(?, ?)",
            new String[] { "The Lost Symbol", "19.95" });
    //更新数据的方法如下:
    db.execSQL("update Book set price = ? where name = ?",
            new String[] { "10.99", "The Da Vinci Code" });
    //删除数据的方法如下:
    db.execSQL("delete from Book where name = ?", new String[] { "The Da Vinci Code" });
    //查询数据的方法如下:
    db.rawQuery("select * from Book", null);