SharedPreferences getString returns null though set by editor in AsyncTask

后端 未结 2 1297
太阳男子
太阳男子 2021-01-16 02:19

I have a LoginActivity which calls an AsyncTask to post username and password to the server and on response, it will write username to Shared

相关标签:
2条回答
  • 2021-01-16 02:36

    Use getSharedPreference method instead of getPreference.

    0 讨论(0)
  • 2021-01-16 02:49

    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.

    0 讨论(0)
提交回复
热议问题