Android:如何从RSS源获取值并从另一个RSS源中的值中减去它

时间:2014-08-19 19:00:26

标签: java android xml rss

嘿,我有两个RSS提要 - http://www.petrolprices.com/feeds/averages.xml?search_type=town&search_value=kilmarnockhttp://www.petrolprices.com/feeds/averages.xml?search_type=town&search_value=glasgow。现在我想要做的是从一个RSS提要中获取一个值,并使用其他RSS提要中的值计算它。例如,

132.9 - 133.1

我将如何做到这一点?

基本思想是用户创建RSS URL,然后onClick获取每个RSS源的所有值,并将其与另一个进行比较,以便用户获得差异,从而通过选择一个或另一个

1 个答案:

答案 0 :(得分:1)

据我了解,您的问题有一个简单的答案,一个更具体的答案。我将首先说明如何将字符数据转换为数字(无论是int,double,float等)的简单答案,特别关注异常情况,然后深入研究特别适用于您的细节问题

每当你有一个你认为某种类型的数字的字符串表示时,你可以为目标包装类调用适当的valueOf()或parseXYZ()方法。例如。如果你正在寻找一个整数:theInt是字符串“42”。 Integer.valueOf(theInt)将返回值为42的Integer,Integer.parseInt(theInt)将返回int 42。 http://developer.android.com/reference/java/lang/Double.html

如果theInt代表,例如“四十二”或“42.0”,则任何一种方法都会抛出NumberFormatException。解析一个浮点数遵循相同的过程,除了“42.0”将正确解析,“42.0.0”将在Android上抛出NumberFormatException。传递给其中一个方法的整个字符串必须是所选类型的有效数字。最后的空白也会抛出异常。

如果您正在使用扫描仪,则可以使用hasNextXYZ()和nextXYZ()来检查并获取下一个数字,其中XYZ可以是任何基本类型。扫描程序将对下一个令牌进行操作,该令牌将根据您设置的分隔符进行定义。 http://developer.android.com/reference/java/util/Scanner.html

“很好,那么何时,何地以及如何获取XML中的数字并将它们传递给上述任何方法?”您应该有一个数据结构来保存每个值,您在解析XML时填充的内容。根据{{​​3}}处的状态,我的理解是将XML解析为令牌已经解决了。因此,更新解析器以针对最高,平均和最低元素的值调用正确的字符串到数字转换方法。您需要的字符串已经正确修剪,并在每个阶段通过解析器。

或者,为了进一步解耦代码,创建一个保存您将要比较的数据集的对象,然后让解析器简单地实例化并调用setter。 FuelData可能就是那个对象。

class FuelData { 
    String KEY_TYPE;
    double highest;
    double average;
    double lowest;
    // if future support for currency types needed, would go here, hook in to units attribute in xml
    FuelData(String type) { // call this every time a type is encountered parsing html
        KEY_TYPE = type;
    }

    void setHighest(String val) { // here, val is value of "Highest" element
        try {
            highest = Double.parseDouble(val); // because you're not using a Scanner to parse
        } catch (NumberFormatException e) {
        // handle appropriately
        }
        // perhaps sanity check: disallow negatives, check not less than lowest, etc.
    }

    // and so on for average and lowest

    double computeSavings(FuelData pricesB) { // called by onClick
    // your subtraction goes here. Perhaps you decide it's reasonable to use this method
    // to compute savings for Regular vs. Premium and therefore do not check type,
    // perhaps you decide that's illogical and do check types.
    // Note: good arguments can be made that this method should exist in a different
    // class. I've placed it here for simplicity's sake.
    }
}

以逻辑方式收集FuelData,可以在解析完成后访问,例如将feed1解析为一组FuelData,将feed2解析为一组FuelData等,然后让onClick获取所有已解析的FuelData在每个RSS提要中,通过computeSavings进行比较,并返回结果。