package com.bigfat.sharedpreferencestest; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; public class MainActivity extends ActionBarActivity implements View.OnClickListener { public static final String TAG = "MainActivity"; private Button saveData; private Button restoreData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); saveData = (Button) findViewById(R.id.save_data); restoreData = (Button) findViewById(R.id.restore_data); saveData.setOnClickListener(this); restoreData.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.save_data: SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit(); editor.putString("name", "Tom"); editor.putInt("age", 30); editor.putBoolean("married", false); editor.apply(); break; case R.id.restore_data: SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE); String name = pref.getString("name", ""); int age = pref.getInt("age", 0); boolean married = pref.getBoolean("married", false); Log.d(TAG, "name is " + name); Log.d(TAG, "age is " + age); Log.d(TAG, "married is " + married); break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }