Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - save Object to SharedPreferences and get it anywhere in the app

In my app I have a custom User class which holds some regular data (name etc...). I need to save that object and get it anywhere and anytime in other pages of the app. I made a helper class public final class GeneralMethods with many methods which I use a lot (static, of course).
In order to save the data Im using Gson library. I made this method:

public static void saveData(Context con, String variable, String data)
{
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
    prefs.edit().putString(variable, data).apply();
}

To save an object, I use this method as follows:

Gson gson = new Gson();
String stringUser = gson.toJson(newUser);    
GeneralMethods.saveData(VerificationActivity.this,"userObject",stringUser);

To load the data back, I'm using this static method:

public static String getData(Context con, String variable, String defaultValue)
{
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
    String data = prefs.getString(variable, defaultValue);
    return data;
}

I dont really know how to get the data back, this is what I've done so far:

Gson gson = new Gson();
String user="";
String value="";
user = GeneralMethods.getData(SplashScreenActivity.this,value,"userObject");

Im struggling with the getData method, how do I parse the data from String back to the User type?


EDIT
I tried the suggestions bellow and I always get NULL. Maybe I dont save the object in the right way?


EDIT2
It seems Im not generating the object correctly and therefore nothing is being saved. This is the user "Singleton" class:

public class User implements Serializable {

    private static User userInstance=null; //the only instance of the class
    private static String userName; //userName = the short phone number
    private User(){}

    public static User getInstance(){
        if(userInstance ==null){
            userInstance = new User();
        }
        return userInstance;
    }

    public static User getUserInstance() {
        return userInstance;
    }

    public String getUserName(){
        return this.userName;
    }

    public static void setUserName(String userName) {
        User.userName = userName;
    }

    public static void init(String _userName) {
        User.setUserName(_userName);
    }
}

This is how i setup the object with the relevant data (user name as the constructor parameter):

   User.init(name);

This is how i convert the object to a String:

   Gson gson = new Gson();
    String stringUser = gson.toJson(User.getInstance());
GeneralMethods.saveData(VerificationActivity.this,"userObject",stringUser);
like image 332
Alex Avatar asked Dec 08 '22 04:12

Alex


2 Answers

Replace your existing User class with below

public class User implements Serializable
{

    private static User userInstance = null; // the only instance of the class
    private String userName; // userName = the short phone number
    private User(){}
    public static User getInstance()
    {
        if (userInstance == null)
        {
            userInstance = new User();
        }
        return userInstance;
    }

    public String getUserName()
    {
        return userName;
    }

    public void setUserName(String p_userName)
    {
        userName = p_userName;
    }

    @Override
    public String toString()
    {
        return "User [userName=" + getUserName() + "]";
    }
}

Initialize User Name

User m_user = User.getInstance();
m_user.setUserName(name);

Convert the object to a String

Gson gson = new Gson();
String stringUser = gson.toJson(m_user);
GeneralMethods.saveData(VerificationActivity.this,"userObject",stringUser);
like image 197
Android Team Avatar answered Dec 10 '22 18:12

Android Team


We can do this by using Gson library. And shared preference is accessible through out the application. I have created my own class to access shared pref with getter and setter of all type like String, Int, Object etc.

To use Gson Library, Below is the code. If you want the class that I have created then let me know

You can use gson.jar to store class objects into SharedPreferences. You can downlaod this jar from here https://code.google.com/p/google-gson/downloads/list

Or add GSON dependency in Gradle file

compile 'com.google.code.gson:gson:2.5'

To Save

 Editor prefsEditor = mPrefs.edit();
 Gson gson = new Gson();
 String json = gson.toJson(MyObject);
 prefsEditor.putString("MyObject", json);
 prefsEditor.commit();

To Retreive

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

Hope this helps you Summved

like image 21
Summved Jain Avatar answered Dec 10 '22 18:12

Summved Jain