Android How to - Get and set SharedPreferences








The following code shows how to Get and set SharedPreferences.

Example

Main layout xml file

<?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="I'm App1!"
    />
</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
//from   w  ww .j a  v a 2s. c  o  m
public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      SharedPreferences prefs = getSharedPreferences("app1prefs", MODE_PRIVATE);
      String value = "Hello from App1 preference file!";
      prefs.edit().putString("shared_value", value).commit();
   }

   @Override
   public String toString() {
      return "Hello from App1 toString()!";
   }
}
null