Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<ol> <li><p>Download <code>gson-1.7.1.jar</code> from this link: <a href="http://www.java2s.com/Code/Jar/g/Downloadgson171jar.htm" rel="noreferrer">GsonLibJar</a></p></li> <li><p>Add this library to your android project and configure build path.</p></li> <li><p>Add the following class to your package.</p> <pre><code>package com.abhan.objectinpreference; import java.lang.reflect.Type; import android.content.Context; import android.content.SharedPreferences; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class ComplexPreferences { private static ComplexPreferences complexPreferences; private final Context context; private final SharedPreferences preferences; private final SharedPreferences.Editor editor; private static Gson GSON = new Gson(); Type typeOfObject = new TypeToken&lt;Object&gt;(){} .getType(); private ComplexPreferences(Context context, String namePreferences, int mode) { this.context = context; if (namePreferences == null || namePreferences.equals("")) { namePreferences = "abhan"; } preferences = context.getSharedPreferences(namePreferences, mode); editor = preferences.edit(); } public static ComplexPreferences getComplexPreferences(Context context, String namePreferences, int mode) { if (complexPreferences == null) { complexPreferences = new ComplexPreferences(context, namePreferences, mode); } return complexPreferences; } public void putObject(String key, Object object) { if (object == null) { throw new IllegalArgumentException("Object is null"); } if (key.equals("") || key == null) { throw new IllegalArgumentException("Key is empty or null"); } editor.putString(key, GSON.toJson(object)); } public void commit() { editor.commit(); } public &lt;T&gt; T getObject(String key, Class&lt;T&gt; a) { String gson = preferences.getString(key, null); if (gson == null) { return null; } else { try { return GSON.fromJson(gson, a); } catch (Exception e) { throw new IllegalArgumentException("Object stored with key " + key + " is instance of other class"); } } } } </code></pre></li> <li><p>Create one more class by extending <code>Application</code> class like this</p> <pre><code>package com.abhan.objectinpreference; import android.app.Application; public class ObjectPreference extends Application { private static final String TAG = "ObjectPreference"; private ComplexPreferences complexPrefenreces = null; @Override public void onCreate() { super.onCreate(); complexPrefenreces = ComplexPreferences.getComplexPreferences(getBaseContext(), "abhan", MODE_PRIVATE); android.util.Log.i(TAG, "Preference Created."); } public ComplexPreferences getComplexPreference() { if(complexPrefenreces != null) { return complexPrefenreces; } return null; } } </code></pre></li> <li><p>Add that application class in your manifest's <code>application</code> tag like this.</p> <pre><code>&lt;application android:name=".ObjectPreference" android:allowBackup="false" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; ....your activities and the rest goes here &lt;/application&gt; </code></pre></li> <li><p>In Your Main Activity where you wanted to store value in <code>Shared Preference</code> do something like this.</p> <pre><code>package com.abhan.objectinpreference; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { private final String TAG = "MainActivity"; private ObjectPreference objectPreference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); objectPreference = (ObjectPreference) this.getApplication(); User user = new User(); user.setName("abhan"); user.setAddress("Mumbai"); user.setAge(25); user.setActive(true); User user1 = new User(); user1.setName("Harry"); user.setAddress("London"); user1.setAge(21); user1.setActive(false); ComplexPreferences complexPrefenreces = objectPreference.getComplexPreference(); if(complexPrefenreces != null) { complexPrefenreces.putObject("user", user); complexPrefenreces.putObject("user1", user1); complexPrefenreces.commit(); } else { android.util.Log.e(TAG, "Preference is null"); } } } </code></pre></li> <li><p>In another activity where you wanted to get the value from <code>Preference</code> do something like this.</p> <pre><code>package com.abhan.objectinpreference; import android.app.Activity; import android.os.Bundle; public class SecondActivity extends Activity { private final String TAG = "SecondActivity"; private ObjectPreference objectPreference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); objectPreference = (ObjectPreference) this.getApplication(); ComplexPreferences complexPreferences = objectPreference.getComplexPreference(); android.util.Log.i(TAG, "User"); User user = complexPreferences.getObject("user", User.class); android.util.Log.i(TAG, "Name " + user.getName()); android.util.Log.i(TAG, "Address " + user.getAddress()); android.util.Log.i(TAG, "Age " + user.getAge()); android.util.Log.i(TAG, "isActive " + user.isActive()); android.util.Log.i(TAG, "User1"); User user1 = complexPreferences.getObject("user", User.class); android.util.Log.i(TAG, "Name " + user1.getName()); android.util.Log.i(TAG, "Address " + user1.getAddress()); android.util.Log.i(TAG, "Age " + user1.getAge()); android.util.Log.i(TAG, "isActive " + user1.isActive()); } } </code></pre></li> </ol> <p>Hope this can help you. In this answer I used your class for the reference 'User' so you can better understand. However we can not relay on this method if you opted to store very large objects in preference as we all know that we have limited memory size for each app in data directory so that if you are sure you have only limited data to store in shared preference you can use this alternative.</p> <p>Any suggestions on this implement are most welcome.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload