Sometime json array appears with image url's and sometimes it is empty. I am using the following code where array with image url displaying data and image in listview but when array is empty then data is also not displaying. How can i slove this? Any answer will be appreciated
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
JSONArray posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
String slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
String url = thumbnail.getString(KEY_URL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing json data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
Related
I have a trouble finding a way how to parse JSONArray
This is my JSON:
{
"result": [
[
"id",
"name",
"origin",
"destination"
],
[
1,
"A S Peta",
0,
0
],
[
2,
"Aachara",
0,
0
],
.
.
.
[
2238,
"sydney",
0,
0
]
]
}
I need to access it in Android app. I have tried and I am able to receive values, but they are displaying in a single row, and I am unable to split the fields.
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");
for (int i = 1; i < contacts.length(); i++) {
String name = contacts.getString(i).replaceAll("\\[|\\]", "");
HashMap<String, String> contact = new HashMap<>();
contact.put("name", name);
contactList.add(contact);
}
}
This is my output, I need to get the values separately like:
1
A S Peta
0
0
But not in single row:
Json String ca be parsed in JSONObject like:
try {
List<HashMap<String,String>> cityDetails= new ArrayList<HashMap<String,String>>();
JSONObject jsonObject = new JSONObject("your json string");
JSONArray jsonArray = jsonObject.getJSONArray("result");
JSONArray cityKeyArray =jsonArray.getJSONArray(0);
for(int index=1; index<jsonArray.length();index++){
HashMap<String, String> cityData = new HashMap<String, String>();
for(int dataIndex=0; dataIndex<cityKeyArray.length();dataIndex++) {
cityData.put(cityKeyArray.getString(dataIndex), jsonArray.getJSONArray(index).getString(dataIndex));
}
cityDetails.add(cityData);
}
} catch (Exception e) {
e.printStackTrace();
}
cityDetails can be used in the adapter to show value according to the keys which are in the first array of the JSON String i.e. cityKeyArray.
So, the collections will show the data as user requirements.
Hope this will help to solve your query.
Thanks and Happy coding!!!
update your code with this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");
for (int i = 1; i < contacts.length(); i++) {
JSONArray contactArray = contacts.getJSONArray(i);
int id = contactArray.getInt(0);
String name = contactArray.getString(1);
String origin= contactArray.getString(2);
String destination= contactArray.getString(3);
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contact.put("origin", origin);
contact.put("destination", destination);
contactList.add(contact);
}
}
String name = contacts.getString(i).replaceAll("\\[|\\]", "");
Do not do this; it seems you do not have strings for your arrays.
You have nested lists, it seems, so you can access those JSON arrays via another getJSONArray(index) method
Or you could fix the source of the JSON (your server?) to return better parsable JSON
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");
for (int i = 1; i < contacts.length(); i++) {
HashMap<String, String> contact = new HashMap<>();
contact.put("name", contacts.getString("name"));
contactList.add(contact);
}
}
Do this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");
for (int i = 1; i < contacts.length(); i++) {
JsonArray array=contacts.get(i);
String name = array.getString("name");
HashMap<String, String> contact = new HashMap<>();
contact.put("name", name);
contactList.add(contact);
}
}
I'm building a a Gallery app using GridView and ViewPager. I'm getting the image URLs from JSON. I've got the GridView displaying the images correctly, and now I'm moving on to the ViewPager. What I think I need to do is generate a String array of the image URLs for the ViewPager Adapter. In the GridView Activity, I've created a HashMap with the id, URL, and image description strings stored. My question now is: Is it possible to generate a String Array by retrieving all the stored URL strings from the HashMap? What I need is this from the HashMap:
public static final String[] imagesStr = new String[] {
"http://www.mysite/images/building0001.jpg",
"http://www.mysite/images/building00011.jpg",
"http://www.mysite/images/building0010.jpg" };
Here's how I'm generating the HashMap:
#Override
protected Void doInBackground(Void... params) {
// Retrieve JSON Objects from the given URL address
galleryArrList = new ArrayList<HashMap<String, String>>();
jsonobject = JIJSONfunctions.getJSONfromURL(urlPathStr);
try {
// Locate the array name in JSON
JSArrGallery = jsonobject.getJSONArray("gallery");
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
idStr = galleryJO.getString(TAG_ID);
urlStr = galleryJO.getString(TAG_URL);
descrStr = galleryJO.getString(TAG_DESCR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String,String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, idStr);
map.put(TAG_URL, urlStr);
map.put(TAG_DESCR, descrStr);
galleryArrList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
I'm a bit unclear on how a HashMap works, but I assume that the code is going through the JSON Array and pulling each URL string out and storing it in the HashMap, right? So now can I pull all the gathered URL Strings and create a String Array with them? How would I do that?
Seems straightforward enough. After you have populated your List<HashMap<String,String>>, iterate over each map and pull the value you need from it to add to a String[]. Please refer to the following snippet:
galleryArrList = new ArrayList<HashMap<String, String>>();
jsonobject = JIJSONfunctions.getJSONfromURL(urlPathStr);
try { ... }
final int length = galleryArrList.size();
final String[] imagesStr = new String[length];
for (int i = 0; i < length; i++) {
final Map<String, String> map = galleryArrList.get(i);
imagesStr[i] = map.get(TAG_URL);
}
You might try using an ArrayList and add the URLs to the ArrayList within the for loop. When the loop is done, you can use the ArrayList.toArray(T[] array) method copy the URLs from the ArrayList to a String array.
ArrayList.toArray
ArrayList arlist = new ArrayList();
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
idStr = galleryJO.getString(TAG_ID);
urlStr = galleryJO.getString(TAG_URL);
descrStr = galleryJO.getString(TAG_DESCR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String,String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, idStr);
map.put(TAG_URL, urlStr);
map.put(TAG_DESCR, descrStr);
galleryArrList.add(map);
arlist.add(urlStr);
}
// Create a String array to hold the URLs
String[] arUrls = new String[arlist.size()];
// Copy the URLs from the ArrayList to the String array
arlist.toArray(arUrls);
I tried to add json data to listview.But i don't know how to add the json data to list adapter.
try {
mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
String address = jsonChildNode.optString("address");
String mobile = jsonChildNode.optString("mobile");
String direction = "Direction: "+jsonChildNode.optString("direction");
String bestTime = "Best time to visite: "+jsonChildNode.optString("bestTime");
String food = jsonChildNode.optString("food");
String dress = jsonChildNode.optString("dress");
String priceRange = "Price Range: "+jsonChildNode.optString("priceRange");
String rate = jsonChildNode.optString("Rate");
String comment = "Price Range: "+jsonChildNode.optString("comment");
map.put("restName",restName);
map.put("address",address);
map.put("mobile",mobile);
map.put("direction",direction);
map.put("bestTime",bestTime);
map.put("food",food);
map.put("dress",dress);
map.put("priceRange",priceRange);
map.put("rate",rate);
map.put("comment",comment);
mylist = new ArrayList<HashMap<String, String>>();
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
// ListAdapter adapter = new SimpleAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,mylist);
// list.setAdapter(adapter);
}
Can anyone tel me how to set this data to list view.?
Try this..
Your doing reversely. declear the arraylist before for loop and declear the HashMap inside the for loop .
mylist = new ArrayList<HashMap<String, String>>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
HashMap<String, String> map = new HashMap<String, String>();
String address = jsonChildNode.optString("address");
//So on
map.put("restName",restName);
//So on
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
google-gson
I would use gson for this. Check the gson project website for more details on how. This is an example for object serialisation/deserialisation:
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
I am trying to parse JSON response where i am able to parse title,date, content and name but iam not able to parse url and display it in Listview. when i parse the url it is displaying image url in textview Can anybody direct me in right path
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String siteurl = c.getString(KEY_SITEURL);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url1 = null;
String slug1 = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug1 = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url1 = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_SITEURL, siteurl);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug1);
map.put(KEY_URL, url1);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
I am confused How to use looping for Json response Array in another Array. The following is my jsonresponse how to loop this to get data and images in listview
`{
"status": "ok",
"posts": [
{
"id": 2498,
"title": "jigsaw lamp imported from thailand",
"content": "<p>Hi. It’s a invitation to have a look at a unique lamp shade called jigsaw lamp from thailand. Available in multi attractive colours.</p>\n",
"date": "2012-12-26 09:48:15",
"author": {
"name": "Tapas123456",
},
"attachments": [
{
"description": "",
"caption": "",
"mime_type": "image/jpeg",
"images": {
"thumbnail": {
"url": "http://site/wp-content/uploads/2012/12/646675-50x47.jpg",
}
}
]
},........
the following is the code i used to loop is this the right way of doing it?
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// Phone number is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
JSONArray attachments = json.getJSONArray(KEY_ATTACHMENTS);
for(int j = 0; j < attachments.length(); j++){
JSONObject d = attachments.getJSONObject(j);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = d.getJSONObject(KEY_THUMB_URL);
String url = thumbnail.getString(KEY_URL);
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
// adding HashList to ArrayList
songsList.add(map);
Just Replace Following code
for(int j = 0; j < attachments.length(); j++){
JSONObject d = attachments.getJSONObject(j);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
String url = thumbnail.getString(KEY_URL);
}
instead of old code.