如何调用从片段到 class 的方法?

How do I call a method from fragment to class?

我有一个片段,我想调用 AppConfig.class 中的一个方法。但是当我 运行 应用程序出现错误时 " Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' on a null object reference"。我该如何解决这个错误?

这是我在 AppConfig.class

中的代码
 public void updateUserLoginStatus(boolean status){

    SharedPreferences.Editor editor= sharedPreferences.edit();
    editor.putBoolean(context.getString(R.string.pref_is_user_login),status);
    editor.apply();

}

这是我在 Fragment 中的代码

appConfig.updateUserLoginStatus(false);

您需要在调用中创建一个 Appconfig 对象 Activity/fragment。

例子-

Appconfig appconfig = new Appconfig(); appconfig.updateUserLoginStatus(假);

空指针异常表明,您刚刚在 class 中为 appConfig 声明了一个全局变量,但尚未对其进行初始化。

如果您想从所有 activities/fragment 中访问共享首选项作为默认文件名,请考虑使用

getDefaultSharedPreferences(Context context)

Gets a SharedPreferences instance that points to the default file that is used by the preference framework in the given context.

因此,在 AppConfig class 中,您可以实现一个空白,您可以在其中从不同的 Activity 传递 Context 以获得 getDefaultSharedPreferences

private static Context context;
static SharedPreferences sharedPreferences;

public static void init(Context ctx){
    context = ctx;
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

}

在调用 updateUserLoginStatus 之前,您必须调用 AppConfig.init() .

从Activity-

     AppConfig.init(this);

    AppConfig appConfig = new AppConfig();
    appConfig.updateUserLoginStatus(false); 

来自片段 -

     AppConfig.init(getContext());
     AppConfig appConfig = new AppConfig();
     appConfig.updateUserLoginStatus(false);