简体   繁体   English

Android Sharedpreferences传递变量值

[英]Android Sharedpreferences passing value of variable

How can I pass the value of the variable to other class? 如何将变量的值传递给其他类? I'm using SharedPreference and I don't know if im passing the right value to other class. 我正在使用SharedPreference ,我不知道即时通讯是否将正确的值传递给其他类。 Here's my statement. 这是我的声明。

if (arr != null) {
    int sum = 0;
    for(int i = 0;i<arr.length();i++) {
        listdata.add(arr.get(i).toString());
        String money = arr.getJSONObject(i).getString("amount");
        sum += Integer.parseInt(money);
    }

    SharedPreferences sharedPref1 = getActivity().getSharedPreferences(String.valueOf(sum), Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref1.edit();
    editor.putInt(String.valueOf(sum), sum);
    editor.commit();
}

Here is how I get the SharedPreference in other class. 这是我如何在其他类中获取SharedPreference Is this right? 这是正确的吗?

 SharedPreferences sharedpref1 = getContext().getSharedPreferences(String.valueOf(""), MODE_PRIVATE);
 int budgeted = sharedpref1.getInt(String.valueOf(""), Integer.parseInt(""));

SharedPreference is basically a key-value pair stored locally in the application package storage. SharedPreference基本上是本地存储在应用程序包存储中的键值对。 So you might pick a tag for your SharedPreference in your application. 因此,您可以在应用程序中为SharedPreference选择一个标签。 Lets say, your SharedPreference tag is MySharedPreference . 可以说,您的SharedPreference标记是MySharedPreference

So in case of storing a value in your SharedPreference you need to do this. 因此,在将值存储在SharedPreference中的情况下,您需要这样做。

SharedPreferences sharedPref1 = getActivity().getSharedPreferences("MySharedPreference", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref1.edit();
editor.putInt("TotalSum", sum);  // Pick a key here. 
editor.commit();

And when you're retrieving the preference value from some other class, just do this. 当您从其他类中检索首选项值时,只需执行此操作。

SharedPreferences sharedpref1 = getContext().getSharedPreferences("MySharedPreference", MODE_PRIVATE);
int budgeted = sharedpref1.getInt("TotalSum", 0); // Use the same key you used before to retrieve the data. 

You can use listener to pass data from one class to another 您可以使用侦听器将数据从一个类传递到另一个类

CustomListener listener = new CustomListener();
myClass.setOnSumListener(listener);
------
int sum = listener.getSumValue();

or you can use event bus lib https://github.com/greenrobot/EventBus 或者您可以使用事件总线库https://github.com/greenrobot/EventBus

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM