java - 在 Android Java 中调用另一个类中的函数
问题描述
我一直在寻找这个问题的答案,发现了许多类似的问题,但似乎没有一个足够相似,而且我在网上找到的解决方案都没有解决这个问题。
对于我正在编写的 Android 应用程序,我需要将 Android 首选项保存到数据库中。为了做到这一点,我想创建一个单独的类,其中包含我可以调用的函数来同步、更新等偏好。所以这就是问题所在
- 从 mainActivity 调用 syncSettings 类中的initialSaveSettings()
我现在尝试这样做的方法是调用:
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 开发非常陌生,所以如果我说或问一些愚蠢的问题,这很可能就是为什么......
解决方案
尝试这个:
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();
推荐阅读
- excel - 匹配Excel中四列中一行中的比较值
- html - HTML5 自动播放视频根据导航条件播放和失败
- c# - 如何释放不在列表视图“视野”中的图像控件的内存
- reactjs - 带有 REDUX 错误的 REACT 16 (cdn)
- html - 为什么`min-height`会影响flex布局中div的高度?
- glsl - Buggy 纹理坐标映射
- ios - 无法在ios swift中将文件保存到本地存储
- angular - 具有多个布尔值的 Angular 5 BehaviorSubject
- git - 我应该将 Visual Studio Code 指向哪个 Git.EXE?
- c++ - Xcode:链接器命令失败,退出代码为 1(使用 -v 查看调用)[C++]