一、SharedPreferences:一种清醒的存储方式,基于XML存储key-value键值对方式的数据。
SharedPreferences对象本身只能获取数据,而不能存储和修改数据,存储修改只能通过Editor对象实现。、
实现步骤:
1、获取SharedPreferences对象。
2、获取SharedPreferences.Editor对象。
3、通过Editor接口的pubXxx方法保存key-value对,其中Xxx表示不同的数据类型。
4、通过Editor对象的commit方法提交数据。
示例:
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><Buttonandroid:id="@+id/btn_save"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="保存数据" /><Buttonandroid:id="@+id/btn_load"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="获取数据" /><Buttonandroid:id="@+id/btn_remove"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="删除数据" /></LinearLayout>
main_activity.java
package com.example.sharedpreferencesdemo1;import android.app.Activity; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast;public class MainActivity extends Activity{Button btn_save;Button btn_load;Button btn_remove;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn_save = (Button) findViewById(R.id.btn_save);btn_load = (Button) findViewById(R.id.btn_load);btn_remove = (Button) findViewById(R.id.btn_remove);btn_save.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stub//获取SharedPreferences对象SharedPreferences pref = getSharedPreferences("mypreferences", MODE_PRIVATE);//获取Editor对象Editor editor = pref.edit(); //写入数据editor.putString("name", "张三");editor.putInt("age", 30);editor.putLong("time", System.currentTimeMillis());editor.putBoolean("state", true);//保存数据 editor.commit();//提示Toast.makeText(MainActivity.this, "保存成功", 3).show();}});//读取数据btn_load.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {//获取SharedPreferences对象SharedPreferences pref = getSharedPreferences("mypreferences", MODE_PRIVATE);//通过getString方法获取值,第一个参数为key值,第二个为未取到值时给的默认值System.out.println(pref.getString("name", ""));System.out.println(pref.getInt("age", 0));System.out.println(pref.getBoolean("state", false));System.out.println(pref.getLong("time", 0));}});btn_remove.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stub//获取SharedPreferences对象SharedPreferences pref = getSharedPreferences("mypreferences", MODE_PRIVATE);//获取editor对象Editor editor = pref.edit();// 通过key值移除数据editor.remove("name");//提交数据 editor.commit();}});}}
实现保存,读取和删除数据。