Android五種數(shù)據(jù)存儲(chǔ)方式

android的五種數(shù)據(jù)存儲(chǔ)方式

  • 文件存儲(chǔ)
  • SharedPreferences
  • SQLite數(shù)據(jù)庫(kù)存儲(chǔ)
  • ContentProvider
  • 網(wǎng)絡(luò)存儲(chǔ)
一、文件存儲(chǔ)

默認(rèn)存儲(chǔ)路徑:/data/data/<PackageName>/files
文件操作模式:MODE_PRIVATE(默認(rèn)):覆蓋、MODE_APPEND:追加

  • 寫入文件
public void save(){
      String data = "save something here";
      FileOutputStream out = null;
      ButteredWriter writer = null;
      try{
            out = openFileOutput("data",Context.MODE_PRIVATE);
            writer = new ButteredWriter(new OutputSreamWriter(out));
            writer.write(data);
      }catch(IOException e){
            e.printStackTrace();
      }finally{
            try{
                  if(writer!=null){
                        writer.close();
                  }
            }catch(IOException e){
                  e.printStackTrace();
       }
}
  • 讀取數(shù)據(jù)
public String load(){
      FileInputStream in = null;
      ButteredReader reader = null;
      StringBuilder builder = new StringBuilder();
      try{
            in = openFileInput("data");
            reader = new ButteredReader(new InputStreamReader(in));
            String line= "";
            while((line = reader.readline()) != null){
                   builder.append();
            }
      }catch(IOException e){
            e.printStackTrace();
      }finally{
            if(reader != null){
                    try{
                          reader.close();
                    }catch(IOException e){
                          e.printStackTrace();
                    }
             }
      }
}
二、SharedPreferences

默認(rèn)存儲(chǔ)路徑:/data/data/<PackageName>/shared_prefs
操作模式:MODE_PRIVATE(默認(rèn)):只有當(dāng)前的應(yīng)用程序才能對(duì)文件進(jìn)行讀寫、MODE_MULTI_PROCESS:用于多個(gè)進(jìn)程對(duì)同一個(gè)SharedPreferences進(jìn)行讀寫。
存儲(chǔ)數(shù)據(jù)格式:鍵值對(duì)

獲取SharedPreferences對(duì)象的方法
  • Context的getSharedPreferences()方法,參數(shù)一是文件名,參數(shù)二是操作模式
  • Activity的getPreferences()方法,參數(shù)為操作模式,使用當(dāng)前應(yīng)用程序包名為文件名
  • PreferenceManager的getDefaultSharedPreferences()靜態(tài)方法,接收Context參數(shù),使用當(dāng)前應(yīng)用程序包名為文件名
存儲(chǔ)數(shù)據(jù)
  • 調(diào)用SharedPreferences對(duì)象的edit()方法獲取一個(gè)SharedPreferences.Editor對(duì)象
  • 向Editor對(duì)象中添加數(shù)據(jù)putBoolean、putString等
  • 調(diào)用commit()方法提交數(shù)據(jù)
SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
editor.putString("name","ZhangSan");
editor.putInt("age",12);
editor.putBoolean("isMarried",false);
editor.commit();
從SharedPreferences文件中讀取數(shù)據(jù)
SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE);
String name = pref.getString("name");
int age = pref.getInt("age");
boolean isMarried = pref.getBoolean("isMarried");
三、SQLite數(shù)據(jù)庫(kù)存儲(chǔ)

默認(rèn)存儲(chǔ)路徑:/data/data/<PackageName>/databases
數(shù)據(jù)類型

  • integer 整型
  • real 浮點(diǎn)型
  • text 文本類型
  • blob 二進(jìn)制類型
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 context;
    public MyDatabaseHelper (Context context, String name, CursorFactory factory, int version) {  
        super(context, name, factory, version);  
        this.context = context;
    }  

    @Override  
    public void onCreate(SQLiteDatabase db) {  
        db.execSQL(CREATE_BOOK);          
    }  
      
    //當(dāng)打開數(shù)據(jù)庫(kù)時(shí)傳入的版本號(hào)與當(dāng)前的版本號(hào)不同時(shí)會(huì)調(diào)用該方法  
    @Override  
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {    
    
    }    
}  

在MainActivity中

MyDatabaseHelper helper = new MyDatabaseHelper(this,"BookStore.db",null,1);
 //檢測(cè)到?jīng)]有BookStore這個(gè)數(shù)據(jù)庫(kù),會(huì)創(chuàng)建該數(shù)據(jù)庫(kù)并調(diào)用MyDatabaseHelper中的onCreated方法。
helper.getWritableDatabase(); 
升級(jí)數(shù)據(jù)庫(kù)
public class MyDatabaseHelper extends SQLiteOpenHelper{  
    ......
    //當(dāng)打開數(shù)據(jù)庫(kù)時(shí)傳入的版本號(hào)與當(dāng)前的版本號(hào)不同時(shí)會(huì)調(diào)用該方法  
    @Override  
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {   
          db.execSQL("drop table if exists Book");
          onCreate(db):
    }    
} 

在MainActivity中只需將version改為大于原來版本號(hào)即可。

MyDatabaseHelper helper = new MyDatabaseHelper(this,"BookStore.db",null,2);
helper.getWritableDatabase(); 
向數(shù)據(jù)庫(kù)添加數(shù)據(jù)

insert()方法,參數(shù)一表名,參數(shù)二是在未指定添加數(shù)據(jù)的情況下給某些可為空的列自動(dòng)賦值為NULL,設(shè)置為null即可,參數(shù)三是ContentValues對(duì)象。
MainActivity

SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name","The Book Name");
values.put("author","chen");
values.put("pages",100);
values.put("price",200);
db.insert("Book",null,values);
更新數(shù)據(jù)庫(kù)中的數(shù)據(jù)

update()方法,參數(shù)一是表名,參數(shù)二是ContentValues對(duì)象,參數(shù)三、四是去約束更新某一行或某幾行的數(shù)據(jù),不指定默認(rèn)更新所有。
MainActivity

SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("price",120);
db.update("Book",values,"name= ?",new String[]{"The Book Name"});
從數(shù)據(jù)庫(kù)中刪除數(shù)據(jù)

delete()方法,參數(shù)一是表名,參數(shù)二、三是去約束刪除某一行或某幾行的數(shù)據(jù),不指定默認(rèn)刪除所有。
MainActivity

SQLiteDatabase db = helper.getWritableDatabase();
db.delete("Book","pages> ?",new String[]{"100"});
查詢數(shù)據(jù)庫(kù)中的數(shù)據(jù)

query()方法,參數(shù)一是表名,參數(shù)二是指定查詢哪幾列,默認(rèn)全部,參數(shù)三、四是去約束查詢某一行或某幾行的數(shù)據(jù),不指定默認(rèn)查詢所有,參數(shù)五是用于指定需要去group by的列,參數(shù)六是對(duì)group by的數(shù)據(jù)進(jìn)一步的過濾,參數(shù)七是查詢結(jié)果的排序方式
MainActivity

SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.query("Book",null,null,null,null,null,null);
if(cursor.moveToFirst()){
      do{
            String name = cursor.getString(cursor.getColumnIndex("name");
            String author = cursor.getString(cursor.getColumnIndex("author");
            int pages = cursor.getString(cursor.getColumnIndex("pages");
            double price = cursor.getString(cursor.getColumnIndex("price");
       }while(cursor.moveToNext());
}
cursor.close():
使用SQL語句操作數(shù)據(jù)庫(kù)
//添加數(shù)據(jù)
db.execSQL("insert into Book(name,author,pages,price) values(?,?,?,?) "
            ,new String[]{"The Book Name","chen",100,20});
//更新數(shù)據(jù)
db.execSQL("update Book set price = ? where name = ?",new String[]
            {"10","The Book Name"});
//刪除數(shù)據(jù)
db.execSQL("delete from Book where pages > ?",new String[]{"100"});
//查詢數(shù)據(jù)
db.execSQL("select * from Book",null);
使用事務(wù)操作
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();  //開啟事務(wù)
try{
      ......
      db.insert("Book",null,values);
      db.setTransactionSuccessful();  //事務(wù)成功執(zhí)行
}catch(SQLException e){
      e.printStackTrace();
}finally{
      db.endTransaction();  //結(jié)束事務(wù)
}
四、ContentProvider

ContentProvider主要用于不同的程序之間實(shí)現(xiàn)數(shù)據(jù)共享的功能。

  • 訪問其他應(yīng)用程序中的數(shù)據(jù)

工具類ContentResolver,提供了一系列方法對(duì)數(shù)據(jù)進(jìn)行CRUD操作。

ContentResolver的使用方法

1、內(nèi)容URI
內(nèi)容URI是由權(quán)限和路徑組成的,權(quán)限是用于區(qū)分不同的應(yīng)用程序,一般是以包名來命名。路徑是用于區(qū)分同一個(gè)應(yīng)用程序的不同表。

//包名為com.example.app的表table1訪問路徑
Uri uri  = Uri.parse("content://com.example.app.provider/table1");

2、使用Uri對(duì)象進(jìn)行數(shù)據(jù)操作

  • 查詢
Cursor cursor = getContentResolver().query(uri,null,null,null,null);
if(cursor != null){
      while(cursor.moveToNext()){
            String column1 = cursor.getString(cursor.getColumnIndex("column1"));
            String column2 = cursor.getString(cursor.getColumnIndex("column2"));
      }
      cursor.close();
}
  • 插入
ContentValues values = new ContentValues();
values.put("column1","text");
values.put("column2",1);
getContentResolver().insert(uri,values);
五、網(wǎng)絡(luò)存儲(chǔ)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容