I’m new to SharedPreferences. I’d like to save user profile using sharedpreferences, and the second time the user goes to profile activity, he should see the details he filled in before. How am I able to do that? Can you please give me some code to do that?
Here’s what I have tried but I don’t know what to put inside if else statements:
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
public class A extends Activity
{
private static final String MY_KEY = "myprefs";
private SharedPreferences myPrefs;
private boolean loggedIn;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.iprofile);
myPrefs = getSharedPreferences(MY_KEY, MODE_PRIVATE);
loggedIn = myPrefs.getBoolean("loggedIn", false); //default to false if the value has not been set
if(loggedIn)
{
//do stuff
}
else
{
//do other stuff
}
}
}
this is my xml file: http://pastebin.com/gXCHpk0E and my java class: http://pastebin.com/NZJ0CR8H
Lets assume, that you have an user class, what looks something like this :
You could create a static utility function to read or write if needed the user in the SharedPreferences of the phone:
If you have that, then you can simply do this in your Activity (in fact all of your activites):
If the users data is stored, then it will return a valid user object. If it is not, it will ask the user until he/she enters acceptable data, and return a valid User object after.