SharedPreferences example in Android

/* Activity for writing data into SharedPreferences */ public class WriteActivity extends Activity { SharedPreferences mSharedPreferences; EditText mEditText; Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mButton = (Button) findViewById(; mEditText = (EditText) findViewById(; mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mSharedPreferences = getSharedPreferences("mySPKey", MODE_PRIVATE); SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putString("myKey", mEditText.getText().toString()); editor.commit(); startActivity(new Intent(WriteActivity.this,ReadActivity.class)); } }); } } /* Activity for reading data from SharedPreferences */ public class SecActivity extends Activity { SharedPreferences mSharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sec_layout); mSharedPreferences = getSharedPreferences("mySPKey", MODE_PRIVATE); TextView tv = (TextView) findViewById(; String savedString = mSharedPreferences.getString("myKey", "default"); tv.setText(savedString); } }
Simple demonstration of how to save and retrieve data from SharedPreferences on Android.

#android #sharedPreferences #java #code


Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.