Android資料存放區之SharedPreferences

來源:互聯網
上載者:User

標籤:android   style   blog   http   io   os   ar   java   sp   

SharedPreferences是一種輕型的資料存放區方式,基於XML檔案儲存體key-value pairs索引值對資料,通常用來儲存一些簡單的配置資訊。SharedPreferences對象本身只能擷取資料而不支援儲存和修改,儲存修改是通過Editor對象實現。每一個 SharedPreferences 檔案都是由framework管理的並且可以是私人或者可共用的。 

資料存放區

建立一個Android項目,在MainActivity的onCreate方法中,調用getSharedPreferences方法,需要注意的是,如果已經存在檔案則不會建立,如果索引值對不存在則會繼續添加到裡面,如果存在名字相同,值不同則會覆蓋原有的值。

        Context context=MainActivity.this;        SharedPreferences shared=context.getSharedPreferences("Test", MODE_PRIVATE);        Editor editor=shared.edit();        editor.putString("Name", "FlyElephant");        editor.putInt("Age", 24);        editor.putBoolean("IsMarried", false);        editor.commit();

 儲存完之後這個時候之後就發現,檔案夾下多了一個Test.xml,全路徑應該是data/data/com.example.preference/shared_prefs/Test.xml

匯出之後發現xml中內容為:

<?xml version=‘1.0‘ encoding=‘utf-8‘ standalone=‘yes‘ ?><map><string name="Name">FlyElephant</string><int name="Age" value="24" /><boolean name="IsMarried" value="false" /></map>
顯示資料

設定一個按鈕點擊事件loadData

   public void loadData(View view){    SharedPreferences shared=MainActivity.this.getSharedPreferences("Test", MODE_PRIVATE);        EditText editText=(EditText) findViewById(R.id.edit_sharedName);        editText.setText(shared.getString("Name", ""));        EditText editAge=(EditText) findViewById(R.id.edit_sharedAge);        String ageString=String.valueOf(shared.getInt("Age", 0));        editAge.setText(ageString);    }

 資料顯示結果:

刪除節點

點擊第二個按鈕,執行的事件:

   public void deleteNode(View view) {    SharedPreferences shared=MainActivity.this.getSharedPreferences("Test", MODE_PRIVATE);    Editor editor=shared.edit();    editor.remove("Age");    editor.commit();    Toast.makeText(MainActivity.this, "刪除成功",Toast.LENGTH_SHORT).show();}

效果如下:

刪除檔案

根據路徑,調用一下File就直接刪除了這個檔案:

    public void deleteFile(View view){    String pathString="/data/data/"+getPackageName()+"/shared_prefs";    File file=new File(pathString,"Test.xml");    Log.i("com.example.preference",pathString);    if (file.exists()) {file.delete();}      Toast.makeText(MainActivity.this, "檔案刪除成功",Toast.LENGTH_SHORT).show();    }

  Android初學中,白天公司搞.NET,晚上回來搞Android,感覺回到了大學,感覺挺好~

Android資料存放區之SharedPreferences

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.