Android数据持久化:SharePreference
生活随笔
收集整理的這篇文章主要介紹了
Android数据持久化:SharePreference
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
- SharePreference:作為Android數(shù)據(jù)持久化的一種,具有一定的便捷性,適合存儲一些體積小的數(shù)據(jù)。
- 存儲數(shù)據(jù)方式:鍵值對的方式,類似于Map;
- 利用SharePreference.Editor對象存儲數(shù)據(jù);
- 利用SharePreferences對象讀取數(shù)據(jù);
- 存儲數(shù)據(jù)
SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();editor.putString("name","Damon");editor.putInt("age",28);editor.putBoolean("sex",false);editor.commit();
- 讀取數(shù)據(jù)
SharedPreferences preferences = getSharedPreferences("data",MODE_PRIVATE);String name = preferences.getString("name",null);Integer age = preferences.getInt("age",18);Boolean sex = preferences.getBoolean("sex",false);
- 實(shí)踐參考代碼:
public class Main2Activity extends AppCompatActivity {private Button writeButton;private Button readButton;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main2);writeButton = (Button) findViewById(R.id.writeButton);readButton = (Button) findViewById(R.id.readButton);writeButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();editor.putString("name","Damon");editor.putInt("age",28);editor.putBoolean("sex",false);editor.commit();}});readButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {SharedPreferences preferences = getSharedPreferences("data",MODE_PRIVATE);String name = preferences.getString("name",null);Integer age = preferences.getInt("age",18);Boolean sex = preferences.getBoolean("sex",false);Log.d("Main2Activity","------->" + name + age + sex);}});}
}
- 相關(guān)xml
<LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/writeButton"android:textAllCaps="true"android:text="Write"/><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/readButton"android:textAllCaps="true"android:text="Read"/></LinearLayout>
- 控制臺數(shù)據(jù)輸出
總結(jié)
以上是生活随笔為你收集整理的Android数据持久化:SharePreference的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android数据持久化:文件存储
- 下一篇: 线程的状态、调度、同步