2-20 Android SharePreferences簡單使用(四)

對於數據的存儲有數據庫存儲,有sharePreferences這些方法

數據庫使用的是sqlite,而後者是將存儲的數據存入xml文件中,這個文件在/data/data/包名/shared_prefs中

我現在有一個很小的例子

兩個EditText,在那裏面寫入數據,然後點擊返回鍵,然後在點擊啓動應用,將會看到,在兩個EditText中內容還依然存在

private EditText eText_num,eText_word;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        eText_num=(EditText)findViewById(R.id.editText1);
        eText_word=(EditText)findViewById(R.id.editText2);
    }
    
    @Override
    protected void onResume() {
    super.onResume();
    SharedPreferences sp=getSharedPreferences("test", MODE_WORLD_READABLE);
    String num=sp.getString("num","");
    String word=sp.getString("word", "");
    eText_num.setText(num);
    eText_word.setText(word);
//     sp.edit().clear();
//     sp.edit().commit();
    }
    @Override
    protected void onPause() {
    super.onPause();
    SharedPreferences sp=getSharedPreferences("test", MODE_WORLD_WRITEABLE);
    Editor editor=sp.edit();
    editor.putString("num", eText_num.getText().toString());
    editor.putString("word", eText_word.getText().toString());
    editor.commit();
    }

發佈了32 篇原創文章 · 獲贊 11 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章