I have this String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"10\", \"qty\":\"65\"}, ]" ;
which is on array list, I want to put them on the variable on each loop and save it to the database, but for now I do this code for debugging purpose because at the first loop of the code it is suuposed to output "qty" value but instead it is a null like this {"pname":"7","qty":"222"} null but on the next run of loop it outputs this {"pname":"8","qty":"5"} 222 it seems that on the second loop the first objects qty value is then taken on the second loop, the final output is this
{"pname":"7","qty":"222"} null {"pname":"8","qty":"5"} 222 {"pname":"10","qty":"65"} 5
and this is the code that I have
String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"10\", \"qty\":\"65\"}, ]" ;
HashMap<String, String> item = new HashMap<String, String>();
JSONArray jsonArray = new JSONArray(data);
JSONObject jsonObject = new JSONObject();
ArrayList<HashMap> mylist = new ArrayList<HashMap>();
String txtPname = "", txtQty = "";
if (jsonArray == null) {
System.out.println("json is empty");
} else {
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
txtPname = item.put("pname", jsonObject.getString("pname"));
txtQty = item.put("qty", jsonObject.getString("qty"));
output.append(jsonObject).append(" ");
output.append(txtQty).append(" ");
}
}
can anyone help me about this? any help will be so much appreciated, Thanks!!!
You are assigning wrong value to txtQty rather than the current value in the JSONObject:
HashMap Put Method (From Docs):
Returns:
the previous value associated with key, or null if there was no
mapping for key. (A null return can also indicate that the map
previously associated null with key.)
Thats why you are getting null at first attempt and 222 at second.
Following code will give you desired result:
String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"10\", \"qty\":\"65\"}, ]" ;
HashMap<String, String> item = new HashMap<String, String>();
JSONArray jsonArray = new JSONArray(data);
JSONObject jsonObject = new JSONObject();
ArrayList<HashMap> mylist = new ArrayList<HashMap>();
String txtPname = "", txtQty = "";
if (jsonArray == null) {
System.out.println("json is empty");
} else {
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
txtPname = item.put("pname", jsonObject.getString("pname"));
txtQty = item.put("qty", jsonObject.getString("qty"));
output.append(jsonObject).append(" ");
output.append(jsonObject.getString("qty")).append(" ");
}
}
Related
I'm retrieving data from JSON like below :
worker: [{
content: "android"
}, {
content: "java"
}]
So I supposed that I will see values (android, java) but it doesn't happen i only see java iterated :
And this my way to get this length of array I retrieved from JSON:
I get the array correctly and pass it with SharedPreference :
JSONArray workerArr = object.getJSONArray("worker");
String jsonString = workerArr.toString();
SharedPreferences settings = getSharedPreferences("pref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("jsonString", jsonString);
editor.commit();
Then I get this length by this way simply :
SharedPreferences settings = getSharedPreferences("pref", 0);
String jsonString = settings.getString("jsonString", null);
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(jsonString);
Log.i(TAG, "displayCommentsJsonArray: " + jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
And here is how i add retrieved item to list...
List<String> top250 = new ArrayList<String>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
String value = "";
value = mCursor.getString(ArticleLoader.Query.WORKERS);
top250.add(value);
listDataChild.put(listDataHeader.get(0), top250);
}
}
So i should see two values in my list instead of same values with same count of array..
i don't know what i missed?
my mCursor throw this value in log :
prepareListData: java prepareListData: java
You are iterating the jsonArray, but I can't see any code where you parse the data from it.
Move the listDataChild.put(listDataHeader.get(0), top250); outside the loop. (As #Sac pointed)
Try the code below.
if (jsonArray != null) {
List<String> top250 = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String value = object.getString("content");
top250.add(value);
}
listDataChild.put(listDataHeader.get(0), top250);
}
I don't know the content of mCursor variable.
The output keeps repeating the name for each property. Only need to see the name once, and then prop_name and address can print out for each occassion under the single name. The JSON looks like:
[{"pmid":"2","name":"CARLYLE MANAGEMENT","result":"1","properties":[{"prop_id":"32","prop_name":"Bonneville Tower","address":"25801 Lakeshore","city":"Euclid","state":"OH","zip":"44132","lat":"41.6223","long":"-81.5034"}]},
{"pmid":"1","name":"COMMERCIAL ONE REALTY","result":"18","properties":[{"prop_id":"3","prop_name":"Autumn Chase Apartments","address":"146 Grand Circuit Blvd.","city":"Delaware","state":"OH","zip":"43015","lat":"40.3105","long":"-83.1138"},
{"prop_id":"6","prop_name":"Barrington Club Apartments","address":"4600 Barrington Club","city":"Columbus","state":"OH","zip":"43220","lat":"40.0536","long":"-83.0448"},{"prop_id":"17","prop_name":"Battleship Building Condominium","address":"444 North Front St.","city":"Columbus","state":"OH","zip":"43215","lat":"39.9712","long":"-83.0042"}]
The code is currently:
String pmid = mJsonObject.getString("pmid");
String name = mJsonObject.getString("name");
String result = mJsonObject.getString("result");
JSONArray mJsonArrayProperty = mJsonObject.getJSONArray("properties");
int innerLength = mJsonArrayProperty.length();
for (int k = 0; k < innerLength; k++) {
// JSONArray mJsonArrayProperty = mJsonObject.getJSONArray("properties");
// for (int i = 0; i < mJsonArrayProperty.length(); i++) {
JSONObject mJsonObjectProperty = mJsonArrayProperty.getJSONObject(k);
String prop_id = mJsonObjectProperty.getString("prop_id");
String prop_name = mJsonObjectProperty.getString("prop_name");
String address = mJsonObjectProperty.getString("address");
String city = mJsonObjectProperty.getString("city");
String state = mJsonObjectProperty.getString("state");
String zip = mJsonObjectProperty.getString("zip");
String lat = mJsonObjectProperty.getString("lat");
String lon = mJsonObjectProperty.getString("long");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_EMAIL, prop_name);
contact.put(TAG_NAME, name);
contact.put(TAG_PHONE, address);
// adding contact to contact list
contactList.add(contact);
}
} }catch (JSONException e) {
e.printStackTrace();
}
The output gives me the prop_name and address but it also says the name over and over each time. The goal is to see the name once and then the multiple properties under it. How can this be accomplished with a for or if statement, or any other way.
I am just writing the algo, How you can do it...
First you have to get the JSONObject in which you have the jsondata.
From that JSONObject you should get JSONArray because the whole jsondata you have is an array.
Now from that JSONArray you should get the string pmid, name etc..
Now again you have to get JSONArray because properties is JSONArray now you can iterate it.
And for doing this you should have use two for loop or any iteration method you want to use.
Try Out this...
JSONArray one=new JSONArray(json);
for (int i = 0; i < one.length(); i++)
{
JSONObject jsonObject=one.getJSONObject(i);
String pmid=jsonObject.getString("pmid");
String name=jsonObject.getString("name");
String result=jsonObject.getString("result");
JSONArray properties=jsonObject.getJSONArray("properties");
for (int j = 0; j < properties.length(); j++)
{
JSONObject js=properties.getJSONObject(j);
String prop_id=js.getString("prop_id");
String prop_name=js.getString("prop_name");
String address=js.getString("address");
String city=js.getString("city");
String state=js.getString("state");
String zip=js.getString("zip");
String lat=js.getString("lat");
String Long=js.getString("long");
}
}
from the following link , I need to get the value stored in "media".
Here is my code:
Content = Content.replace("jsonFlickrFeed(", "");
Content = Content.replace("})", "}");
jsonResponse = new JSONObject(Content);
JSONArray jsonMainNode = jsonResponse.optJSONArray("items"); // this works great!
But I can not access past "items"
You will have to loop through the JSON like this:
...
JSONArray jsonMainNode = jsonResponse.optJSONArray("items");
for (int i=0; i<jsonMainNode.length(); i++) {
String media = jsonMainNode.getJSONObject(i).getString("media");
}
This will loop through the images and return the value(s) in media.
In your case it should be something like this:
..
JSONArray jsonMainNode = jsonResponse.optJSONArray("items");
for (int i=0; i<jsonMainNode.length(); i++) {
JSONObject finalNode = jsonMainNode.getJSONObject(i);
JSONArray finalArray = finalNode.optJSONArray("media");
for (int j=0; j<finalArray.length(); j++) {
String m = finalArray.getJSONObject(j).getString("m");
}
}
...because there is another node inside the media node, called m.
Here is an example getting the tags string for each item in the JSONArray that you have:
for (int i = 0; i < jsonMainNode.length(); i++){
JSONObject jsonObject = jsonMainNode.getJSONObject(i);
String tags = jsonObject.getString("tags");
}
This will iterate through all JSONObjects that are in the array, and extract the tags field from each object.
JSONArray jsonMainNode = jsonResponse.optJSONArray("items"); // this works great!
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject item = (JSONObject) jsonMainNode.get(i);
JSONObject media = item.getJSONObject("media");
String valueMedia = media.getString("m");
Log.d("TAG", valueMedia);
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put("empty");
jsonArray.put(2);
jsonArray.put(3);
jsonArray.put("empty");
jsonArray.put(4);
jsonArray.put("empty");
lets say we have this jsonArray, there are strings empty, how to remove them without leaving gaps?
You can use the following code :
for (int i = 0, len = jsonArray.length(); i < len; i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String val = jsonArray.getJSONObject(i).getString();
if (val.equals("empty")) {
jsonArray.remove(i);
}
}
take a look at this post.
Make a list to put the indexes of the elements with the "empty" string and iterate over your list (the one with the "empty" elements) saving the indexes of the items to delete. After that, iterate over the previosly saved indexes and use
list.remove(position);
where position takes the value of every item to delente (within the list of index).
Should work with few fixes to Keerthi's code:
for (int i = 0; i < jsonArray.length(); i++) {
if (jsonArray.get(i).equals("empty")) {
jsonArray.remove(i);
}
}
You can use this following code
JSONArray list = new JSONArray();
JSONArray jsonArray = new JSONArray(jsonstring);
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
//Excluding the item string equal to "empty"
if (!"empty".equals(jsonArray.getString(i))
{
list.put(jsonArray.get(i));
}
}
//Now, list JSONArray has no empty string values
}
you can use string replace after converting the array to string as,
JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put("empty");
jsonArray.put(2);
jsonArray.put(3);
jsonArray.put("empty");
jsonArray.put(4);
jsonArray.put("empty");
System.err.println(jsonArray);
String jsonString = jsonArray.toString();
String replacedString = jsonString.replaceAll("\"empty\",", "").replaceAll("\"empty\"", "");
jsonArray = new JSONArray(replacedString);
System.out.println(jsonArray);
Before replace:
jsonArray is [1,"empty",2,3,"empty",4,"empty"]
After replace:
jsonArray is [1,2,3,4]
I'm prsing information from a json file and showing data in a custom ListView. Now, I have an Array named authors. Where authors are multiple. But, in ListView I can only see the last authors name or last array item .
How can I show all items ? Here is my code
for (int index = 0; index < jsonArray.length(); index++)
{
HashMap<String, String> temp = new HashMap<String,String>();
JSONObject jsonObject = jsonArray.getJSONObject(index);
String topic = jsonObject.getString("topic");
String type = jsonObject.getString("type");
String title = jsonObject.getString("title");
String absData = jsonObject.getString("abstract");
JSONArray getAuthorsArray = new JSONArray(jsonObject.getString("authors"));
for(int a =0 ; a < getAuthorsArray.length(); a++){
JSONObject getJSonObj = (JSONObject)getAuthorsArray.get(a);
String authordName = getJSonObj.getString("name");
Log.e("Name", authordName);
temp.put(KEY_AUTHOR, authordName);
}
temp.put(KEY_TOPIC, topic);
temp.put(KEY_TYPE, type);
temp.put(KEY_TITLE, title);
temp.put(KEY_ABSTRACT,absData);
list.add(temp);
}
}
simpleAdapter = new SimpleAdapter(this, list, R.layout.abstract_items, from, new int[]{R.id.abTopic,R.id.abType,R.id.abTitle,R.id.SubTitle});
setListAdapter(simpleAdapter);
temp.put(KEY_AUTHOR, authordName);
That's probably why. You are iterating over the all authors but HashMap will override values and only the last one is being saveed.
As I understand you are getting back a JSON response with an array of JSONObject. Each JSONObject holding some info and a sub-JSONArray of associated authors.
The easiest approach could be just building ArrayList<JSONObject> and extending BaseAdapter implementing an adapter of your own. It's very easy. For large collections of data search on ViewHolder pattern, for optimization.
'HashMap<String, String> temp;
for (int index = 0; index < jsonArray.length(); index++)
{
temp = new HashMap<String,String>();
JSONObject jsonObject = jsonArray.getJSONObject(index);
String topic = jsonObject.getString("topic");
String type = jsonObject.getString("type");
String title = jsonObject.getString("title");
String absData = jsonObject.getString("abstract");
JSONArray getAuthorsArray = new JSONArray(jsonObject.getString("authors"));
for(int a =0 ; a < getAuthorsArray.length(); a++){
JSONObject getJSonObj = (JSONObject)getAuthorsArray.get(a);
String authordName = getJSonObj.getString("name");
Log.e("Name", authordName);
temp.put(KEY_AUTHOR, authordName);
}
temp.put(KEY_TOPIC, topic);
temp.put(KEY_TYPE, type);
temp.put(KEY_TITLE, title);
temp.put(KEY_ABSTRACT,absData);
list.add(temp);
}
}
simpleAdapter = new SimpleAdapter(this, list, R.layout.abstract_items, from, new int[]{R.id.abTopic,R.id.abType,R.id.abTitle,R.id.SubTitle});
setListAdapter(simpleAdapter);'
you declare the "HashMap"line in above the onstart values.it will help for you.