Shared preferences from other activity to be call with button

隐身守侯 提交于 2019-12-25 07:24:44

问题


I'm a beginner trying to understand sharedpreferences. Everything is going smoothly as my program of shared preferences run as I want it to be .

My inputs are in activity 1 and using shared preferences, I call them back in activity 2.

But how can I call the inputs from activity 1 to activity 3 using shared preferences by just using a button from activity 2?


回答1:


Store sharedpreference to Constant class and use static variables than set and get values from that class anytime you want.

Setting values in Preference:

MY_PREFS_NAME - a static String variable like: 

public static final String MY_PREFS_NAME = "MyPrefsFile";

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Amit");
 editor.putInt("idName", 888);
 editor.commit();

Retrieve data from preference:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 

    String restoredText = prefs.getString("text", null);
    if (restoredText != null) {
      String name = prefs.getString("name", "No name defined");  //"No name defined" is the default value.
      int idName = prefs.getInt("idName", 0);    //0 is the default value.
    }

check this answer for more details.



来源:https://stackoverflow.com/questions/38899829/shared-preferences-from-other-activity-to-be-call-with-button

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