I have a LoginActivity
which calls an AsyncTask
to post username and password to the server and on response, it will write username to SharedPreferences
(can retrieve the username from SP here) and return to may app's MainActivity
. However, I retrieve the username from SP in MainActivity
, it is null
. Where did I do wrong?
AsyncTask code:
//activity is the context passed from LoginActivity (using "this")
protected void onPostExecute(String result) {
if(result!=null){
try {
JSONTokener jsonParser = new JSONTokener(result);
JSONObject msg = (JSONObject) jsonParser.nextValue();
String data=msg.getString("data");
int code=Integer.parseInt(msg.getString("code"));
if(code==0){
//Write to local storage
SharedPreferences settings = activity.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
JSONTokener dataParser = new JSONTokener(data);
JSONObject dataJSON=(JSONObject) dataParser.nextValue();
editor.putString("acc_username", dataJSON.getString("username"));
if(dataJSON.getString("token")!=null){
editor.putString("acc_token", dataJSON.getString("token"));
}
editor.commit();
//Log.d("TEST",activity.getPreferences(Context.MODE_PRIVATE).getString("acc_username", null));//I can get the username here -- means the post and login request and response are correct.
Intent intent=new Intent(activity, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
activity.startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
MainActivity code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//read login info from device
SharedPreferences settings = getPreferences(MODE_PRIVATE);
String accUsername = settings.getString("acc_username", null);
Log.d("TEST","accUsername="+accUsername);//it is null!
}
Manifest permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />