Toast Array value not working
I am trying to test to make sure my the value I want is in the array. Below the first toast works and just spits out my whole string of JSON data.
But the second toast which I am trying to show the value of [1] in my new JSONArray the jsonArray is giving me the following error jsonArray can not be defined to a variable
Am I not referencing it correctly?
try{
JSONArray jsonArray = new JSONArray(jsonData);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(MainActivity.this, jsonData, Toast.LENGTH开发者_Go百科_LONG).show();
Toast.makeText(MainActivity.this, jsonArray[1], Toast.LENGTH_LONG).show();
EDIT based on the feedback it could also be a scope issue since it is in the "try" Do I have to use a try? and if so how do I make it available to the rest of the script.
JSONArray
is just a Java object, not an array, which means you cannot use array indexing on it. Perhaps you meant jsonData[1]
? Additionally, since jsonArray
is declared and initialized in the try
block, it is not in scope for the Toast
call. Assuming that jsonData
is a Collection
:
try
{
JSONArray jsonArray = new JSONArray(jsonData);
// ...
Toast.makeText(MainActivity.this, jsonData.get(1), Toast.LENGTH_LONG).show();
}
// ...
Change the last line to:
Toast.makeText(MainActivity.this, jsonArray.get(1).toString(), Toast.LENGTH_LONG).show();
Or, if you know that element 1 is a String,
Toast.makeText(MainActivity.this, jsonArray.getString(1), Toast.LENGTH_LONG).show();
EDIT
Based on your edit, I'm embarrassed that I didn't see it, but yes, you do have a scope issue. Move the Toasts inside the try
block (in addition to what I suggested above).
The jsonArray variable is not declared within the same scope as your Toast.
Try something like this:
try {
JSONArray jsonArray = new JSONArray(jsonData);
Toast.makeText(MainActivity.this, jsonData, Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, jsonArray[1], Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
精彩评论