android 資料存放區操作之 SharedPreferences

來源:互聯網
上載者:User

android的資料存放區方式有

1.SharedPreferences

2.檔案儲存體

3.SQLite儲存

4.內容提供器(Content provider)

5.網路

 

1.SharedPreferences

是android用來提供用來儲存簡單的配置資訊的一種方式。是一種key/value關係的資料類型,資料儲存在一個xml檔案中

首先需要建立一個SharedPreferences對象

 SharedPreferences s=getSharedPreferences("filename", 0);

其中 第一個參數為儲存的檔案名稱,在FileExplorer中/data/data/包名/shared_prefs下可以看到對應的檔案

讀檔案 :
s.getString("name", "")

第一個參數為key 第二個為預設值;

    當然還有對應的不同的擷取值的方式

寫檔案:
s.edit() .putString("name", edit_name.getText().toString()) .commit();

s.edit()表示進入編輯狀態

putString()壓入值

commit()提交內容

同樣put也有壓入不同值的方式:

 

全部代碼:

public class main extends Activity {EditText edit_name;Button but_sub;    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                edit_name=(EditText)this.findViewById(R.id.edit_name);        //擷取一個SharedPreferences對象        SharedPreferences s=getSharedPreferences("filename", 0);               edit_name.setText(s.getString("name", ""));         but_sub=(Button)this.findViewById(R.id.but_sub);        but_sub.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stub    SharedPreferences s=getSharedPreferences("filename", 0);s.edit() .putString("name", edit_name.getText().toString())  .commit();}});     }}

Preferences只能在同一包中使用,不能在不同的包使用,儲存的資料以健值的方式明文儲存,適合儲存單一資料型別。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.