Not able to populate ListView from JSON URL (android) - android

Good evening, I'm new to Android development and I'm having issues populating a ListView from JSON URL
The parsing is fine though. This is what I have tried so far:
try {
JSONArray array = new JSONArray(result);
String asef = "";
for(int i = 0; i < array.length(); i++)
{
JSONObject hospital = array.getJSONObject(i);
JSONObject hospital2 = hospital.getJSONObject("address");
if (!hospital2.isNull("hospital")) {
String hospitalName = hospital2.getString("hospital");
String hospitalLat = hospital.getString("lat");
String hospitalLon = hospital.getString("lon");
hospitals.add("hospitalLat");
}
}
}
This is my listview
ListView listView = (ListView) findViewById(R.id.listView);
ArrayList<String> hospitals = new ArrayList<String>();

Related

I want to list data from JSON string using an array, but why my app crashes?

I want to list data from a JSON string in ListView.
I store the strings in an array.
When I write i in the line JSONObject day = jsonArray.getJSONObject(0); the app crashes.
What did I wrong?
String json_string1 = "{\"list\":[{\"dt\":1471255200,\"temp\":{\"day\":30.04,\"min\":17.35,\"max\":30.04},\"pressure\":1018.83,\"humidity\":35,\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"de scription\":\"scattered clouds\",\"icon\":\"03d\"}],\"speed\":2.66,\"deg\":314,\"clouds\":48},{\"dt\":1471341600,\"temp\":{\"day\":29.48,\"min\":19.3,\"max\":29.95},\"pressure\":1018.63,\"humidity\":100,\"weather\":[{\"id\":501,\"main\":\"Rain\",\"des cription\":\"moderate rain\",\"icon\":\"10d\"}],\"speed\":2.46,\"deg\":28,\"clouds\":92,\"rain\":8.5},{\"dt\":1471428000,\"temp\":{\"day\":28.96,\"min\":17.84,\"m ax\":297.54},\"pressure\":1012.1,\"humidity\":95,\"weather\":[{\"id\":501,\"main\":\"Ra in\",\"description\":\"moderate rain\",\"icon\":\"10d\"}],\"speed\":2.27,\"deg\":118,\"clouds\":88,\"rain\":5.55},{\"dt\":1471514400,\"temp\":{\"day\":26.89,\"min\":17.84,\" max\":28.95},\"pressure\":1014.27,\"humidity\":83,\"weather\":[{\"id\":500,\"main\":\"R ain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.98,\"deg\":93,\"clouds\":20},{\"dt\":1471600800,\"temp\":{\"day\":30.04,\"min\":21.87,\"max\":30.04},\"pressure\":1014.65,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"descrip tion\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.66,\"deg\":194,\"clouds\":11,\"rain\":0.22},{\"dt\":1471687200,\"temp\":{\"day\":31.3,\"min\":22.56,\"max\":32.3},\"p ressure\":1018.6,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"descriptio n\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.69,\"deg\":180,\"clouds\":16,\"rain\":0.77},{\"dt\":1471773600,\"temp\":{\"day\":31.77,\"min\":21.67,\"max\":30.77},\"pressure\":1016.93,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"speed\":2.49,\"deg\":227,\"clouds\":14,\"rain\":2.2}]}";
JSONObject jsonObject;
String[] days_array = new String[7];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
jsonObject = new JSONObject(json_string1);
JSONArray jsonArray = jsonObject.optJSONArray("list");
int lengthJsonArr = jsonArray.length();
for (int i = 0; i < lengthJsonArr; i++) {
JSONObject day = jsonArray.getJSONObject(0);
JSONObject temp = day.getJSONObject("temp");
int min = temp.getInt("min");
int max = temp.getInt("max");
JSONArray weather = day.getJSONArray("weather");
JSONObject zero = weather.getJSONObject(0);
String main = zero.getString("main");
double speed = day.getDouble("speed");
days_array[i] = max + "/" + min + ", " + main + ", Wind=" + speed;
}
} catch (JSONException e) {
e.printStackTrace();
}
ListView ListView = (ListView) findViewById(R.id.list_view);
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_layout, R.id.item_name, days_array);
ListView.setAdapter(adapter);
}
You had two wrong property names: "m ax" and " max". This fixed json will work:
String json_string1 = "{\"list\":[{\"dt\":1471255200,\"temp\":{\"day\":30.04,\"min\":17.35,\"max\":30.04},\"pressure\":1018.83,\"humidity\":35,\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"de scription\":\"scattered clouds\",\"icon\":\"03d\"}],\"speed\":2.66,\"deg\":314,\"clouds\":48},{\"dt\":1471341600,\"temp\":{\"day\":29.48,\"min\":19.3,\"max\":29.95},\"pressure\":1018.63,\"humidity\":100,\"weather\":[{\"id\":501,\"main\":\"Rain\",\"des cription\":\"moderate rain\",\"icon\":\"10d\"}],\"speed\":2.46,\"deg\":28,\"clouds\":92,\"rain\":8.5},{\"dt\":1471428000,\"temp\":{\"day\":28.96,\"min\":17.84,\"max\":297.54},\"pressure\":1012.1,\"humidity\":95,\"weather\":[{\"id\":501,\"main\":\"Ra in\",\"description\":\"moderate rain\",\"icon\":\"10d\"}],\"speed\":2.27,\"deg\":118,\"clouds\":88,\"rain\":5.55},{\"dt\":1471514400,\"temp\":{\"day\":26.89,\"min\":17.84,\"max\":28.95},\"pressure\":1014.27,\"humidity\":83,\"weather\":[{\"id\":500,\"main\":\"R ain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.98,\"deg\":93,\"clouds\":20},{\"dt\":1471600800,\"temp\":{\"day\":30.04,\"min\":21.87,\"max\":30.04},\"pressure\":1014.65,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"descrip tion\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.66,\"deg\":194,\"clouds\":11,\"rain\":0.22},{\"dt\":1471687200,\"temp\":{\"day\":31.3,\"min\":22.56,\"max\":32.3},\"p ressure\":1018.6,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"descriptio n\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.69,\"deg\":180,\"clouds\":16,\"rain\":0.77},{\"dt\":1471773600,\"temp\":{\"day\":31.77,\"min\":21.67,\"max\":30.77},\"pressure\":1016.93,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"speed\":2.49,\"deg\":227,\"clouds\":14,\"rain\":2.2}]}";
To ensure that it does not happen again, you can use online tools such as the next https://jsoneditoronline.org/ to validate your future jsons before thinking that you have any error in your code.
One more thing, you could also improve the name of your variable String json_string1 byString jsonString1 to keep java's camel case convention

parse JsonArray in android

How to parse this jsonarray "Images" ??
I parse this json ,, but i can't get "Images"
the Jsonarray "data" inside it elements , inside every element array of images >>>>
this is the response
this is my code
JSONObject responseObject = new JSONObject(response);
JSONArray newsJsonArray = responseObject.getJSONArray("data");
final List <AndroidVersion> newsList = new ArrayList <AndroidVersion>();
newsImages = new ArrayList<String>();
newsids = new ArrayList<String>();
newsnames = new ArrayList<String>();
newshotelsid = new ArrayList<String>();
newscontents = new ArrayList<String>();
newstimesto = new ArrayList<String>();
newscost = new ArrayList<String>();
newstimesfrom = new ArrayList<String>();
newscountry = new ArrayList<String>();
newscity = new ArrayList<String>();
newstype = new ArrayList<String>();
newsImages = new ArrayList<String>();
for (int j = 0; j < newsJsonArray.length(); j++) {
AndroidVersion news = new AndroidVersion();
if (newsJsonArray.getJSONObject(j).has("id")) {
newsids.add(newsJsonArray.getJSONObject(j).getString("id"));
}
if (newsJsonArray.getJSONObject(j).has("name")) {
news.setName(newsJsonArray.getJSONObject(j).getString("name"));
newsnames.add(newsJsonArray.getJSONObject(j).getString("name"));
}
if (newsJsonArray.getJSONObject(j).has("desc")) {
news.setdesc(newsJsonArray.getJSONObject(j).getString("desc")
.replaceAll("<p>", "").replaceAll("<\\/p>\\r\\n", "").replaceAll(" ", ""));
newscontents.add(newsJsonArray.getJSONObject(j).getString("describtion"));
}
if (newsJsonArray.getJSONObject(j).has("country")) {
news.setcountry(newsJsonArray.getJSONObject(j).getString("country"));
newscountry.add(newsJsonArray.getJSONObject(j).getString("country"));
}
if (newsJsonArray.getJSONObject(j).has("city")) {
news.setcity(newsJsonArray.getJSONObject(j).getString("city"));
newscity.add(newsJsonArray.getJSONObject(j).getString("city"));
}
if (newsJsonArray.getJSONObject(j).has("date_from")) {
news.setdate_from(newsJsonArray.getJSONObject(j).getString("date_from"));
newstimesfrom.add(newsJsonArray.getJSONObject(j).getString("date_from"));
}
if (newsJsonArray.getJSONObject(j).has("date_to")) {
news.setdate_to(newsJsonArray.getJSONObject(j).getString("date_to"));
newstimesto.add(newsJsonArray.getJSONObject(j).getString("date_to"));
}
if (newsJsonArray.getJSONObject(j).has("num persons")) {
news.sethotel_id(newsJsonArray.getJSONObject(j).getString("num persons"));
newshotelsid.add(newsJsonArray.getJSONObject(j).getString("num persons"));
}
if (newsJsonArray.getJSONObject(j).has("price")) {
news.setprice(newsJsonArray.getJSONObject(j).getString("price"));
newscost.add(newsJsonArray.getJSONObject(j).getString("price"));
}
if (newsJsonArray.getJSONObject(j).has("images")) {
news.setImage(newsJsonArray.getJSONObject(j).getString("images"));
newsImages.add(newsJsonArray.getJSONObject(j).getString("images"));
}
newsList.add(news);
}
I would highly recommend using Gson to parse it.
Create a response object with structure matching the json response. Then you can use the single object without having to create it down into parts.
Change this part:
if (newsJsonArray.getJSONObject(j).has("images")) {
news.setImage(newsJsonArray.getJSONObject(j).getString("images"));
newsImages.add(newsJsonArray.getJSONObject(j).getString("images"));
}
to:
if(newsJsonArray.getJSONObject(j).getJSONArray("images") != null) {
JSONArray jArray = newsJsonArray.getJSONObject(j).getJSONArray("images");
for (int k=0; k<jArray.length(); k++) {
news.setImage(jArray.getString(k));
newsImages.add(jArray.getString(k));
}
}
You can use direct string object from JSONArray like below:
JSONArray array = object.getJSONArray("images");
for (int i = 0; i < array.length(); i++) {
String image = array.getString(i);
}

How To store json values in a set of arrays in android

i have a json file like so :
http://da.pantoto.org/api/files
i want to store these values in variables to be used later. The values should be stored in some String array variables like id[], uploadDate[], url[].
i can find examples using ListView and ArrayAdapter. but thats not what i really want. Anyone can help??
This is only an example to show how you can get the values from JSON. You need to store these values as you need.
JSONObject jsonObject = new JSONObject("your response");
JSONArray filedetails = jsonObject.getJSONArray("files");
for(int i=0; i<filedetails.size();i++){
String id = filedetails.get(i).getString("id");
JSONArray tagsdetails= filedetails.get(i).getJSONArray("tags");
for(int i=0; i<tagsdetails.size();i++){
//fetch values in it
}
}
You can't do it exactly that way, You have to iterate trough the array and get each object properties individually and then if you want you could create an array to store each object property.
//From the example: http://da.pantoto.org/api/files
JSONArray files = null;
//Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
//Making a request to url and getting response
String jsonStr = sh.makeServiceCall("http://da.pantoto.org/api/files", ServiceHandler.GET);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
files = jsonObj.getJSONArray("files");
//YOUR NEW ARRAY
String[] ids = new String[20];
String[] urls = new String[20];
//etc
//looping through All files
for (int i = 0; i < files.length(); i++) {
JSONObject c = files.getJSONObject(i);
String id = c.getString("id");
String url = c.getString("url");
//etc
//HERE IS WHAT YOU COULD DO OPTIONALLY IF YOU WANT HAVE IT ALL ON A SINGLE ARRAY WITHOUT OBJECTS:
ids[i] = id;
urls[i] = url;
//etc
}
this is a simple way to do this. see i also done this kind of string array and later use
try {
JSONObject jObj = new JSONObject(strDocketListResponse);
JSONArray jsonArray = jObj.getJSONArray("GetManifestDocketListResult");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject detailsObject = jsonArray.getJSONObject(i);
String strDktNo = detailsObject.getString("Docketno");
String strDocketDate = detailsObject.getString("DocketDate");
String strOrigin = detailsObject.getString("Origin");
String strDestination = detailsObject.getString("Destination");
String[] strDocketNoDkt = new String[]{strDktNo};
String[] strDocketDateDkt = new String[]{strDocketDate};
String[] strDocketOriginDkt = new String[]{strOrigin};
String[] strDocketDestnDkt = new String[]{strDestination};
for (int sanjay = 0; sanjay < strDocketNoDkt.length; sanjay++) {
ItemCheckList itemCheckList = new ItemCheckList();
itemCheckList.setDocket_NO(strDocketNoDkt[sanjay]);
itemCheckList.setDocket_Date(strDocketDateDkt[sanjay]);
itemCheckList.setDocket_Origin(strDocketOriginDkt[sanjay]);
itemCheckList.setDocket_Destination(strDocketDestnDkt[sanjay]);
checkLists.add(itemCheckList);
}
checkAdapter = new ItemCheckAdapter(ActivityManifestEntry.this, checkLists, check_all);
manifestListView.setAdapter(checkAdapter);
}
} catch (Exception e) {
e.printStackTrace();
}

Android get elements from json array

I'm trying to get elements from my json array.
this is my json response:
{"IDs":["635426812801493839","635429094450867472","635433640807558204"]}
This is what I've tried so far:
itemList = new ArrayList<HashMap<String, String>>();
JSONArray a = jsonObj.getJSONArray(Constants.IDS);
int arrSize = a.length();
ArrayList<String> stringArray = new ArrayList<String>();
for (int i = 0; i < arrSize; ++i) {
JSONObject obj = a.getJSONObject(i);
stringArray.add(obj.toString());
item = new HashMap<String, String>();
item.put(Constants.ID, obj.toString());
itemList.add(item);
}
Log.e("ARR COUNT", "" + stringArray.size());
But I'm getting empty list. What is wrong with my code? Any help will be truly appreciated. Thanks.
The for loop should be
for (int i = 0; i < arrSize; ++i) {
stringArray.add(a.getString(i));
your the JSONArray contains already string
JSONObject obj = a.getJSONObject(i);
replace with
String str = a.getString(i);
Use this
itemList = new ArrayList<HashMap<String, String>>();
JSONArray a = jsonObj.getJSONArray(Constants.IDS);
int arrSize = a.length();
ArrayList<String> stringArray = new ArrayList<String>();
for (int i = 0; i < arrSize; ++i) {
stringArray.add(a.getString(i));
item = new HashMap<String, String>();
item.put(Constants.ID, obj.toString());
itemList.add(item);
}
Log.e("ARR COUNT", "" + stringArray.size());

How to set json data to list view?

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

Categories

Resources