SharedPreferences getString returns null though set by editor in AsyncTask

时光总嘲笑我的痴心妄想 提交于 2019-12-19 10:59:10

问题


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" />

回答1:


The problem is that you use the wrong method: getPreferences (int mode). Please refer to the document: http://developer.android.com/reference/android/app/Activity.html#getPreferences(int)

"This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name."

So, in your code, the Preferences file name you used to save your data may be "LoginActivity" because you save it in your LoginActivity class. Then when you get that data in your MainActivity class by using getPreferences (int mode) means you want to get data from a Preferences file named "MainAcitity". So, you must get a null.

How to solve your problem: Use the getSharedPreferences(String, int) method instead of getPreferences (int mode) and give the save Preferences file name in your two Activity class.




回答2:


Use getSharedPreference method instead of getPreference.



来源:https://stackoverflow.com/questions/25968482/sharedpreferences-getstring-returns-null-though-set-by-editor-in-asynctask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!