Forgive for I am new to Android and a novice at Java. I am trying to create a dynamic list view using data from a MySQL server. However, sometimes a query returns only one result. When my adapter class parses a JSONArray with one element to a String array, I receive an ArrayIndexOutOfBoundsException. How do I avoid using an empty string in my resultArray to compensate for the exception? I don't want to use the empty string because it will still be selectable within the listview.
Parsing code:
try
{
jArray = new JSONArray(result);
// Taking a peek at the contents
Log.e("log_tag", jArray.getJSONObject(0).getString(queryID));
//For some reason if I don't do this
// I get ArrayIndexOutOfBoundsException.
if (jArray.length() == 1)
{
resultArray = new String[2];
resultArray[1] = "";
}
else
resultArray = new String[jArray.length()];
for(int i = 0; i < jArray.length(); i++)
{
resultArray[i] = jArray.getJSONObject(i).getString(queryID);
}
}
catch(JSONException e)
{
throw new NullResultFromServerException("No results from server.");
}
for(int i = 0; i < jArray.length(); i++)
{
String empty= jArray.getJSONObject(i).getString(queryID);
empty=empty.trim(); //this will remove the blank white space
if(!empty.equalsIgnoreCase(""))
resultArray[i] = empty;
}
Related
Output of String return: [{"type":1, "txt":"ERROR"}]. I'm trying to get the content of txt key which is ERROR. And that
by transforming string return into an array. However I'm getting some errors commented next to each line on the follow code.
Any insight? I tried everything to retrieve the value of txt.
Vector<ClsReturn> ret = null;
ret = ds.id(collection, "fs",in_uri );
String return = JSONArray.toJSONString(ret);
JSONObject myJsonObject = new JSONObject(ret);
JSONArray array = new JSONArray(return); //The constructor JSONArray(String) is undefined
for(int i=0; i<array.length(); i++){ //The method length() is undefined for the type JSONArray
JSONObject jsonObj = array.getJSONObject(i); //The method getJSONObject(int) is undefined for the type JSONArray
System.out.println(jsonObj.getString("txt"));
}
Try this
String retur = JSONArray.toJSONString(ret);
JSONObject myJsonObject = new JSONObject();
JSONArray array = new JSONArray(retur);
int i = 0;
while(i < array .length()){
myJsonObject = array .getJSONObject(i);
System.out.println(myJsonObject.getString("txt"));
i++;
}
i am trying to make an app that requires to loop through an array of JSON objects. For this i first create an ArrayList and then convert it to an Array and loop through it, however i get the following error:
Day::drawEvents |
StringIndexOutOfBoundsException: length = 16;
regionStart = -2;
regionLength = 1
The error doesn't even show up on the logcat as an error it only displays as popup message on the device.
The code that i suspect causes the error:
List<JSONObject> appointments = new ArrayList<JSONObject>();
JSONObject jsonObject = new JSONObject(jsonAppointments);
JSONObject jsonResponse = jsonObject.getJSONObject("response");
JSONArray jsonData = jsonResponse.getJSONArray("data");
for (int i = 0; i < jsonData.length(); i++) {
appointments.add(jsonData.getJSONObject(i));
}
List<JSONObject> appointments = new ArrayList<JSONObject>();
...adding items to the ArrayList...
JSONObject[] appointmentsArray = new JSONObject[appointments.size()];
appointments.toArray(appointmentsArray);
int len = appointments.size();
for (int i = 0; i < len; i++) {
start = appointmentsArray[i].getInt("start") * 1000L;
...processing the array content...
}
I used the code below to retrieve json data and put it in a table. That worked. But I want to display the data in a combobox now. Right now, it is displaying the items in the dropdown in this format: ljava.lang.string #5c647e05
Can someone please tell me what I'm doing wrong? Thank you.
Hashtable response = parser.parse(reader);
java.util.List allResult = (java.util.List) response.get("AllResult");
System.out.println(allResult);
try {
String[][] data = new String[allResult.size()][4];
for (int i = 0; i < allResult.size(); i++) {
Object obj = allResult.get(i);
String result = (String) ((Hashtable) obj).get("Status");
String investorName = (String) ((Hashtable) obj).get("investorName");
if (result.equalsIgnoreCase("ok")) {
for (int j = 0; j < 4; j++) {
if (j == 0) {
data[i][j] = investorName; }
}
}
}
ComboBox investorNames = new ComboBox(data);
details.addComponent(investorNames);
System.out.println("Data here: " + data);
String[] columnNames = { "Seller's Name", "Stock Name", "Unit", "Price" };
TableModel model = new DefaultTableModel(columnNames, data, false);
Table table = new Table(model);
table.setScrollable(true);
details.addComponent(table);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Try to paste in Combobox only vector of invector names not whole array of arrays. As Combobox just invokes toString() on every array (row) of matrix, that's why you got Ljava.lang.String#5c647e05 and not investor names. Something like this:
String[] comboData = new String[allResult.size()];
for (int i = 0; i < allResult.size(); i++){
...
String investorName = (String) ((Hashtable) obj).get("investorName");
comboData[i] = investorName
...
}
ComboBox investorNames = new ComboBox(comboData);
details.addComponent(investorNames);
....
ComboBox expects an array of string but you are passing to it an array of array of strings.
So those ljava.lang.string #5c647e05 that you are seeing are the 'toString' representation of an array of strings.
You need to somehow (depending on what you need to do) flatten your 'data' so that it becomes an array of strings.
I get data from Json and there's a Json array. I want to convert that Json array into String array, so I can send it into another activity and show it in ListView.
Here's My java code
if (jsonStr != null) {
try {
foodsFilter = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foodsFilter.length(); i++) {
JSONObject c = foodsFilter.getJSONObject(i);
if(c.getString("category_name").equals("Food")) {
String category_name = c.getString(TAG_CATEGORY_NAME);
String filter_type = c.getString(TAG_FILTER_TYPE);
//String item_list = c.getString(TAG_ITEM_LIST);
JSONArray itemList = new JSONArray(c.getString("item_list"));
String item_list = itemList.toString();
// tmp hashmap for single contact
HashMap<String, String> filter = new HashMap<String, String>();
// adding each child node to HashMap key => value
filter.put(TAG_CATEGORY_NAME, category_name);
filter.put(TAG_FILTER_TYPE, filter_type);
filter.put(TAG_ITEM_LIST, item_list);
// adding contact to contact list
foodsFilterList.add(filter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I try that code to convert the JSONarray, but I realized that code is for convert the JSONArray into String.
Here's my JSON data
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}]
I want to convert the item_list Array into like this
item_list = {"Ascending", "Descending"}
So I can send it into another activity use Intent and show it in ListView
What you have
String item_list = itemList.toString();
You need to parse items_list which is a JSONArray.
JSONArray itemList = new JSONArray(c.getString("item_list"));
// loop through the array itemList and get the items
for(int i=0;i<itemList.length();i++)
{
String item = itemList.getString(i); // item at index i
}
Now you can add the strings to a list/array and then do what is required.
Please have a look on this tutorial.
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Maybe this would help you.
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
Why I am getting duplicate entries in my ArrayList<String[]>?
allStepsJSONStringArray contains an array of single strings in the format of JSON
I loop through and pass each JSON string to a function that writes it to a temporary internal file
I read the file
Then pass it to getStepsArray() which breaks down the JSON string and puts each entry into a String[]
Loop to add to master ArrayList - allStepsArray
for (int i = 0; i < allStepsJSONStringArray.size(); i++) {
writer.writeToInternal(allStepsJSONStringArray.get(i));
reader.readFromInternal(writer.filename);
stepsArray = reader.getStepsArray();
for (int s = 0; s < stepsArray.size(); s++) {
allStepsArray.add(stepsArray.get(s));
}
}
getStepsArray()
public ArrayList<String[]> getStepsArray() {
try {
JSONObject jObject = new JSONObject(jsonString);
JSONArray jArray = jObject.getJSONArray("steps");
String stepOrder = null;
String stepName = null;
String stepType = null;
String stepId = null;
String checklistId = null;
String checklistName = null;
for (int i = 0; i < jArray.length(); i++) {
stepOrder = jArray.getJSONObject(i).getString("order");
stepName = jArray.getJSONObject(i).getString("name");
stepType = jArray.getJSONObject(i).getString("type");
stepId = jArray.getJSONObject(i).getString("id");
checklistId = jObject.getString("checklistId");
checklistName = jObject.getString("checklistName");
stepsArray.add(new String[] {stepOrder, stepName, stepType, stepId, checklistName, checklistId});
}
} catch (Exception e) {
e.printStackTrace();
}
return stepsArray;
}
Word for word:
Because you don't seem to ever reset stepsArray. The second time you add elements to it, the previous elements will still be there and will get added to allStepsArray again.