从文本值中分离数值

时间:2014-10-24 02:24:53

标签: android text separator textutils

我正在从REST API中检索信息,它显示:

"Per 78g - Calories: 221kcal | Fat: 12.65g | Carbs: 16.20g | Protein: 10.88g"

我已将项目导入ListView,当用户点击某个项目时,我希望将每个数字值单独列出,如下所示,而不显示其文本。基于上面的例子:

String calories = 221;
String fat = 12.65;
String carbs = 16.20;
String protein = 10.88;

我摆脱了“Per 78g”:

String sd = food.getString("food_description");
String[] row = sd.split("-");
tems.add(new Item(food.getString("food_name"), row[1]));

在每个列表项中显示以下内容。

"Calories: 221kcal | Fat: 12.65g | Carbs: 16.20g | Protein: 10.88g"

当用户点击列表时项目:如何正确分离并删除文本?一旦我单独得到数值,我就没事了。

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub

    String calories = adapter.getItem(arg2).getDescription();

    String[] calRow = calories.split("?|?");

    Toast.makeText(getActivity(), "" + calRow[1], Toast.LENGTH_LONG).show();

    mCallback.onFoodSelected(adapter.getItem(arg2).getTitle(), calRow[1]);
}

API文档非常糟糕且过时。我正在使用它,因为它有很好的信息。 对于那些认为这是不好的做法的人来说,这就是返回JSON的例子:

{  
   "foods":{  
      "food":{  
         "food_description":"Per 342g - Calories: 835kcal | Fat: 32.28g | Carbs: 105.43g | Protein: 29.41g",
         "food_id":"4384",
         "food_name":"Plain French Toast",
         "food_type":"Generic",
         "food_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/french-toast-plain"
      },
      "max_results":"20",
      "page_number":"0",
      "total_results":"228"
   }
}

1 个答案:

答案 0 :(得分:1)

如下更改您的JSON,将使您的工作更轻松:

{  
   "foods":{  
      "food":{  
         "food_description":{
            "Per" : "342g",
            "Calories": "835kcal",
            " Fat": "32.28g",
            "Carbs":" 105.43g",
            " Protein": "29.41g"
            },
         "food_id":"4384",
         "food_name":"Plain French Toast",
         "food_type":"Generic",
         "food_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/french-toast-plain"
      },
      "max_results":"20",
      "page_number":"0",
      "total_results":"228"
   }
}

我假设你知道如何解析它 如果您无法更改json,请尝试使用StringTokenizer或使用String.split()。