首页 > 解决方案 > 在 Android Java 中调用另一个类中的函数

问题描述

我一直在寻找这个问题的答案,发现了许多类似的问题,但似乎没有一个足够相似,而且我在网上找到的解决方案都没有解决这个问题。

对于我正在编写的 Android 应用程序,我需要将 Android 首选项保存到数据库中。为了做到这一点,我想创建一个单独的类,其中包含我可以调用的函数来同步、更新等偏好。所以这就是问题所在

我现在尝试这样做的方法是调用:

 syncSettings sync = new syncSettings();
 sync.initiateSettingSave();

进入 syncSettings 类:

public class syncSettings extends Context {
      public void initiateSettingsSave(){
            PreferenceManager.setDefaultValues(syncSettings.this, R.xml.root_preferences, false);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
      }
}

等问题是 SharedPreferences 需要扩展 Context 并且为了使其正常工作,Android Studio 给出了将 syncSettings 更改为的错误

public abstract class syncSettings extends Context {

这样做会在调用函数时为 new syncSettings() 带来错误,而将抽象带走会在 syncSettings 类中产生错误。我能做些什么来完成这项工作?如果您需要更多信息,请告诉我。

先感谢您。

编辑:我对 Android 开发非常陌生,所以如果我说或问一些愚蠢的问题,这很可能就是为什么......

标签: javaandroidmethodssharedpreferencespreferences

解决方案


尝试这个:

public class syncSettings {
         private Context context;

         public syncSettings(Context context){
             this.context = context;
         }
        
          public void initiateSettingsSave(){
                PreferenceManager.setDefaultValues(syncSettings.this, R.xml.root_preferences, false);
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
          }
    }

在您的活动中:

syncSettings sync = new syncSettings(this);
 sync.initiateSettingSave();

推荐阅读