How to get value of SharedPreferences android

前端 未结 5 1887
我在风中等你
我在风中等你 2021-01-23 02:41

I\'m trying to use SharedPreferences here is what i do

public void StoreToshared(Object userData){
    SharedPreferences mPrefs = getPreferences(MOD         


        
5条回答
  •  隐瞒了意图╮
    2021-01-23 03:21

    The api: getPreferences will use the activity name to create an xml file if not exists. For example, assume StoreToshared method is put in activity: LoginActivity.java, it will create a file: LoginActivity.xml to store your pref data. Hence, when you go into other activity, let say its name is: MainActivity.java, getPreferences will look into file "MainActivity.xml" instead of "LoginActivity.xml", that is why you cannot retrieve your data.

    The solution is to use: getSharedPreferences. Hence your code can be modified as follow:

    public void StoreToshared(Object userData) {

    SharedPreferences mPrefs = getSharedPreferences("FILE_NAME",MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = mPrefs.edit();
    
    Gson gson = new Gson();
    String json = gson.toJson(userData);
    Log.d("data", " Setup --> "+json);
    prefsEditor.putString("userinfo", json);
    prefsEditor.commit();
    

    }

    @Override protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        SharedPreferences mPrefs = getSharedPreferences("FILE_NAME",MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = mPrefs.edit();
    
        String data = mPrefs.getString("userinfo", null);
        Log.i("Text", "Here is the retrieve");
        Log.i("data", " retrieve --> "+data);
    
    }
    

    Hope this help.

提交回复
热议问题