国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

Android數(shù)據(jù)持久化之Preferences機制詳解

2019-12-12 02:57:45
字體:
來源:轉載
供稿:網(wǎng)友

本文實例講述了Android數(shù)據(jù)持久化之Preferences機制。分享給大家供大家參考,具體如下:

在Android中,實現(xiàn)數(shù)據(jù)持久化有五種方式:Preferences,文件File,I/O操作、SQLite數(shù)據(jù)庫,ContentProvider組件。

下面逐個做一簡單的介紹:

一、Preferences的介紹:

Preferences是一種輕量級的數(shù)據(jù)存儲機制,他將一些簡單的數(shù)據(jù)類型的數(shù)據(jù),包括boolean類型,int類型,float類型,long類型以及String類型的數(shù)據(jù),以鍵值對的形式存儲在應用程序的私有Preferences目錄(/data/data/<包名>/shared_prefs/)中,這種Preferences機制廣泛應用于存儲應用程序中的配置信息。

如下是Preferences的一個簡單代碼:

這個代碼是創(chuàng)建不同權限的數(shù)據(jù)對象:

package com.example.data_sharedpreferences;import android.os.Bundle;import android.app.Activity;import android.content.Context;import android.content.SharedPreferences;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {  private TextView text;  private Button button;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    // 寫入數(shù)據(jù)    writeData();    text = (TextView) findViewById(R.id.text);    button = (Button) findViewById(R.id.button0);    button.setOnClickListener(new OnClickListener() {      @Override      public void onClick(View v) {        // TODO Auto-generated method stub        // 讀取數(shù)據(jù)        readData();      }    });  }  /**   * 寫入數(shù)據(jù)   */  public void writeData() {    // 設置權限為私有MODE_PRIVATE    SharedPreferences sp_p = this.getSharedPreferences("ct_sp_private",        Context.MODE_PRIVATE);    // 通過SharedPreferences對象的編輯器對象Editor來實現(xiàn)存入數(shù)據(jù)    SharedPreferences.Editor editor = sp_p.edit();    // 通過該編輯器函數(shù)設置鍵值    editor.putString("username", "marry_private");    // 提交數(shù)據(jù),并將數(shù)據(jù)寫入xml文件中    editor.commit();    // 設置為只讀    SharedPreferences sp_or = this.getSharedPreferences("ct_sp_private",        Context.MODE_WORLD_READABLE);    sp_or.edit().putString("username", "marry_only_read").commit();    // 設置為只寫    SharedPreferences sp_ow = this.getSharedPreferences("ct_sp_private",        Context.MODE_WORLD_WRITEABLE);    sp_ow.edit().putString("username", "marry_only_write").commit();    // 設置為可讀可寫    SharedPreferences sp_x = this.getSharedPreferences("ct_sp_private",        Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);    sp_x.edit().putString("username", "marry_write_read").commit();  }  /**   * 讀取數(shù)據(jù)   * 通過SharedPreferences對象的鍵key可以獲取到對應key的鍵值value。對于不同類型的鍵值有不同的函數(shù):getBoolean   * ,getInt,getFloat,getLong.   */  public void readData() {    // TODO Auto-generated method stub    text.setText("private_username:"        + this.getSharedPreferences("ct_cp_private", 0).getString(            "username", "marry_private")        + "/r/n"        + "read_username:"        + this.getSharedPreferences("ct_cp_private", 0).getString(            "username", "marry_only_read")        + "/r/n"        + "write_username:"        + this.getSharedPreferences("ct_cp_private", 0).getString(            "username", "marry_only_write")        + "/r/n"        + "write_read_username:"        + this.getSharedPreferences("ct_cp_private", 0).getString(            "username", "marry_write_read") + "/r/n");  }  @Override  public boolean onCreateOptionsMenu(Menu menu) {    // Inflate the menu; this adds items to the action bar if it is present.    getMenuInflater().inflate(R.menu.main, menu);    return true;  }}

下面這個代碼則是實現(xiàn)在另外一個應用中訪問上一個應用,并讀取上面應用的數(shù)據(jù):

package com.example.data_sharedpreferences2;import com.example.data_sharedpreferences2.R;import android.os.Bundle;import android.app.Activity;import android.content.Context;import android.content.pm.PackageManager.NameNotFoundException;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;/** * 該程序的功能是訪問data_sharedpreferences應用 Sharedpreferences訪問另一個應用的條件: * 1、被訪問的應用權限為可讀或者可寫 2、必須要知道被訪問應用的包名 * * @author marry * */public class MainActivity extends Activity {  private TextView text;  private Button button;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    text = (TextView) findViewById(R.id.text);    button = (Button) findViewById(R.id.button0);    button.setOnClickListener(new OnClickListener() {      @Override      public void onClick(View v) {        // 訪問應用1,并讀取應用1的數(shù)據(jù)        try {          // 獲得要訪問應用的context          Context ortherContext = createPackageContext(              "com.example.data_sharedpreferences", 0);          // 通過ortherContext.getSharedPreferences打開應用1的文件          text.setText("private_username:"              + ortherContext.getSharedPreferences(                  "ct_cp_private", 0).getString("username",                  "marry_private")              + "/r/n"              + "read_username:"              + ortherContext.getSharedPreferences(                  "ct_cp_private", 0).getString("username",                  "marry_only_read")              + "/r/n"              + "write_username:"              + ortherContext.getSharedPreferences(                  "ct_cp_private", 0).getString("username",                  "marry_only_write")              + "/r/n"              + "write_read_username:"              + ortherContext.getSharedPreferences(                  "ct_cp_private", 0).getString("username",                  "marry_write_read") + "/r/n");        } catch (NameNotFoundException e) {          // TODO Auto-generated catch block          e.printStackTrace();        }      }    });  }  @Override  public boolean onCreateOptionsMenu(Menu menu) {    // Inflate the menu; this adds items to the action bar if it is present.    getMenuInflater().inflate(R.menu.main, menu);    return true;  }}

使用Preferences時有以下需要注意的地方:

1、 通過Context.getSharedPreferences(String fileName,int mode)方法,可以打開一個xml文件,文件的位置在/data/data/package_name/shared_prefs/fileName.xml,如果不存在,則會自動創(chuàng)建??梢詫υ撐募M行讀寫操作,在應用內(nèi)的各組件之間共享數(shù)據(jù)。如果將mode設置為Context.MODE_WORLD_READ或者Context.MODE_WORLD_WRITE,則還可以被其他應用訪問到。不過這不是android推薦的方式,要實現(xiàn)跨應用共享數(shù)據(jù),推薦的方式是用ContentProvider實現(xiàn)

2、 如果要訪問另一個應用創(chuàng)建的shared_prefs文件,需要滿足2個條件,首先另一個應用要設置MODE_WORLD_READMODE_WORLD_WIRTE權限,并且要知道另一個應用的package_name,然后就可以通過Context.createPackageContext()方法,就可以得到另一個應用的context,然后context.getSharedPreferences()方法,就可以打開shared_prefs文件了。不過這種方法并不推薦

3、 在罕見的情況下,如果既把shared_prefs的權限設置為MODE_PRIVATE,又希望某些其他的應用可以訪問到,那么可以在manifest文件中配置android:user_id(好像是這個屬性),讓多個應用共享USER_ID。因為本質(zhì)上shared_prefs文件是采用linux的權限控制的,MODE_PRIVATE類似于-rw-------,所以如果多個應用使用了同一個USER_ID,自然都對這個文件有訪問權限了

更多關于Android相關內(nèi)容感興趣的讀者可查看本站專題:《Android數(shù)據(jù)庫操作技巧總結》、《Android編程之a(chǎn)ctivity操作技巧總結》、《Android文件操作技巧匯總》、《Android編程開發(fā)之SD卡操作方法匯總》、《Android開發(fā)入門與進階教程》、《Android資源操作技巧匯總》、《Android視圖View技巧總結》及《Android控件用法總結

希望本文所述對大家Android程序設計有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 农安县| 沧州市| 桃园市| 天门市| 特克斯县| 渝北区| 凤冈县| 二连浩特市| 昌都县| 开鲁县| 泸州市| 古蔺县| 铜山县| 凌海市| 专栏| 育儿| 当雄县| 上思县| 北票市| 麻城市| 林甸县| 察雅县| 务川| 淮阳县| 苏尼特右旗| 五华县| 巴楚县| 卓资县| 云霄县| 武夷山市| 四会市| 贡觉县| 郸城县| 措勤县| 白玉县| 敦煌市| 长岛县| 冀州市| 南陵县| 兴文县| 宁南县|