Android SharedPreferences store private primitive data in key-value pairs. The data saved using SharedPreferences will still be available in the device even if your application is killed. Types of data that can be saved are booleans, floats, ints, longs, and strings. One use of Android SharedPreferences is to store data that can be used in different activity of your application.
Here’s the code:
package com.example.SharedPreferencesExample; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class SharedPreferencesExampleActivity extends Activity { /** Called when the activity is first created. */ SharedPreferences settings; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { //our edit text/text box where the name will be entered final EditText name_edit_text = (EditText) this.findViewById(R.id.NameTxt); //getSharedPreferences() – Use this if you need multiple preferences files identified by name, //which you specify with the first parameter. //our preference name will be codeofaninja_shared_pref settings = getSharedPreferences(“codeofaninja_shared_pref”, 0); View.OnClickListener handler = new View.OnClickListener(){ public void onClick(View v) { switch (v.getId()) { case R.id.SaveBtn: //get entered value and set to a variable String name_input = name_edit_text.getText().toString(); //empty edit text field name_edit_text.setText(“”); //SAVE shared pref value SharedPreferences.Editor editor = settings.edit(); editor.putString(“name”, name_input); editor.commit(); //show button after saving Toast.makeText(SharedPreferencesExampleActivity.this, “You entered: “ + name_input, Toast.LENGTH_SHORT) .show(); break; case R.id.ShowSavedBtn: //RETRIEVE/load the saved shared pref value String name = settings.getString(“name”, null); Toast.makeText(SharedPreferencesExampleActivity.this, “Saved Name is: “ + name, Toast.LENGTH_LONG) .show(); break; } } }; //we will set the listeners findViewById(R.id.SaveBtn).setOnClickListener(handler); findViewById(R.id.ShowSavedBtn).setOnClickListener(handler); }catch(Exception e){ Log.e(“SharedPreferences Example”, e.toString()); } } }
Our XML Layout:
<?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” > <EditText android:layout_width=“198dp” android:layout_height=“50sp” android:text=“” android:id=“@+id/NameTxt” android:singleLine=“true”> </EditText> <Button android:id=“@+id/SaveBtn” android:layout_width=“198dp” android:layout_height=“wrap_content” android:text=“Save Name” > </Button> <Button android:id=“@+id/ShowSavedBtn” android:layout_width=“198dp” android:layout_height=“wrap_content” android:layout_alignRight=“@+id/SaveBtn” android:text=“Show Saved Name” > </Button> </LinearLayout>
When you run this code:
Entered something on the edit text:
Tapping “Save Name” button will clear the edit text and save the value on the SharedPreferences
Tapping “Show Saved Name” button, it will retrieve the saved value:
Just in case you want to download the code:
SharedPreferences Manager Class
Today I’m going to talk about how I manage Android SharedPreferences in my application. Not a long time ago, I posted about SharedPreferences, so you can take a look back if you don’t have any idea yet about SharedPreferences.
I basically used the setter and getter methods, which has been regarded as “evil” by many developers. I’m just a self thought programmer, I’m open to any suggestions by you guys especially if you are an advanced developer or knows a better implementation.
I feel convenient using this class, you can instantly write and read your SharedPreference values, especially if you choose to store several SharedPref values for your app. You just have to pass the context and then bam! You can use it even for a non-activity class.
How To Use?
Just the common way, instantiate:
// make it a member variable SharedPreferencesManager SharedPrefMgr; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // create an instance SharedPrefMgr = new SharedPreferencesManager(this); // …
Write:
//just an example String username = “ninjazhai”; SharedPrefMgr.setUsername(username);
Read:
String curr_username = SharedPrefMgr.getUsername();
SharedPreferencesManager Class
Just an example of my SharefPreferencesManager Class.
import android.content.Context; import android.content.SharedPreferences; public class SharedPreferencesManager { Context mContext; SharedPreferences settings; SharedPreferences.Editor editor; public SharedPreferencesManager(Context mContext) { settings = mContext.getSharedPreferences(“my_shared_prefs”, 0); editor = settings.edit(); } // —– firstname —– public String getFirstname() { return settings.getString(“firstname”, null); } public void setFirstname(String firstname) { editor.putString(“firstname”, firstname); editor.commit(); } // —– lastname —– public String getLastname() { return settings.getString(“lastname”, null); } public void setLastname(String lastname) { editor.putString(“lastname”, lastname); editor.commit(); } // —– username —– public String getUsername() { return settings.getString(“username”, null); } public void setUsername(String username) { editor.putString(“username”, username); editor.commit(); } // —– folder name —– public String getFolderName() { return settings.getString(“folder_name”, null); } public void setFolderName(String folder_name) { editor.putString(“folder_name”, folder_name); editor.commit(); } // —– debug mode —– public boolean getDebugMode() { return settings.getBoolean(“debug_mode”, false); } public void setDebugMode(boolean debug_mode) { editor.putBoolean(“debug_mode”, debug_mode); editor.commit(); } // … you can add more here … }