How to save class object in android sharedPreference?

I would like to save the class object in android sharedpreference. I did a basic search on this question, and I have some answers, for example, making it a serializable object and saving it, but my need is so simple. I would like to keep some user information such as name, address, age and boolean value. I made one custom class for this.

public class User { private String name; private String address; private int age; private boolean isActive; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isActive() { return isActive; } public void setActive(boolean isActive) { this.isActive = isActive; } } 

Thanks.

+8
android sharedpreferences
source share
5 answers
  • Download gson-1.7.1.jar from this link: GsonLibJar

  • Add this library to your android project and customize the build path.

  • Add the following class to your class.

     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<Object>(){} .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 <T> T getObject(String key, Class<T> 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"); } } } } 
  • Create another class by extending the Application class as follows

     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; } } 
  • Add this application class to the Application manifest tag like this.

     <application android:name=".ObjectPreference" android:allowBackup="false" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > ....your activities and the rest goes here </application> 
  • In your main activity, where you wanted to keep the value in a Shared Preference , do something like this.

     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"); } } } 
  • In another action where you wanted to get a value from Preference , do something like this.

     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()); } } 

Hope this can help you. In this answer, I used your class for the "User" link so you can better understand. However, we cannot relay this method if you decide to store very large objects in preference, since we all know that we have a limited memory size for each application in the data directory, so if you are sure that you have only limited data for storage in general preferences you can use this alternative.

Any suggestions on this performance are welcome.

+18
source share

another way is to save each property yourself. Receptions accept only primitive types, so you cannot put a complex object into it.

+1
source share

You can simply add some regular SharedPreferences "name", "address", "age" and "isActive" and just load them when creating the class

0
source share

You can use global class

  public class GlobalState extends Application { private String testMe; public String getTestMe() { return testMe; } public void setTestMe(String testMe) { this.testMe = testMe; } } 

and then find your application tag in the nadroid manifest and add it to it:

  android:name="com.package.classname" 

and you can set and get data from any of your activity using the following code.

  GlobalState gs = (GlobalState) getApplication(); gs.setTestMe("Some String");</code> // Get values GlobalState gs = (GlobalState) getApplication(); String s = gs.getTestMe(); 
0
source share

A simple solution on how to store the input value in SharedPreferences.

You can extend the MainActivity class or another class where you save the “value of what you want to keep”. Put this in the writer and reader classes:

 public static final String GAME_PREFERENCES_LOGIN = "Login"; 

Here, InputClass is entered, and OutputClass is the output class, respectively.

 // This is a storage, put this in a class which you can extend or in both classes: //(input and output) public static final String GAME_PREFERENCES_LOGIN = "Login"; // String from the text input (can be from anywhere) String login = inputLogin.getText().toString(); // then to add a value in InputCalss "SAVE", SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0); Editor editor = example.edit(); editor.putString("value", login); editor.commit(); 

Now you can use it somewhere else, as in other classes. The OutputClass is called below.

 SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0); String userString = example.getString("value", "defValue"); // the following will print it out in console Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString); 
0
source share

All Articles