【问题标题】:Can't get Value from ListPreference无法从 ListPreference 中获取值
【发布时间】:2012-04-22 18:44:07
【问题描述】:

我无法从此类中的 sharedpreferences 中获得价值。 getDefaultSharedPreferences 给出错误“PreferenceManager 类型中的方法 getDefaultSharedPreferences(Context) 不适用于参数 (HandlingXMLStuff)”

我可以从我的主类中获取值,但我不能将它传递给下面显示的类。

public class HandlingXMLStuff extends DefaultHandler {
String Units;

private XMLDataCollected info = new XMLDataCollected();

public String getInformation() {
    return info.dataToString();
}

@Override
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {



    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    String unit = prefs.getString("unitsofmeasure", "Fahrenheit");

    Log.d("HandlingXMLStuff", "test" + unit);
    // if (Units == "Farenheit") {
    if (localName.equals("city")) {
        String city = attributes.getValue("data");
        info.setCity(city);
        Log.d("DeskClockActivity", "test" + city);

    } else if (localName.equals("temp_f")) {
        String t = attributes.getValue("data");
        int temp = Integer.parseInt(t);
        info.setTemp(temp);
    }
    /*
     * }/* else if (unit == "C") { if (localName.equals("city")) { String
     * city = attributes.getValue("data"); info.setCity(city); } else if
     * (localName.equals("temp_c")) { String t =
     * attributes.getValue("data"); int temp = Integer.parseInt(t);
     * info.setTemp(temp); } }
     */
}

}

【问题讨论】:

    标签: android sharedpreferences android-preferences listpreference


    【解决方案1】:

    getDefaultSharedPreferences 采用上下文参数,而 DefaultHandler 类不是上下文。

    【讨论】:

    • 那么有没有另一种方法可以从 DefaultHandler 类中的 sharedpreference 中获取值?
    • 只需将上下文传递给您的HandlingXMLStuff 类并将其用于getDefaultSharedPreferences 方法
    • @Mike:当然,让您的HandlingXMLStuff 构造函数获取Context 引用并将其用于与共享首选项进行交互。或者,您可以设置一个侦听器接口,您的HandlingXMLStuff 将在适用时调用方法,并将与共享首选项的交互抽象到其他具有Context 的类中。
    猜你喜欢
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多