/* 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(R.id.button1);
mEditText = (EditText) findViewById(R.id.editText1);
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(R.id.textView1);
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
#cesarnog
#android #sharedPreferences #java #code
#cesarnog
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.