2

我有一个 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);

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

4

3 回答 3

4

当然 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);

最后一个值是默认值。

于 2012-05-01T07:00:20.557 回答
2

您应该必须通过context引用变量调用此方法。

public CheckPreferences(Context context, CheckPreferencesListener l)
{
 super(context);
 shc=context;
 ...
 pref = shc.getSharedPreferences("shared_prefs", 1);
 ...
}
于 2012-05-01T03:47:21.300 回答
0

该类Dialog没有定义 getSharedPreferences 方法。你可能想要:

getContext().getSharedPreferences(...)
于 2012-05-01T03:46:42.193 回答