跨多个类使用 SharedPreferences?

2024-04-28

我有一个 SharedPreferences 目前适用于一类,但不适用于第二类。我想我可能把它称为错误的,因为我得到的错误说:

The method getSharedPreferences(String, int) is undefined for the type CheckPreferences

与 SharedPrefernces 一起正确运行的代码是这样的:

public void loadApp()
{
    setContentView(shc_BalloonSat.namespace.R.layout.main);
    alert = new AlertDialog.Builder(this).create();
    //String returned = "";
    lastpacketsPHP = "";
    pref = getSharedPreferences("shared_prefs", 1);
    prefEditor = pref.edit();
    //prefEditor.putString(lastpacketsPHP, "/* Insert PHP file location here */");
    //prefEditor.commit();

    // These next two lines are used to test the PHP files on the SHC server by determining if PHP is set up correctly.
    prefEditor.putString(lastpacketsPHP, "/* Insert PHP file location here */");
    prefEditor.commit();   

    if (!isNetworkConnected(this))
    {
    showAlert();
    }

    else
    {
    api = new httpAPI(this);
        map = new mapAPI(this);
        dialog = new runDialog(this, api, new runDialog.OnDataLoadedListener()
        {

            public void dataLoaded(String textViewString)
            {
            infoTV = (TextView)findViewById(shc_BalloonSat.namespace.R.id.info);
                infoTV.setText(textViewString);
                assignInfoToInfoTextView();
                assignInfoToHistoryTextView();
            }
        });

        dialog.execute();
    }

    CheckPreferences cp = new CheckPreferences(this, new CheckPreferences.CheckPreferencesListener()
    {

        public void onSettingsSaved()
        {
            // This function let's the activity know that the user has saved their preferences and
            // that the rest of the app should be now be shown.
            check.saveSettings();               
        }

        public void onCancel()
        {
            Toast.makeText(getApplicationContext(), "Settings dialog cancelled", Toast.LENGTH_LONG).show();
        }
    });

    cp.show();
}

在我的另一堂课上,我不知道我是否只是错误地调用了它,或者我是否完全错误地看待它。类如下图所示:

package shc_BalloonSat.namespace;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.View;
import android.widget.CheckBox;

public class CheckPreferences extends Dialog
{
Context shc;
private CheckBox altitudeCheckBox = (CheckBox) findViewById(R.id.altitudeCheckbox);
private CheckBox latitudeCheckbox = (CheckBox) findViewById(R.id.latitudeCheckbox);
private CheckBox longitudeCheckbox = (CheckBox) findViewById(R.id.longitudeCheckbox);
private CheckBox velocityCheckbox = (CheckBox) findViewById(R.id.velocityCheckbox);
private CheckPreferencesListener listener;
SharedPreferences pref;
Editor prefEditor;
String userAltitudePreference;
String userLatitudePreference;
String userLongitudePreference;
String userVelocityPreference;
String userAltitudeChoice;
String userLatitudeChoice;
String userLongitudeChoice;
String userVelocityChoice;

public interface CheckPreferencesListener 
{
public void onSettingsSaved();
public void onCancel();
}

public CheckPreferences(Context context, CheckPreferencesListener l)
{
super(context);
this.setContentView(R.layout.custompreferences);
this.setCancelable(false);
this.setCanceledOnTouchOutside(false);
this.setTitle("Data View Settings");
pref = getSharedPreferences("shared_prefs", 1);
prefEditor = pref.edit();
initOnClick();
}

private void initOnClick()
{
View.OnClickListener click = new View.OnClickListener()
{
    public void onClick(View v)
    {
    switch (v.getId())
    {
            case R.id.saveBtn:
            {
                saveSettings();
                listener.onSettingsSaved();
                dismiss();
                break;
            }

            case R.id.cancelBtn:
            {
                listener.onCancel();
                dismiss();
                break;
            }
    }
    }
};

    // Save Button
    this.findViewById(R.id.saveBtn).setOnClickListener(click);

    // Cancel Button
    this.findViewById(R.id.cancelBtn).setOnClickListener(click);
}

public void saveSettings()
{
// This function is called when the user chooses the save their preferences

if (altitudeCheckBox.isChecked())
{
    userAltitudeChoice = "true";
    prefEditor.putString(userAltitudePreference, userAltitudeChoice);
    prefEditor.commit();   
}

else if (latitudeCheckbox.isChecked())
{
    userLatitudeChoice = "true";
    prefEditor.putString(userLatitudePreference, userLatitudeChoice);
    prefEditor.commit();  
}

else if (longitudeCheckbox.isChecked())
{
    userLongitudeChoice = "true";
    prefEditor.putString(userLongitudePreference, userLongitudeChoice);
    prefEditor.commit();  
}

else if (velocityCheckbox.isChecked())
{
    userVelocityChoice = "true";
    prefEditor.putString(userVelocityPreference, userVelocityChoice);
    prefEditor.commit();  
}

else
{

}

}
}

我上面提到的错误发生在这一行:

pref = getSharedPreferences("shared_prefs", 1);

任何帮助将不胜感激。我很想知道我做错了什么。


当然,SharedPreferences 在多个类中是相同的。它允许您在应用程序中保存和检索原始数据类型的持久键值对。

标准做法是使用一个具有所有静态方法的 Helper 类来保存和检索每种类型的键值对。另外,将所有密钥放在一个静态类 SharedPreferenceKeys 中。它避免了愚蠢的印刷错误。以下是您可以使用的示例类:

    package com.mobisys.android;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;

public class HelperSharedPreferences {

    public static class SharedPreferencesKeys{
        public static final String key1="key1";
        public static final String key2="key2";
    }

    public static void putSharedPreferencesInt(Context context, String key, int value){
        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
        Editor edit=preferences.edit();
        edit.putInt(key, value);
        edit.commit();
    }

    public static void putSharedPreferencesBoolean(Context context, String key, boolean val){
        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
        Editor edit=preferences.edit();
        edit.putBoolean(key, val);
        edit.commit();
    }

    public static void putSharedPreferencesString(Context context, String key, String val){
        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
        Editor edit=preferences.edit();
        edit.putString(key, val);
        edit.commit();
    }

    public static void putSharedPreferencesFloat(Context context, String key, float val){
        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
        Editor edit=preferences.edit();
        edit.putFloat(key, val);
        edit.commit();
    }

    public static void putSharedPreferencesLong(Context context, String key, long val){
        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
        Editor edit=preferences.edit();
        edit.putLong(key, val);
        edit.commit();
    }

    public static long getSharedPreferencesLong(Context context, String key, long _default){
        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getLong(key, _default);
    }

    public static float getSharedPreferencesFloat(Context context, String key, float _default){
        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getFloat(key, _default);
    }

    public static String getSharedPreferencesString(Context context, String key, String _default){
        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(key, _default);
    }

    public static int getSharedPreferencesInt(Context context, String key, int _default){
        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getInt(key, _default);
    }

    public static boolean getSharedPreferencesBoolean(Context context, String key, boolean _default){
        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getBoolean(key, _default);
    }
}

要输入值(例如布尔值),请从活动中调用以下命令:

HelperSharedPreferences.putSharedPreferenceBoolean(getApplicationContext(),HelperSharedPreferences.SharedPreferenceKeys.key1, true);

要获得相同的值,请调用以下命令:

HelperSharedPreferences.getSharedPreferenceBoolean(getApplicationContext(),HelperSharedPreferences.SharedPreferenceKeys.key1, true);

最后一个值是默认值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

跨多个类使用 SharedPreferences? 的相关文章

  • Google Play 商店中基于服务的 Android 应用程序

    我正在开发一个应用程序 该应用程序仅包含一些服务 没有任何活动 即没有 UI 基本上 当用户在他 她的设备上安装应用程序时 我希望有 2 到 3 个服务在后台运行 对此我有几个疑问 应用程序安装后我的服务将如何启动 我的BroadcastR
  • Android Manifest 自动生成无效权限

    我不小心在 Android 清单中输入了无效的权限名称 并且无法将其删除 这是我的清单代码
  • 在代码中旋转按钮(或其中的文本)

    我必须通过编码随机旋转按钮 或里面的文本 它是相同的 API级别低于11是否有button setRotate x 好吧 看了一下 答案是 很复杂 您可以使用旧的动画框架旋转按钮 例如像这样 Button button Button fin
  • 编译后从字节代码中删除注释

    我们正在使用一个包含使用 JAXB 注释进行注释的 bean 的库 我们使用这些类的方式完全不依赖于 JAXB 换句话说 我们不需要 JAXB 也不依赖注释 但是 由于注释存在 它们最终会被处理注释的其他类引用 这要求我将 JAXB 捆绑到
  • 如何将 Android Instrumentation 测试推送到模拟器/设备?

    我正在尝试使用 Ubuntu 9 04 中的命令行 shell 在 Android 模拟器上运行 Webkit 布局测试 adb s emulator 5554 shell am instrument w com android dumpr
  • Android Facebook sdk 3.5 分享对话框

    您好 我正在为 android sdk 3 5 实现 facebook 共享对话框 但是我按照指南没有取得任何成功 FacebookDialog shareDialog new FacebookDialog ShareDialogBuild
  • Android 5.0 Lollipop 中屏幕固定关闭时如何收到通知?

    我有一个在后台运行的应用程序 并在手机上发生特定事件时启动活动 我发现在 Android 5 0 中 当用户使用另一个应用程序打开屏幕固定时 startActivity intent 调用将被完全忽略 我的应用程序不知道该活动尚未启动 因此
  • ListView:防止视图回收

    我有一个使用回收视图的 ListView 我试图阻止视图被回收 所以我使用 setHasTransientState android support v4 view ViewCompatJB setHasTransientState Vie
  • Android CursorAdapter、ListView 和后台线程

    我一直在开发的这个应用程序有包含数兆字节数据的数据库可供筛选 许多活动只是列表视图 通过数据库中的各个级别的数据下降 直到到达 文档 即从数据库中提取并显示在手机上的 HTML 我遇到的问题是 其中一些活动需要能够通过捕获击键并重新运行带有
  • 我的 Android 设备需要安装哪个驱动程序才能运行我的应用程序?

    我购买了 intex mobile 来在真实设备中测试我的 Android 应用程序 然而 该设备不存在于 OEM USB 驱动程序列表中 android 提供的设备列表中 我检查了 intex 官方网站 但不确定到底需要安装哪个驱动程序
  • Android 8.1 中 Activity 自行旋转并恢复正常

    我的应用程序在所有 Android 版本上运行良好 但我注意到在 Android 8 1 0 Oreo 中 当我将屏幕从纵向活动转到横向活动时 以及当我按后退按钮时 它会显示异常行为 屏幕自动从横向旋转并恢复正常 看起来 Activity
  • 需要在 Android 中伪造正在扫描的 NFC 标签

    好的 我有一个应用程序 此应用程序仅在扫描 NFC 标签 任何标签 时才会完成任务 唯一的问题是 我没有任何 nfc 标签 无论如何 我正试图消除对卡的需要 所以我需要的是一种 伪造 使其看起来 就像已扫描 nfc 标签的方法 我可以编写应
  • Android BLE 扫描在后台几分钟后停止

    当我为公司开发新冠肺炎接触者追踪应用程序时 我在后台遇到了 Android 扫描停止问题 这是我尝试过的 添加前台服务 禁用手机中所有与电池相关的优化选项 启用后台运行的应用程序 测试设备 搭载 Android 10 的 Galaxy S2
  • 使用 mupdf android 库导航到特定页面

    我如何使用 muPDF 库导航到特定页面 或者有没有办法让图书馆不记得我最后在那个pdf文件中浏览的是哪一页 Uri uri Uri parse path Intent intent new Intent MainActivity getC
  • 如何在android中画一条曲线?

    我是 Android 新手 正在开发一个关于绘制线条的示例项目 我想画一条连接两点的曲线或高架线 x1 y1 and x2 y2 我试过canvas drawArc 方法 但是RectF内的值drawArc方法只是圆的 x y 中心点 它在
  • android 多关键词搜索

    我的应用程序包含搜索功能 它将搜索数据库内的内容 我的搜索的弱点是 我只能使用一个标签进行搜索 例如我只能搜索 猫 它会返回我的数据库中包含 猫 一词的内容 因为我正在使用LIKE在 select 语句期间进行查询 如何使用多个标签进行搜索
  • 我应该选择的最低 SDK 版本是多少? (截至2018年11月)

    据我所知 android studio 中默认的最小 SDK 设置是 15 我读到我应该增加它 因为没有多少人 或者可能没有 仍在使用该 android 版本 另外 我计划使用 android studio 中的一些新功能 这些功能仅适用于
  • 收到“无法解析上传的APK的AndroidManifest.xml。它是否正确编译?”启用 Google 应用签名后出现错误

    启用后谷歌应用程序签名 https support google com googleplay android developer answer 7384423 hl en 每次我尝试将签名版本 APK 上传到 Play 商店时 都会收到一
  • 制作弹跳动画

    我想做图层的弹跳动画 我已经完成了该图层从右到中心的操作 现在我想将其向后移动一点 然后回到中心 这会产生反弹效果 我想我可以用这样的翻译来做到这一点
  • 改造方法调用可能会产生“java.lang.NullPointerException”

    使用 Retrofit 2 3 0 我在 Android Studio 中收到以下消息 有关如何删除此 IDE 错误消息的任何建议 谢谢 来自Response文档 http square github io retrofit 2 x ret

随机推荐

  • 如何在 gdb 中禁用“键入 继续,或 q 退出”?

    我想要自动化gdb 并且等待用户输入是不可取的 如何禁用消息 Type
  • 是否有用于将“任何文件类型”转换为 TIFF 图像的编程工具包?

    我已经编写了程序的几种变体 该程序的目的是将 任何文件类型 转换为该文件的 TIFF 图像表示形式 就像使用打印机打印一样 我当前正在使用向其发送文件的第三方打印机驱动程序 它会输出 TIFF 图像 这很好 但它要求我使用 Office I
  • 霍夫变换的累加器填充

    我写了一段需要优化的代码 只是想与社区核实一下该代码是否确实是最佳的 它填充霍夫变换的累加器 实际上 我只是复制粘贴了 OpenCV 库中的大部分代码 谢谢 int i j n index for i 0 i
  • 忽略特定值的绘图数据点

    我有一个如下所示的图 我正在尝试找出一种方法来忽略 x 值 0 0 的绘图点 基本上 我希望我的绘图不包含您在左上角看到的那 3 个点 y np array 4 7 6 6 6 4 6 8 6 2 7 2 6 1 5 9 6 4 6 6 x
  • PHPUnit:我如何模拟这个文件系统?

    考虑以下场景 这不是生产代码 class MyClass public function myMethod create a directory path sys get temp dir md5 rand if mkdir path th
  • Kotlin AutoCompleteTextView 适配器项目选择给出不同的值

    所以我在这个项目上使用 Kotlin 我主要使用 Java 所以我试图在 Kotlin 中找到等效项来实现相同的功能 我从数据库中获取 JSONArray 并将其存储在名为的可序列化数据类中Congregation它有以下变量id Int
  • 如何解决22端口连接超时问题

    ssh connect to host bitbucket org port 22 Connection timed out fatal Could not read from remote repository Please make s
  • 如何创建静态字符串数组?

    Note这个问题包含 Rust 1 0 之前的语法 代码无效 但概念仍然相关 如何在 Rust 中创建全局静态字符串数组 对于整数 编译如下 static ONE u8 1 static TWO u8 2 static ONETWO sta
  • 当我不使用 CoreData 时,为什么我的 iOS 或 OSX 应用程序会出现 CoreData 错误?

    我在构建过程中收到以下错误 API 滥用 尝试在非拥有协调器上序列化存储访问 PSC 0x7fb5ae208890 存储 PSC 0x0 CoreData 为什么我的应用程序中出现 CoreData 错误 我没有使用 CoreData 此消
  • 从文件中读取第n行的快速方法

    介绍 我有一个名为的 C 进程MyProcess我称之为nbLines时间 地点nbLines是一个名为的大文件的行数InputDataFile txt在其中可以找到输入数据 例如调用 MyProcess InputDataFile txt
  • 为什么我无法“停用”pyenv / virtualenv?如何“修复”安装

    我是新安装的乌班图16 04并考虑到使用最新版本的开发pandas我安装了Python 3 6 0使用虚拟环境 选择 3 6 0 的一个原因是因为我在某处读到这个版本的 Python 可以原生处理虚拟环境 即无需安装任何其他东西 无论如何安
  • 为什么 AnyVal 不能用于 isInstanceOf 检查?

    我想知道 为什么 AnyVal 不能在 isInstanceOf 检查中使用 这种行为背后的原因是什么 scala gt val c t c Char t scala gt c isInstanceOf AnyVal
  • 在 Windows 任务栏中对单独的进程进行分组

    我有许多逻辑上相关的独立进程 但所有进程都是单独启动的 没有共同的 父 进程 是否可以使它们在 Windows 任务栏中显示为一组 工作样本 这是一些受雷米答案启发的工作代码 using System using System Runtim
  • Angular 4:响应式网格列表

    昨晚开始探索 Angular 4 我只是想知道是否有办法使mat grid listMaterial Design 组件响应式与 Boostrap 如何处理它一样简单 任何人 提前谢谢您 不是纯 html 不过你可以找到一些 html ts
  • 不间断破折号 html [重复]

    这个问题在这里已经有答案了 我知道有一个不间断的空白 nbsp 是否有不间断的破折号 我可以使用这样我的单词就不会在该位置换行 中断 另外 有人可以向我指出一个列表 其中包含在断开句子时优先考虑的字符 例如空格 提前致谢 Use 8209
  • iOS Objective-C 以编程方式获取 VPN IP

    我使用第三方应用程序连接VPN 我们可以在以下位置获取详细信息Settings gt VPN gt information 我怎样才能得到Assigned IP通过 Objective C 在我们的应用程序中以编程方式 NSString a
  • 是否可以在 Android 中动态更改 EditTextPreference 的摘要?

    我设置了一个首选项屏幕来编辑应用程序中的设置 我想插入一个 EditTextPreference 其中包含一个标题 如 设置您的名字 和一个包含输入名称的摘要 那可能吗 先感谢您 当然 这是一个简短的例子 EditTextPreferenc
  • VS2010 中使用 lambda 参数捕获的 C++ 嵌套 lambda bug?

    我使用的是 Visual Studio 2010 它显然在 lambda 上有一些错误行为 并且有这个嵌套 lambda 其中内部 lambda 返回包装为 std function 的第二个 lambda 参见MSDN 上的 高阶 Lam
  • 从函数调用动态 SQL

    我正在编写一个返回表的函数 有两个参数传递给该函数 并构建并执行查询并将其插入到返回的表中 但是我收到这个错误 只能从函数内执行函数和一些扩展存储过程 我不想使用存储过程 因为这是一个简单的实用函数 有谁知道这是否可以做到 我的函数编码如下
  • 跨多个类使用 SharedPreferences?

    我有一个 SharedPreferences 目前适用于一类 但不适用于第二类 我想我可能把它称为错误的 因为我得到的错误说 The method getSharedPreferences String int is undefined f