我正在尝试传递从 JSON 字符串中提取的 Int 值以减少代码冗余。
在我的 JSON 文件中,我有一个字符串值“resFile“。我将这个字符串存储到TAG_RES_FILE我想将它作为 Int 在 Bundle 中传递。
如果你查看我的代码,你会看到评论//尝试#1//。这按预期工作,但我需要它Int来自存储我的变量TAG_RES_FILE。在评论中//尝试#2//这只是我想要实现的功能的一个例子 - 显然它不是。在下一行中,我尝试将标签字符串转换为Int但这会产生以下运行时错误:
java.lang.NumberFormatException:无效的 int:“resFile”
我什至尝试将 0x7f060000 (来自 R.java)放入 JSON 字符串中。
所以我的问题是:我该如何实现这一目标?我走在正确的道路上还是应该采取完全不同的方式?
感谢您的帮助和输入 - 请在您的答案中显示代码示例。
JSON 字符串片段:
[
{
"_id": "1",
"label": "A Lable",
"title": "Some Title",
"description": "Bla, bla, bla",
"containerID": "Some container id",
"isRawRes": "boolean value here",
"resFile": "R.raw.advisory_circulators_sort_list"
}, {. . .
]
在我的哈希图中:
// Parse the string to a JSON object
for (int i = 0; i < json.length(); i++) {
JSONObject json_data = json.getJSONObject(i);
// Storing each json item in variable
String id = json_data.getString(TAG_ID);
String label = json_data.getString(TAG_LABEL);
String title = json_data.getString(TAG_TITLE);
String description = json_data.getString(TAG_DISCR);
String containerID = json_data.getString(TAG_FRAG_ID);
String isRawRes = json_data.getString(TAG_IS_RAW_RES);
String resFile = json_data.getString(TAG_RES_FILE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_LABEL, label);
map.put(TAG_TITLE, title);
map.put(TAG_DISCR, description);
map.put(TAG_FRAG_ID, containerID);
map.put(TAG_IS_RAW_RES, isRawRes);
map.put(TAG_RES_FILE, resFile);
// adding HashList to ArrayList
mList.add(map);
}
在我的 ListViews setOnItemClickListener 中:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
. . .
final Bundle args = new Bundle();
//TRY #1//int rawRes = R.raw.advisory_circulators_sort_list; <--I NEED TO GET THIS IN FROM MY TAG!!
//TRY #2//int rawRes = TAG_RES_FILE; <-- TO SOMETHING LIKE THIS!!
int passResFile = Integer.parseInt(TAG_RES_FILE);//<--THIS GIVES A NPE!!
args.putInt("KEY_RES_FILE", passResFile);
bolean isRawRes = true;
args.putBoolean("KEY_IS_RAW_RES", isRawRes);
// Delayed to improve animations
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
ListViewFragment lvf = new ListViewFragment();
lcFT.replace(R.id.listContainer, lvf).commit();
lvf.setArguments(args);
}
}, 300);
}