Arraylist shows empty after adding items - android

I have an arraylist, which i used to store json parsed values.but after adding values to arraylist it shows its size as 1.i've attached my code below.pls help me to solve this
public void completed(JSONObject jsonObject) {
login_data = new ArrayList<Login_modal>();
try {
String response=jsonObject.toString();
JSONObject result = new JSONObject(response);
JSONObject res = result.getJSONObject(RES);
String stat = res.getString(STAT);
String username = res.getString(USERNAME);
String useremail = res.getString(USEREMAIL);
String userId = res.getString(USERID);
String userAvatarFile = res.getString(USERAVATARFILE);
String userType = res.getString(USERTYPE);
String authID = res.getString(AUTHID);
String cntr = res.getString(CNTR);
String loggedInOnce = res.getString(LOGGEDINONCE);
String topicarn = res.getString(TOPICARN);
Login_modal login_details = new Login_modal(stat, username, useremail, userId, userAvatarFile, userType, authID, cntr, loggedInOnce, topicarn);
login_details.setStat(STAT);
login_details.setUsername(USERNAME);
login_details.setUseremail(USEREMAIL);
login_details.setUserId(USERID);
login_details.setUserAvatarFile(USERAVATARFILE);
login_details.setUserType(USERTYPE);
login_details.setAuthID(AUTHID);
login_details.setCntr(CNTR);
login_details.setLoggedInOnce(LOGGEDINONCE);
login_details.setTopicarn(TOPICARN);
login_data.add(login_details);
} catch (JSONException e) {
e.printStackTrace();
}
here is my json file
{
"res": {
"stat": "SUCCESS",
"username": "Aggie",
"useremail": "aggie#logicalsteps.net",
"userId": "u55e29ddfe7cbd",
"userAvatarFile": "",
"userType": "SUB",
"authID": "",
"cntr": "",
"loggedInOnce": "",
"topicarn": "arn:aws:sns:us-east-1:080141827424:Demogroup"
}
}
here i am getting arraylist
if(login_data.get(1).equals("SUCCESS")) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
else {
Toast.makeText(Login.this, "Login failed try again", Toast.LENGTH_SHORT).show();
}
error log
FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)

You're doing wrong. correct way is
if(login_data.get(0).getStat().equals("SUCCESS"))
your login_data has only 1 record so you will get this by get(0) 0:index(first element)
login_data.get(0) ----> return Login_modal at 0 position
login_data.get(0).getStat() ----> return Stat of Login_modal at 0 position

Arraylist index starts with 0 and you are using login_data.get(1) and the arraylist size only 1
if(login_data.get(0).equals("SUCCESS")) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
else {
Toast.makeText(Login.this, "Login failed try again", Toast.LENGTH_SHORT).show();
}
Your JSON response keys are in lower case but you are pasring in UPPER case
for example you should parse like this for the rest:
String stat = res.getString("stat");
You already created constructor and again you are using setter method. I'm assuming that in LOGIN_MODEL constructor you are setting every variable.
comment these lines
login_details.setStat(STAT);
login_details.setUsername(USERNAME);
login_details.setUseremail(USEREMAIL);
login_details.setUserId(USERID);
login_details.setUserAvatarFile(USERAVATARFILE);
login_details.setUserType(USERTYPE);
login_details.setAuthID(AUTHID);
login_details.setCntr(CNTR);
login_details.setLoggedInOnce(LOGGEDINONCE);
login_details.setTopicarn(TOPICARN);

common man its typo error. You are passing your json key in arrayList
login_details.setStat(STAT);
It should be
login_details.setStat(stat);
because you have stored value in stat not in STAT, STAT is your JSON key.
And one more point, your arraylist is having only 1 record so instead of login_data.get(1) you need to use login_data.get(0)
if(login_data.get(0).getStat().equalsIgnoreCase("SUCCESS"))

You added only one data.
login_data.add(login_details);
The following is not adding data to the list
login_details.setStat(STAT);
login_details.setUsername(USERNAME);
...
you are setting the value of the properties of the Login_modal modal instance login_details.
and then adding that one Login_modal instance to login_data.
so you will really end up with one.
Here you get exception (Index out of bounds) because you are accessing the 2nd (index 1; 1st is index 0) element of login_data which does not exist.
if(login_data.get(1).equals("SUCCESS")) {

Related

Why do I get an empty response when my android app calls my API on my server?

I have android application that called information and show it as a list.
I have a spinner when you choose the date from the spinner you get the information related to that date.
In the app first load it calls automatically today information.
this is the code I use in my main activity to create my spinner and fill it with elements and handle the clicks on each item:
// Spinner element
spinner = (Spinner) v.findViewById(R.id.spinner);
// Spinner click listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// On selecting a spinner item
//String item = parent.getItemAtPosition(position).toString();
switch(position){
case 3:
if (JsonUtils.isNetworkAvailable(getActivity())) {
list.clear();
new MyTask().execute(Config.SERVER_URL + "/banko_api.php?d_o=-1");
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
}
break;
case 4:
if (JsonUtils.isNetworkAvailable(getActivity())) {
list.clear();
new MyTask().execute(Config.SERVER_URL + "/banko_api.php?d_o=0");
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
}
break;
case 5:
if (JsonUtils.isNetworkAvailable(getActivity())) {
list.clear();
new MyTask().execute(Config.SERVER_URL + "/banko_api.php?d_o=1");
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
}
break;
default:
if (JsonUtils.isNetworkAvailable(getActivity())) {
list.clear();
new MyTask().execute(Config.SERVER_URL + "/banko_api.php?d_o=0");
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, -1);
Date yesterday = calendar.getTime();
calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
DateFormat dateFormat = new SimpleDateFormat("dd/MM EEE");
String todayAsString = dateFormat.format(today);
String tomorrowAsString = dateFormat.format(tomorrow);
String yesterdayAsString = dateFormat.format(yesterday);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add(yesterdayAsString);
categories.add(todayAsString);
categories.add(tomorrowAsString);
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getContext(), R.layout.spinner_item, categories);
dataAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
spinner.setSelection(4);
The problem : first load of the app is calling the data of today (which is the default choice in my spinner) without any problem.
if i choose another element in the spinner it also calls the related data without problem.
now if I want to select back today element in the spinner no data will be brought from the server even when the app at the start up it calls data from the same link and get it.
I get this message in my log :
W/System.err: org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject
The onPostExcute of my Asynktask contains this code:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != progressDialog && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (null == result || result.length() == 0) {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
} else {
try {
Log.d("resultTT",result);
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(JsonConfig.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemMatch objItem = new ItemMatch();
objItem.setMatchId(objJson.getString(JsonConfig.Match_ID));
objItem.setMatchTournamentName(objJson.getString(JsonConfig.Match_LEAGUE_NAME));
objItem.setMatchTime(objJson.getString(JsonConfig.Match_TIME));
objItem.setMatchStatus(objJson.getString(JsonConfig.Match_STATUS));
objItem.setMatchLocalTeamName(objJson.getString(JsonConfig.Match_LOCALTEAM_NAME));
objItem.setMatchVisitorTeamName(objJson.getString(JsonConfig.Match_VISITORTEAM_NAME));
objItem.setMatchLocalTeamGoals(objJson.getString(JsonConfig.Match_LOCALTEAM_GOALS));
objItem.setMatchVisitorTeamGoals(objJson.getString(JsonConfig.Match_VISITORTEAM_GOALS));
objItem.setMatchBestOddPercent(objJson.getString(JsonConfig.Match_BEST_ODD_PERCENT));
objItem.setMatchBestOddResult(objJson.getString(JsonConfig.Match_BEST_ODD_RESULT));
list.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
for (int j = 0; j < list.size(); j++) {
object = list.get(j);
array_match_id.add(String.valueOf(object.getMatchId()));
str_match_id = array_match_id.toArray(str_match_id);
array_league_name.add(String.valueOf(object.getMatchTournamentName()));
str_league_name = array_league_name.toArray(str_league_name);
array_match_time.add(String.valueOf(object.getMatchTime()));
str_match_time = array_match_time.toArray(str_match_time);
array_match_status.add(String.valueOf(object.getMatchStatus()));
str_match_status = array_match_status.toArray(str_match_status);
array_match_localteam_name.add(object.getMatchLocalTeamName());
str_match_localteam_name = array_match_localteam_name.toArray(str_match_localteam_name);
array_match_visitorteam_name.add(object.getMatchVisitorTeamName());
str_match_visitorteam_name = array_match_visitorteam_name.toArray(str_match_visitorteam_name);
array_match_localteam_goals.add(object.getMatchLocalTeamGoals());
str_match_localteam_goals = array_match_localteam_goals.toArray(str_match_localteam_goals);
array_match_visitorteam_goals.add(object.getMatchVisitorTeamGoals());
str_match_visitorteam_goals = array_match_visitorteam_goals.toArray(str_match_visitorteam_goals);
array_match_best_odd_percent.add(object.getMatchBestOddPercent());
str_match_best_odd_percent = array_match_best_odd_percent.toArray(str_match_best_odd_percent);
array_match_best_odd_result.add(object.getMatchBestOddResult());
str_match_best_odd_result = array_match_best_odd_result.toArray(str_match_best_odd_result);
}
setAdapterToListView();
}
In the try section of this code u can see I make a log of the result to see what is coming from the server i just get this : D/resultTT: []
and as you see the try is inside the else section so in the if statement of this section i check if the result is null or empty ; but the code passes it and enter the else statement but still showing that the returned result array is empty.
I want some help to find the reason behind this empty returned array even it loads fine at the start up. why can not it get the information after I choose any element in the spinner and then come back to the default (today) element?
UPDATE : this is my php side-server api code
<?php
include_once ('includes/variables.php');
DEFINE ('DB_HOST', $host);
DEFINE ('DB_USER', $user);
DEFINE ('DB_PASSWORD', $pass);
DEFINE ('DB_NAME', $database);
$mysqli = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL');
#mysql_select_db (DB_NAME) OR die ('Could not select the database');
?>
<?php
mysql_query("SET NAMES 'utf8'");
$date_offset = mysql_real_escape_string($_GET[d_o]);
//$date_offset = 0;
if(empty($date_offset) || $date_offset == "0")
{
$date_offset_value = "0";
$query="SELECT a.*, m.match_id, m.match_time, m.en_tournament_name FROM app_banko a inner join matches_of_comments m on m.match_id = a.match_id where a.date_offset = $date_offset_value limit 20";
$resouter = mysql_query($query);
}
else
{
$date_offset_value = $date_offset;
$query="SELECT a.*, m.match_id, m.match_time, m.en_tournament_name FROM app_banko a inner join matches_of_comments m on m.match_id = a.match_id where a.date_offset = $date_offset_value limit 20";
$resouter = mysql_query($query);
}
$set = array();
$total_records = mysql_num_rows($resouter);
if($total_records >= 1){
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)){
$set['NewsApp'][] = $link;
}
}
echo $val= str_replace('\\/', '/', json_encode($set));
?>
If you get an array in return when expecting an object, there might be something wrong with the request to the API. One way is to figure it out it set up Wireshark on the development machine to sniff and filter the traffic. Then you can see if your request is faulty.
It is possible that the value of the response argument from the onPostExecute method contains stringified JSONArray, not JSONObject.
You can always test this with:
try:
JSONArray jsonArray = new JSONArray(result);
catch(JSONException e) {
// String `result` is not an array. Parse it as a regular JSONObject.
}
Testing wheter string is an empty json array (depends on it's formatting, especially when it may contain some white characters) checking it's length might be a pretty bad idea.
It all depends how are determined an API endpoints that you are calling.
One more tip at the end. If you are planning to consume REST API I strongly recommend using:
Retrofit - which allows you to easily define interfaces to access your API,
GSON - to automatically convert responses for Java models.
Your result string is an empty array but not an empty string. The empty array is represented as the following string:
String result = "[]";
In that case result.length() is equal to 2.
When parsing JSON you need to know if the parsed object is of type Object or of type Array. The former one is wrapped with braces {}, the later one with square brackets [].
So the following line:
JSONObject mainJson = new JSONObject(result);
Should probably be:
JSONArray mainJson = new JSONArray(result);
But I cannot emphasize enough that you need to know what your API returns if you want to be able to parse it correctly.
EDIT:
Well, json_encode will have a hard time to guess whether it should create a JSON Array or a JSON Object out of the empty array that you created with $set = array();.
Adding objects to the array like you do in your loop makes it obvious for json_encode that it should create a JSON Object.
I don't know if you can force json_encode's behavior, but worst case you could check yourself if the array is empty and return "" or null if the array is empty.
$set = array();
$total_records = mysql_num_rows($resouter);
if ($total_records >= 1) {
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)) {
$set['NewsApp'][] = $link;
}
echo $val= str_replace('\\/', '/', json_encode($set));
} else {
echo $val="";
}
please put a check result.isEmpty() in your try block condition may this could solve your problem.
you can not directly get response in string . it can use JSONObject and JSONArray.

Cannot find symbol variable Android Studio

I am working on parsing data from a JSON url.
But the JSONobjects have different keys.
I want to get all the data from each json object and when it doesn't have that key I want to give it a default message.
This is what I'm trying to use:
if(myJSONObject.has("mykey")) { <- in this case "abv"
//it has it, do appropriate processing
}
I got this variable
private static final String TAG_ABV = "abv";
I tried doing this to check if the abv key was included in the JSON and give the string a default text of "No value" when it was not inculed.
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
if(c.has("abv")) {
String abv = c.getString(TAG_ABV);
} else {
String abv = "No value";
}
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_ABV, abv);
dataList.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
But I have this error: cannot find symbol variable abv
I guess the abv inside the if statement is out the scope.
You're declaring abv inside the if/else blocks, which means it's only accessible inside that block. When you try to use it later (in data.put(TAG_ABV, abv); the variable you created is no longer accessible - it's out of scope. If you move the declaration of abv to the line before the if/else statement, that should fix your error.

Storing String Array as JSON Array then getting Ljava.lang.String# when trying to receive and set TextView as value

Right now i am pulling a value from a EditText MainActivity and putting that as at string in sharedpref. In a later activity I am receiving that value and trying to add it to the end of an array that is contunially growing. To store the Array in that later activity for receiving later to continue adding I used a JSON array. So basically I create a String Array when the counter is 0 (first input the user has done since clearing) and receive the string value from the MainActivity EditText and add that as the first value in the String Array and then store it as a JSON Array. When I receive it later (when counter is > 0) and convert it back to string Array, the outPut in my TextView for any given spot in the array is [L.java.lang.String;#42a5e438,. Below is my code for both if coutner == 0 and counter >0; Does anyone know what the solution is?
int placeCounterExplanation = pref.getInt("placeCounterExplanation",0);
//getting new item
String explanationItem = pref.getString("explanationItem",null);
if(placeCounterExplanation > 0){
///////////////////////////////////// RECEIVE//
//pull existing array
JSONArray explanationjArray;
try {
explanationjArray = new JSONArray(settings.getString("jArray", ""));
//converting from json back to workable string array
// String []ExplanationDetailArray = new String[explanationjArray.length()];
String []ExplanationDetailArray = new String[100];
//matching them/converting
for(int i = 0, count = explanationjArray.length(); i<= count; i++)
{
try {
String jsonString = explanationjArray.getString(i);
ExplanationDetailArray[i] = jsonString;
}
catch (JSONException e) {
e.printStackTrace();
}
}
//after matching^ it adds newest value
ExplanationDetailArray[placeCounterExplanation] = explanationItem;
////////////////////////////////////////////////////////////////////////
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
txtProduct.setText(product);
if (product.equals("Alcohol")){
test.setText(ExplanationDetailArray[0]);
String placeCount = Integer.toString(placeCounterExplanation);
test2.setText(ExplanationDetailArray[1]);
// test3.setText(placeCounterExplanation - 1);
}
//////////////////////////////////////////////////////////////////////////
/////STORE
explanationjArray.put(Arrays.toString(ExplanationDetailArray));
// explanationjArray.put(ExplanationDetailArray);
editor2.putString("jArray", explanationjArray.toString());
editor2.commit();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if (placeCounterExplanation == 0){
ExplanationDetailArray = new String[100];
ExplanationDetailArray[0] = explanationItem;
JSONArray explanationjArray = new JSONArray();
//////////////////////////////
// String sC = Integer.toString(spotCounter);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
txtProduct.setText(product);
if (product.equals("Alcohol")){
test.setText(ExplanationDetailArray[0]);
// test2.setText(ExplanationDetailArray[1]);
// test3.setText(placeCounterExplanation - 1);
}
///////////////////////////////
//STORING MIGHT NOT NEED THIS INSIDE HERE
// explanationjArray.put(ExplanationDetailArray);
explanationjArray.put(Arrays.toString(ExplanationDetailArray));
editor2.putString("jArray", explanationjArray.toString());
editor2.commit();
// placeCounterExplanation = placeCounterExplanation + 1;
// editor.putInt("placeCounterExplanation",placeCounterExplanation);
//editor.commit();
}
//after either IF Statement catches teh program, it advances the counter.
placeCounterExplanation = placeCounterExplanation + 1;
editor.putInt("placeCounterExplanation",placeCounterExplanation);
editor.commit();
I believe your problem is coming from the following line in code :
explanationjArray.put(ExplanationDetailArray);
This will insert a textual representation of the object into the JSON array. Instead you can do :
explanationjArray.put(Arrays.toString(ExplanationDetailArray));
or your own implementation of converting the string array to a concatenated set of strings.

How to edit an item in a json file?

I have this structure that is generated by my application and I read in a listView:
[{
"phone": "202020",
"name": "Jhon",
"id": 10,
"age": 20
},
{
"phone": "303030",
"name": "Rose",
"id": 11,
"age": 22
}]
When I select an item in the listview, I open a screen form passing the values ​​of the clicked item.
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String age = ((TextView) view.findViewById(R.id.age)).getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_AGGE, age);
in.putExtra(TAG_PHONE, phone);
startActivity(in);
}
});
This screen opens when you click on the item is a form where I put the values ​​passed from the previous screen fields.
My question is: When you click save in this form, I have to get the new values ​​and update the json file. How to do this?
Ex: I want to change the record ID 22, which is the user Rose.
ADD MORE INFORMATION:
I already use the Gson to generate items.
Code to generate:
btnSalvar.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
gson = new GsonBuilder().setPrettyPrinting().create();
final File file = new File(Environment.getExternalStorageDirectory() + "/download/ibbca/auditar.json");
// to check if file exists before before it maybe will be created
if (file.exists())
fileExists = true;
try{
// create file or get access to file
raf = new RandomAccessFile(file, "rw");
if (fileExists) // start new file as an array
raf.seek(file.length() - 1);
else { // start writing inside the bracket
raf.writeBytes("[");
raf.seek(file.length());
}
UserTestJson obj1 = new UserTestJson();
obj1.setId(10);
obj1.setName("Jhon");
obj1.setAge(20);
obj1.setPhone("202020");
toJson(obj1);
// end file
raf.writeBytes("]");
raf.close();
}catch(FileNotFoundException f){
f.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
And the Class UserTestJson, i created with get and seters for each variable.
The Simplest way is, Just go to that json Object and set the desired value for the key.
JSONArray arr = new JSONArray(str);
for(int i = 0; i < arr.length(); i++){
JSONObject jsonObj = (JSONObject)arr.get(i); // get the josn object
if(jsonObj.getString("name").equals("Rose")){ // compare for the key-value
((JSONObject)arr.get(i)).put("id", 22); // put the new value for the key
}
textview.setText(arr.toString());// display and verify your Json with updated value
}
It's perhaps a good time to switch to an ArrayAdapter.
I recommend to transfer the JSON into a custom model bean first:
class Person {
long id;
String phone, name, age;
}
Then you can use an JSON parser library like gson to parse the array into a List<Person> and use this array to drive your list. (See Gson help with parse array - works without array but won't with array) for an example on the parsing.
Finally, when you are ready to write back the data, simply re-generate the JSON from the array. This question got an example for that: Trouble with Gson serializing an ArrayList of POJO's
Pros:
Once your JSON data model changes, only a small change in your model is needed to read the new format.
You can use standard Java tools like ArrayList and POJOs
Cons:
You will need to import GSON or equivalent into your project.
Also check this question: How to parse JSON in Android
I cant find a direct way to do so.
But you can use this function to solve the problem first. See if there is other solution
private JSONObject setJSONVal(JSONObject jsonObject, String index, String value) throws JSONException{
String jsonString = jsonObject.toString().trim();
jsonString = jsonString.replace("\"" + index + "\":\"" + jsonObject.getString(index) + "\"", "\"" + index + "\":\"" + value + "\"");
return new JSONObject(jsonString);
}

How to Get JSON String to Int then to Arg Bundle?

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_list as opposed to R.raw.advisory_circulators_sort_list. Then, to get the Integer identifier, use this method:
int passResFile = getResources().getIdentifier( resFile, "raw", getPackageName() );

Categories

Resources