標籤: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