【问题标题】:How do I call a method from fragment to class?如何从片段调用方法到类?
【发布时间】:2021-08-20 16:53:57
【问题描述】:

我有一个片段,我想调用一个 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);

【问题讨论】:

  • sharedPreferences 为空。
  • 你能分享一下共享偏好初始化吗?
  • 使用editor.commit(); 代替editor.apply();

标签: android android-studio android-fragments


【解决方案1】:

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

getDefaultSharedPreferences(上下文上下文)

获取一个 SharedPreferences 实例,该实例指向给定上下文中首选项框架使用的默认文件。

因此,在 AppConfig 类中,您可以实现一个 void,您可以在其中从不同的活动传递 Context 以获取 getDefaultSharedPreferences

private static Context context;
static SharedPreferences sharedPreferences;

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

}

在拨打updateUserLoginStatus之前,您必须先拨打AppConfig.init()

来自活动 -

     AppConfig.init(this);

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

从片段 -

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

【讨论】:

  • 您可以通过点击复选标记来接受答案 ✓
【解决方案2】:

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

例子-

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

空指针异常表明,你刚刚在你的类中为 appConfig 声明了一个全局变量,但没有初始化它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多