-1

I am trying to save objects in Internal storage and it works fine, I can save data, retrieve data, however on official site it says files stored in Internal Storage are removed only when you uninstall your application therefore If I exit from my app and start it again it should be there but I may do something wrong as when I try to retrieve data I got a null object reference exception. Could anyone put me back on the right track please.

public class UserData implements Serializable {

public static User user;
static UserData instance=null;

public static UserData getInstance(){
    if( instance == null )
        instance = new UserData();
    return instance;
}
public static void setUser(User usr){
    user = new User(usr.getNume(),usr.getPhone(),usr.getEmail());
}

public static void saveData(UserData instance,Context ctx,User usr){
    setUser(usr);
        String filename = "User.data";
       ObjectOutput out;
        try {
            File outFile = new File(ctx.getFilesDir(), filename);
            out = new ObjectOutputStream(new FileOutputStream(outFile));
            out.writeObject(instance);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

}

public static UserData loadData(Context ctx){
    ObjectInput in;
    String filename = "User.data";
    UserData ss=null;
    try {
        File outFile = new File(ctx.getFilesDir(), filename);
        in = new ObjectInputStream(new FileInputStream(outFile));
        ss=(UserData) in.readObject();
        in.close();
    } catch (Exception e) {e.printStackTrace();}
    return ss;
}
}

Here is how User class implementation

  public class User {
    private String nume;
    private String phone;
    private String email;

    public User(String nume, String phone, String email) {
        this.nume = nume;
        this.phone = phone;
        this.email = email;
    }

    public String getNume() {
        return nume;
    }

    public String getPhone() {
        return phone;
    }

    public String getEmail() {
        return email;
    }
    }

And below is the call to retrieve data but the object containing params is null

 UserData user = UserData.getInstance();
    user.loadData(Login.this);
    if(user.user != null){ // commenting this line will lead to the inner if and accesing user.user.getNume() will throw a null pointer exception
        if(user.user.getNume() != "null"){
            Log.d("STATE", user.user.toString());
            Intent intent = new Intent(Login.this,MenuRest.class);
            this.startActivity(intent);
        }
    }

Edit As requested below is the stacktrace of the error:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: gabriel.androidf, PID: 30318
java.lang.RuntimeException: Unable to start activity ComponentInfo{gabriel.androidf/gabriel.androidf.activities.Login}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String gabriel.androidf.models.User.getNume()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String gabriel.androidf.models.User.getNume()' on a null object reference
    at gabriel.androidf.activities.Login.onCreate(Login.java:42)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5417) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Application terminated.
  • 2
    show the exception stacktrace – Vladyslav Matviienko Jan 14 '19 at 08:26
  • I am not near laptop at this momment but as soon as i get there will post it, anyway without posting it nothing can be done? As I said calling method user.user.getName() will lead me to an null object reference exception that means user instance or user objects are null so I am not retrieving the same object I inserted in local storage –  Jan 14 '19 at 08:38
  • @Gabriel your User class is not Serializable, so it not saved. Why your user object inside UserData is static? – Alex Jan 14 '19 at 08:49
  • @Alex I used an implementation of an accepted answer from here but that answer was related to external storage and I updated for internal storage, about static user object, yes I didn't update anything to the code cause first wanted to make sure it works, static is not necessary in this case –  Jan 14 '19 at 08:57
  • `As I said calling method user.user.getName()` you never said that. There is no place in your code where you call `getName`. At least you didn't post it. – Vladyslav Matviienko Jan 14 '19 at 09:10
  • There is look at where I said " how I retrieve data"( last portion of code) and in the inner if I just call what you say I didn' said :D. –  Jan 14 '19 at 09:15
  • @VladyslavMatviienko Ok now you also have the stacktrace –  Jan 14 '19 at 11:57
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Radesh Jan 20 '19 at 11:25

1 Answers1

0

It works using this code :

public class UserData implements Serializable {

public  User user;
static UserData instance=null;
private static File myfolder;

public static UserData getInstance(){
    if( instance == null )
        instance = new UserData();
    return instance;
}
public  void setUser(User usr){
    user = new User(usr.getNume(),usr.getPhone(),usr.getEmail());
}
public User getUser(){
    return user;
}

public  void saveData(Activity pContext){
    if(myfolder == null){
        myfolder = pContext.getExternalFilesDir(null);
    }
    ObjectOutput out;
    try {
        File outFile = new File(myfolder,
                "someRandom.data");
        out = new ObjectOutputStream(new FileOutputStream(outFile));
        out.writeObject(instance);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public UserData loadData(Context pContext){
    ObjectInput in;
    if(myfolder == null){
        myfolder = pContext.getExternalFilesDir(null);
    }
    instance = null;
    try {
        FileInputStream fileIn = new FileInputStream(myfolder.getPath() + File.separator + "someRandom.data");
        in = new ObjectInputStream(fileIn);
        instance = (UserData) in.readObject();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return instance;
}
}

And also by setting by making User class implementing Serializable