简体   繁体   English

在活动之间使用SharedPreferences

[英]Using SharedPreferences between Activity

I have a configuration page which has a form on it. 我有一个配置页,上面有一个表格。 When the button is pressed, I want to save that value to a SharedPreference. 当按下按钮时,我想将该值保存到SharedPreference。 This SharedPreference value then needs to be accessed from elsewhere in my app. 然后,需要从我的应用程序中的其他位置访问此SharedPreference值。

I am trying to save the value like the below. 我正在尝试保存如下所示的值。 I want to save the collectionID so I can use it elsewhere 我想保存collectionID,以便可以在其他地方使用

public class ConfigPage extends Activity {

    public static final String PREFS_NAME = "MyPrefsFile";

    Button   mButton;
    EditText mEdit;
    String collectionID;
    String key = "GregKey";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.config);
        getActionBar().hide();

        mButton = (Button)findViewById(R.id.setCollection);
        mEdit   = (EditText)findViewById(R.id.collectionName);

        mButton.setOnClickListener(
                new View.OnClickListener()
                {
                    public void onClick(View view)
                    {
                        collectionID = mEdit.getText().toString();
                        Log.d("EditText", collectionID);
                        SharedPreferences settings =
                                getSharedPreferences(PREFS_NAME, 0);
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putString(key, collectionID);
                        editor.commit();
                    }
                });

    }
}

Once it has been saved, I then need to access it in another class, however I can't figure out how to do this. 保存后,我需要在另一个类中访问它,但是我不知道该怎么做。 The example above crashes the application at the moment so something isn't quite right 上面的示例目前使应用程序崩溃,因此有些不对劲

I want to save the collectionID so I can use it elsewhere 我想保存collectionID,以便可以在其他地方使用

Use mButton Button onClick event for saving EditText text in SharedPreferences as : 使用mButton Button onClick事件将SharedPreferences EditText文本保存为:

 mButton.setOnClickListener( new View.OnClickListener()
         {
            public void onClick(View view)
             {
                collectionID = mEdit.getText().toString();
                 Log.d("EditText", collectionID);
                 // save value here in SharedPreferences
                 SharedPreferences settings = 
                            ConfigPage.this.getSharedPreferences(PREFS_NAME, 0);
                 SharedPreferences.Editor editor = settings.edit();
                 editor.putString(collectionID, collectionID);
                 editor.commit();
               }
         });

Your crash occurs because your value is null : 您的崩溃是因为您的值为null

String savedID;

You need to add a value to the variable: 您需要为变量添加一个值:

String savedID = "somevalue";

Also, your key is null as long as the Button is not pressed which will also lead to a crash. 此外,只要不按下Button您的键就为空 ,这也会导致崩溃。

The putString(String key, String value) method enables you to store a specific value with a specific key , that can later be used to reaccess the stored value. putString(String key, String value)方法使您可以使用特定的key存储特定的 ,以后可以使用该key重新访问存储的值。

Example: 例:

String key = "somekey";
String value = "yourvaluetostore";

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value); // store the value
editor.commit();

In another Activity: 在另一个活动中:

String key = "somekey";
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);

// get the value "" is default
String value = sharedPreferences.getString(key, ""); 

All you need in the other Activity is the key you stored the value with. 您在其他活动中所需要的就是存储值的键 With this key, you can pull the correct stored value out of the SharedPreferences . 使用此键,可以从SharedPreferences提取正确的存储值。 --> The key is needed to identify the value. -> 需要密钥来标识值。

Since you are using the part of code : 由于您正在使用代码的一部分:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(collectionID, savedID);
editor.commit();

Log.d("Saved as", savedID);

in the onCreate method, that translates to onCreate方法中,

...
editor.putString(null, null);
Log.d("Saved as", null);

Correct your code so that you fill those elements before. 更正您的代码,以便您之前填写这些元素。 I guess you wanted to make the save in the OnClick part 我想您想在OnClick部分进行保存

Yes something its not quite right here because as i see you are saving nothing. 是的,这并不完全正确,因为我看到您没有节省任何费用。 on shared pref you should have a "key" which will be use to identify the saved value in your example it should be something like this 在共享首选项上,您应该有一个“键”,该键将用于标识示例中保存的值,它应该是这样的

public class ConfigPage extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";
public static final String COLLECTIONID_KEY = "COLLECTIONID_KEY";
Button   mButton;
EditText mEdit;
String collectionID;
String savedID;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.config);
    getActionBar().hide();

    mButton = (Button)findViewById(R.id.setCollection);
    mEdit   = (EditText)findViewById(R.id.collectionName);

    mButton.setOnClickListener(
            new View.OnClickListener()
            {
                public void onClick(View view)
                {
                    collectionID = mEdit.getText().toString();
                    Log.d("EditText", collectionID);
                }
            });

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(COLLECTIONID_KEY, collectionID);
    editor.commit();

    Log.d("Saved as", COLLECTIONID_KEY);
}

} }

then to retrieve it : 然后检索它:

SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
String mySavedCollectionID = sharedPreferences.getString(COLLECTIONID_KEY);

and make sure that its done on the Onclick event otherwise you might end up with crash again because after the on-click event in your code the lines below will run anyway and save null! 并确保其在Onclick事件上完成,否则您可能会再次崩溃,因为在代码中的on-click事件之后,下面的行仍将运行并保存null!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用SharedPreferences在两个应用之间共享数据 - Share data between two app using SharedPreferences 在微调器中进行用户选择,将其存储在sharedPreferences中,并在其他活动中使用它 - Taking user selection in a spinner, storing it in sharedPreferences, and using it in another activity 如何使用 sharedpreferences 保存计时器时间并在另一个活动中检索它 - How to save chronometer time and retrieve it in another activity using sharedpreferences 使用GSON将对象保存在SharedPreferences中并从Android Studio中的活动中读取 - Saving an Object in SharedPreferences and Reading it From an Activity in Android Studio Using GSON 通过为活动使用SharedPreferences实现FLAG_KEEP_SCREEN_ON - Implementing FLAG_KEEP_SCREEN_ON by using SharedPreferences for an Activity 使用SharedPreferences在两个不同的应用程序之间发送数据 - Send data between two differents application using SharedPreferences 在另一个活动中检索sharedpreferences字符串 - Retrieving sharedpreferences string in another activity java.lang.RuntimeException:使用SharedPreferences期间无法在Fragment中启动活动ComponentInfo - java.lang.RuntimeException: Unable to start activity ComponentInfo in a Fragment during using SharedPreferences 添加 Firebase 身份验证后,在 Android Studio(登录活动)中使用 SharedPreferences() 方法时出错 - Error Using SharedPreferences() Method In Android Studio (Login Activity) After Adding Firebase Authentication 使用SharedPreferences将数组从Api传递到另一个活动,并添加到已保存的数组 - passing Array from Api to to another activity using SharedPreferences and adding to already saved array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM