android - SharedPreferences getString returns null though set by editor in AsyncTask -
i have loginactivity
calls asynctask
post username , password server , on response, write username sharedpreferences
(can retrieve username sp here) , return may app's mainactivity
. however, retrieve username sp in mainactivity
, null
. did wrong?
asynctask code:
//activity context passed 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 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 username here -- means post , login request , response 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 device sharedpreferences settings = getpreferences(mode_private); string accusername = settings.getstring("acc_username", null); log.d("test","accusername="+accusername);//it 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" />
the problem use wrong method: getpreferences (int mode). please refer document: http://developer.android.com/reference/android/app/activity.html#getpreferences(int)
"this calls underlying getsharedpreferences(string, int) method passing in activity's class name preferences name."
so, in code, preferences file name used save data may "loginactivity" because save in loginactivity class. when data in mainactivity class using getpreferences (int mode) means want data preferences file named "mainacitity". so, must null.
how solve problem: use getsharedpreferences(string, int) method instead of getpreferences (int mode) , give save preferences file name in 2 activity class.
Comments
Post a Comment