I’m trying to pass an Int value pulled from a JSON String to reduce code redundancy.
Within my JSON file, I have a string value in “resFile“. I store this string into TAG_RES_FILE where I want to pass it in a Bundle as an Int.
If you look in my code, you will see comment //TRY #1//. This works as expected but I need that Int to come from a variable that stores my TAG_RES_FILE. At comment //TRY #2// is just an example to what I want to function – obviously it does not. In the next line, I tried converting the tag string to a Int but this gives a runtime error of:
java.lang.NumberFormatException: Invalid int: “resFile”
I have even tried putting 0x7f060000 (from R.java) into the JSON String.
So my question is: How do I accomplish this? Am I on the right track or should I go about it a completely different way?
Thnx for your help and input – please show code examples in your answer.
JSON String Snippit:
[
{
"_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"
}, {. . .
]
In my HashMap:
// 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);
}
In my 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);
}
Instead, just store
advisory_circulators_sort_listas opposed toR.raw.advisory_circulators_sort_list. Then, to get the Integer identifier, use this method: