4

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);
Alex
  • 1,982
  • 4
  • 37
  • 70

7 Answers7

5

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);
3

I'd suggest you to use Dependency Injection pattern.

I usually create Preferences class which exposes getters and setters to quickly read and save values to SharedPreferences. I inject the same instance of Preferences anywhere in the code using Dagger as Dependency Injector.

Why use Singleton object over public static helpers?

If you have a helper class of utility functions that you're using directly, it creates a hidden dependency; you have no control over who can use it, or where. Injecting that same helper class via a stateless singleton instance lets you control where and how it's being used, and replace it / mock it / etc. when you need to.

Read more here.

Example of Preferences class:

@Singleton
public class Preferences {

    private SharedPreferences sharedPreferences;
    private final String NOTIFICATIONS_ENABLED = "NOTIFICATIONS_ENABLED";

    @Inject
    public Preferences(Context context) {
        sharedPreferences = context.getSharedPreferences("Preferences", 0);
    }

    public void setNotificationsEnabled(boolean enabled){
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putBoolean(NOTIFICATIONS_ENABLED, enabled);
        edit.commit();           
    }

    public boolean isNotificationsEnabled(){
        return sharedPreferences.getBoolean(NOTIFICATIONS_ENABLED, true);
    }
}

and how to use it in Activity:

public class MainActivity extends Activity {

    @Inject
    NavigationController navigationController;

    @Inject
    Preferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedObjectGraph.getObjectGraph().inject(this);

        if(preferences.isNotificationsEnabled()){
            // do something
        }
    }
Community
  • 1
  • 1
klimat
  • 24,711
  • 7
  • 63
  • 70
2

You need to just replace one line of code

user = GeneralMethods.getData(SplashScreenActivity.this,value,"userObject");

To

user = GeneralMethods.getData(SplashScreenActivity.this,"userObject",value);
  • I tried what you've suggested and it seems something else is broken. When I create a new user and save it, when I try to get the user's name, i get NULL. Maybe i dont save the object correctly? – Alex Apr 02 '15 at 09:23
  • Did you get string from "String stringUser = gson.toJson(newUser);" this line I checked your code & working fine. –  Apr 02 '15 at 09:33
  • Apparently not, i get only `{ }`. Probably not creating the object correctly. Im using a Singleton as the base `User` class. I will update my question with the relevant data. – Alex Apr 02 '15 at 09:46
0

For getting the data back-

//Creating a shared preference
SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);

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

Hope this helps :)

Ashish Tamrakar
  • 810
  • 10
  • 24
0
public static String getData(Context con, String variable)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
String data = prefs.getString(variable, null);
return data;
}

Gson gson = new Gson();
String json = GeneralMethods.getData(SplashScreenActivity.this,"userObject");
if(json!=null){
  MyObject obj = gson.fromJson(json, MyObject.class);
}
John
  • 8,846
  • 8
  • 50
  • 85
0

You are doing it correctly, but i think you have switched the two fields in the getData method.

You have this method:

public static String getData(Context con, String variable, String defaultValue)
{....}

But you are sending in this:

user = GeneralMethods.getData(SplashScreenActivity.this,value,"userObject");

That means that your variable is this.value and your defaultValue is "userObject". I believe you want to have it the other way around

vonGohren
  • 929
  • 8
  • 22
0

Try this

This will help you to create a class of shared preference and use it any where in any class.

  1. Create a class named as MySharedPreferences

    public class MySharedPreferences
    {
     public static final String mySharedPrefrences = "MyPrefs" ;
     public static SharedPreferences sharedPreferences;
     public static SharedPreferences.Editor editor;
      private static MySharedPreferences instance;
    
    public static MySharedPreferences with(Context context) {
    if (instance == null) {
        instance = new MySharedPreferences(context);
    }
    return instance;
    }
    
    public MySharedPreferences(Context context)
    {
    sharedPreferences=context.getSharedPreferences(mySharedPrefrences, Context.MODE_PRIVATE);
    }
    
    public static String  getUserId(String str_userid)
    {
    if (sharedPreferences!= null) {
        return sharedPreferences.getString(str_userid, "");
    }
    return "";
    }
    
    public void saveUserId(String str_userId_key,String str_userId_value)
    {
    editor = sharedPreferences.edit();
    editor.putString(str_userId_key,str_userId_value);
    editor.commit();
    }
    
    public void clearAllData(Context context)
    {
    sharedPreferences = context.getSharedPreferences(mySharedPrefrences, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear().apply();
    }
    }
    
  2. And use this like

    MySharedPreferences yourPrefrence =MySharedPreferences.with(getActivity());yourPrefrence.saveUserId("str_userId_key",et_title.getText().toString().trim());
    String value = yourPrefrence.getUserId("str_userId_key");
    
Community
  • 1
  • 1
Sunil
  • 3,785
  • 1
  • 32
  • 43