数据存储

标签: Android


文件存储

openFileOutput方法

此方法将数据存储到指定的文件中,2个参数

第一个是文件名,不可以包含路径,第二个是操作模式,如Context.MODE_PRIVATE和Context.MODE_APEND

通过Java流的方式将数据写入文件中

public void save(String inputText) {
    FileOutputStream out = null;
    BufferedWriter writer = null;
    try {
        out = openFileOutput("data", Context.MODE_PRIVATE);
        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 {
        in = openFileInput("data");
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            content.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return content.toString();
}

SharedPreference

将数据存储到SharedPreferences中

3种方法获取SharedPreferences对象

  1. Context类的getSharedPreferences()方法
  2. Activity类的getPreferences()方法
  3. PreferenceManager类的getDefaultSharedPreferences()方法

通过SharedPreferences对象存储数据

    SharedPreferences.Editor editor = new getSharedPreferences("data",Context.MODE_PRIVATE).edit();
    editor.putString/putBoolean...方法添加数据
    editor.apply()提交数据完成数据存储

从SharedPreferences对象读取数据

    SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
    String name = pref.getString("name", "");
    int age = pref.getInt("age", 0);
    boolean married = pref.getBoolean("married", false);

有默认值作为当没有值的值 有一个记住密码的小功能可以学习下: 判断是否已经复选了,是则通过SharedPreferences对象取出数据,否则在按钮的监听事件中处理数据,判断是否需要存储数据

SQLite数据库

通过SQLiteOpenHelper抽象类继承

创建数据库

重写onCreate方法创建数据库和表

public class MyDatabaseHelper extends SQLiteOpenHelper {

public static final String CREATE_BOOK = "create table Book ("
        + "id integer primary key autoincrement, "
        + "author text, "
        + "price real, "
        + "pages integer, "
        + "name text)";
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) {
    db.execSQL(CREATE_BOOK);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}

}

    MyDatabaseHelper dbHelper;
    dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);
    ...
    dbHelper.getWritableDatabase();//创建数据库和表
    ...

当需要更新数据库时,onUpgrade里更改如下,并更改版本为2

 db.execSQL("drop table if exists Book");
 db.execSQL("drop table if exists Category");

添加数据

通过ContentValues对象添加数据

SQLiteDataBase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "accfcx");//第一条记录数据
...
db.insert("Book",null,values);
values.clear();
...//第二条...

更新数据

仍然通过ContentValues对象,不过只是给需要更改的列添加数据,调用

db.update("Book", values, "name = ?", new String[]{"accfcx"});

删除数据

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

查询数据

Cursor cursor = db.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"));
                } while (cursor.moveToNext());
            }
            cursor.close();

LitePay开源库操作数据库

配置LitePal

  1. 在app/build.gradle中添加库依赖

     compile 'com.android.support:appcompat-v7:24.2.1'
    
  2. 在main目录下新建assets目录,新建litepal.xml文件

    <?xml version="1.0" encoding="utf-8"?>
    <litepal>
         <dbname value="BookStore" ></dbname>
    
    
    
     &lt;version value="2" &gt;&lt;/version&gt;
    
    
     &lt;list&gt;
          &lt;mapping class="com.example.litepaltest.Book"&gt;&lt;/mapping&gt;
          &lt;mapping class="com.example.litepaltest.Category"&gt;&lt;/mapping&gt;
    &lt;/list&gt;
    
    </litepal>
  3. 配置AnroidManifest.xml

    <application
        android:name="org.litepal.LitePalApplication"
        ...
    

创建和升级数据库

LitePal采用ORM方式,需要Java bean实体类作为数据库表的映射,新建实体类,再listpal.xml中添加Book到映射模型列表中

Connector.getDatabase();

数据库创建完毕

添加数据

前面使用ContentValues,而LitePal通过给Java Bean继承DataSupport

public class Book extends DataSupport{
    ...
}

给Book表添加数据

Book book = new Book();
book.setName("The Da Vinci Code");
...
book.save();

更新数据

 Book book = new Book();
            book.setPrice(14.95);
            book.setPress("Anchor");
            book.updateAll("name = ? and author = ?", "The Lost Symbol", "Dan Brown");

删除数据

DataSupport.deleteAll(Book.class, "price < ?", "15");

查询数据

 List<Book> books = DataSupport.findAll(Book.class);