java Android - 在单独的类中使用共享首选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29047777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:35:34  来源:igfitidea点击:

Android - Using Shared Preferences in separate class?

javaandroidandroid-intentandroid-activity

提问by Gaurav Deshpande

I want to save data using Shared Preferences in android. But I am looking to use separate class to do this task. I have implemented that class like below,

我想在 android 中使用共享首选项保存数据。但我希望使用单独的类来完成此任务。我已经实现了如下所示的类,

import android.content.Context;
import android.content.SharedPreferences;

public class SavePref {

    private Context context;

    public SavePref(Context context){
        this.context = context;
    }

    public void saveInt(String key, int value) {

        SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(key, value);
        editor.commit();

    }

}

But there is an error on getActivity(),

但是有一个错误getActivity()

The method getActivity() is undefined for the type SavePref

How to solve this?
Thanks

如何解决这个问题?
谢谢

回答by Blackbelt

getActivity()is a method of Fragmentnot of your SavePref. In your case the simple fix is to use the Context you are keeping as member variable to retrieve the SharedPreferences. An alternative to your approach is to avoid keeping the context as member variable, linking somehow the shared preferences to an instance of of your SavePrefclass, and have a static method

getActivity()是一种Fragment不属于你的方法SavePref。在您的情况下,简单的解决方法是使用您作为成员变量保留的 Context 来检索SharedPreferences. 您的方法的另一种方法是避免将上下文保留为成员变量,以某种方式将共享首选项链接到类的实例SavePref,并使用静态方法

  public static void saveInt(Context context, String key, int value) {
        SharedPreferences sharedPref = context.getDefaultSharedPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(key, value);
        editor.commit();
    }

and address the method like:

并解决如下方法:

SavePref.saveInt(getActivity(), key, value);

from a Fragmentor

从一个Fragment

SavePref.saveInt(this, key, value);

from an Activity. This way you don't need to instantiate SavePref every time you need to call saveInt, and you can avoid to store a reference to the Context.

Activity. 这样您就不需要在每次需要调用时都实例化 SavePref saveInt,并且可以避免存储对Context.

回答by Mister JJ

I have created a class to do the same thing. This way you can save boolean, int, string data or check if data has been saved in a specific group of preferences for your app.

我创建了一个类来做同样的事情。通过这种方式,您可以保存布尔值、整数、字符串数据或检查数据是否已保存在您的应用程序的特定首选项组中。

So, you need to create a class "DataProccessor.java" and put the content down bellow. Also I'm going to leave some examples about how to use it.

因此,您需要创建一个类“DataProccessor.java”并将内容放在下面。此外,我将留下一些有关如何使用它的示例。

I hope it can helps you

我希望它能帮助你

import android.content.Context;
import android.content.SharedPreferences;

public class DataProccessor {

    private static Context context;

    public DataProccessor(Context context){
        this.context = context;
    }

    public final static String PREFS_NAME = "appname_prefs";

    public boolean sharedPreferenceExist(String key)
    {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        if(!prefs.contains(key)){
            return true;
        }
        else {
            return false;
        }
    }

    public static void setInt( String key, int value) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME,0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(key, value);
        editor.apply();
    }

    public static int getInt(String key) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        return prefs.getInt(key, 0);
    }

    public static void setStr(String key, String value) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME,0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(key, value);
        editor.apply();
    }

    public static String getStr(String key) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        return prefs.getString(key,"DNF");
    }

    public static void setBool(String key, boolean value) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME,0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    public static boolean getBool(String key) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        return prefs.getBoolean(key,false);
    }
}

To use it I'll show you some small examples about how to save a String value in case you want to use it in an Activity, Fragment or Service.

为了使用它,我将向您展示一些关于如何保存字符串值的小示例,以防您想在活动、片段或服务中使用它。

For an Activity

对于活动

 //// To Save a value
 DataProccessor dataProccessor = new DataProccessor(this);
 dataProccessor.setStr("email","[email protected]");

 //// To Retreive a value
 dataProccessor.getStr("email");

For a Fragment

对于一个片段

 //// To Save a value
 DataProccessor dataProccessor = new DataProccessor(getActivity());
 dataProccessor.setStr("email","[email protected]");

 //// To Retreive a value
 dataProccessor.getStr("email");

For a Service

对于服务

 //// To Save a value
 DataProccessor dataProccessor = new DataProccessor(getApplicationContext());
 dataProccessor.setStr("email","[email protected]");

 //// To Retreive a value
 dataProccessor.getStr("email");

回答by M D

change

改变

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

to

SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);

You already have contextthen why should you used getActivity()?

您已经有了上下文,那为什么还要使用getActivity()

Actually getActivity()is used to get context in Fragment.

实际上getActivity()用于获取Fragment.

回答by Yogesh singh Pathania

You can simple create the seprate Constant Class in Your Project and call it very simple way when you need to save or retrive the data..

您可以在您的项目中简单地创建单独的常量类,并在需要保存或检索数据时将其称为非常简单的方法。

class Constant {

    companion object {

        val loginData: String = "LoginData"
        val token: String = "token"
        //create the fuction of shared prefrence
        fun setpref(context: Context): SharedPreferences {
            return context.getSharedPreferences("Table Data", Context.MODE_PRIVATE)

        }
    }
}