尽管由AsyncTask中的编辑器设置,但SharedPreferences getString返回null [英] SharedPreferences getString returns null though set by editor in AsyncTask

查看:103
本文介绍了尽管由AsyncTask中的编辑器设置,但SharedPreferences getString返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 LoginActivity ,它调用 AsyncTask 将用户名和密码发布到服务器,并在响应时将用户名写入 SharedPreferences (可以在此处从SP检索用户名),然后返回到may app的 MainActivity .但是,我从 MainActivity 中的SP中检索了用户名,它是 null .我在哪里做错了?

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代码:

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代码:

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!
}

清单权限:

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

推荐答案

问题是您使用了错误的方法:getPreferences(int模式).请参考文件: http://developer.android.com/reference/android/app/Activity.html#getPreferences(int)

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)

通过传入此活动的类名称作为首选项名称,它只需调用底层的getSharedPreferences(String,int)方法."

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

因此,在您的代码中,用于保存数据的首选项文件名可能是"LoginActivity",因为您将其保存在LoginActivity类中.然后,当您使用getPreferences(int模式)在MainActivity类中获取数据时,意味着您希望从名为"MainAcitity"的首选项文件中获取数据.因此,您必须输入一个空值.

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.

如何解决您的问题:使用getSharedPreferences(String,int)方法代替getPreferences(int模式),并在两个Activity类中提供保存Preferences文件的名称.

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.

这篇关于尽管由AsyncTask中的编辑器设置,但SharedPreferences getString返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆