exampleuse SharedPreferences
exampleuse.java
/* * to access from: data/data/com.android.SharedPreferences/share_prefs */ public class exampleuse extends Activity { public final static String COLUMN_NAME ="name"; public final static String COLUMN_MOBILE ="mobile"; exampleHelper sp; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.main); sp = new exampleHelper(this, "contacts"); //1. to store some value sp.putValue(COLUMN_NAME, "Mr WANG"); sp.putValue(COLUMN_MOBILE, "XXXXXXXXXX"); //2. to fetch the value String name = sp.getValue(COLUMN_NAME); String mobile = sp.getValue(COLUMN_MOBILE); TextView tv = new TextView(this); tv.setText("NAME:"+ name + "\n" + "MOBILE:" + mobile); setContentView(tv); } }
exampleHelper
public class exampleHelper { SharedPreferences sp; SharedPreferences.Editor editor; Context context; public exampleHelper(Context c,String name){ context = c; sp = context.getSharedPreferences(name, 0); editor = sp.edit(); } public void putValue(String key, String value){ editor = sp.edit(); editor.putString(key, value); editor.commit(); } public String getValue(String key){ return sp.getString(key, null); } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>