Parse JSON :Nested Objects in Android - android
I am pretty new to Android.I am trying to parse a JSON url. But I am getting following error "Json parsing error: No value for unofficial-summary".
Here is the response that I am getting.
Response from url: {"success":true,"data":{"summary":{"total":15616130,"confirmedCasesIndian":15616082,"confirmedCasesForeign":48,"discharged":13276039,"deaths":182553,"confirmedButLocationUnidentified":0},"unofficial-summary":[{"source":"covid19india.org","total":7945975,"recovered":7198877,"deaths":119538,"active":626192}],"regional":[{"loc":"Andaman and Nicobar Islands","confirmedCasesIndian":5466,"confirmedCasesForeign":0,"discharged":5243,"deaths":64,"totalConfirmed":5466},{"loc":"Andhra Pradesh","confirmedCasesIndian":976987,"confirmedCasesForeign":0,"discharged":915626,"deaths":7472,"totalConfirmed":976987},{"loc":"Arunachal Pradesh","confirmedCasesIndian":17113,"confirmedCasesForeign":0,"discharged":16835,"deaths":56,"totalConfirmed":17113},{"loc":"Assam","confirmedCasesIndian":227473,"confirmedCasesForeign":0,"discharged":217296,"deaths":1145,"totalConfirmed":227473},{"loc":"Bihar","confirmedCasesIndian":342059,"confirmedCasesForeign":0,"discharged":283863,"deaths":1841,"totalConfirmed":342059},{"loc":"Chandigarh","confirmedCasesIndian":35148,"confirmedCasesForeign":0,"discharged":30768,"deaths":421,"totalConfirmed":35148},{"loc":"Chhattisgarh","confirmedCasesIndian":574299,"confirmedCasesForeign":0,"discharged":442337,"deaths":6274,"totalConfirmed":574299},{"loc":"Dadra and Nagar Haveli and Daman and Diu","confirmedCasesIndian":5422,"confirmedCasesForeign":0,"discharged":4047,"deaths":4,"totalConfirmed":5422},{"loc":"Delhi","confirmedCasesIndian":905540,"confirmedCasesForeign":1,"discharged":807328,"deaths":12638,"totalConfirmed":905541},{"loc":"Goa","confirmedCasesIndian":69311,"confirmedCasesForeign":1,"discharged":60145,"deaths":926,"totalConfirmed":69312},{"loc":"Gujarat","confirmedCasesIndian":428177,"confirmedCasesForeign":1,"discharged":346063,"deaths":5615,"totalConfirmed":428178},{"loc":"Haryana","confirmedCasesIndian":371610,"confirmedCasesForeign":14,"discharged":318369,"deaths":3483,"totalConfirmed":371624},{"loc":"Himachal Pradesh","confirmedCasesIndian":79410,"confirmedCasesForeign":0,"discharged":68164,"deaths":1219,"totalConfirmed":79410},{"loc":"Jammu and Kashmir","confirmedCasesIndian":150238,"confirmedCasesForeign":0,"discharged":134697,"deaths":2071,"totalConfirmed":150238},{"loc":"Jharkhand","confirmedCasesIndian":172315,"confirmedCasesForeign":0,"discharged":137590,"deaths":1547,"totalConfirmed":172315},{"loc":"Karnataka","confirmedCasesIndian":1198644,"confirmedCasesForeign":0,"discharged":1025821,"deaths":13646,"totalConfirmed":1198644},{"loc":"Kerala","confirmedCasesIndian":1272637,"confirmedCasesForeign":8,"discharged":1148671,"deaths":4978,"totalConfirmed":1272645},{"loc":"Ladakh","confirmedCasesIndian":12556,"confirmedCasesForeign":0,"discharged":10610,"deaths":134,"totalConfirmed":12556},{"loc":"Lakshadweep","confirmedCasesIndian":1335,"confirmedCasesForeign":0,"discharged":817,"deaths":1,"totalConfirmed":1335},{"loc":"Madhya Pradesh","confirmedCasesIndian":433704,"confirmedCasesForeign":0,"discharged":350720,"deaths":4713,"totalConfirmed":433704},{"loc":"Maharashtra","confirmedCasesIndian":3960356,"confirmedCasesForeign":3,"discharged":3213464,"deaths":61343,"totalConfirmed":3960359},{"loc":"Manipur","confirmedCasesIndian":29869,"confirmedCasesForeign":0,"discharged":29106,"deaths":378,"totalConfirmed":29869},{"loc":"Meghalaya","confirmedCasesIndian":15116,"confirmedCasesForeign":0,"discharged":14105,"deaths":154,"totalConfirmed":15116},{"loc":"Mizoram","confirmedCasesIndian":5085,"confirmedCasesForeign":0,"discharged":4569,"deaths":12,"totalConfirmed":5085},{"loc":"Nagaland","confirmedCasesIndian":12650,"confirmedCasesForeign":0,"discharged":12299,"deaths":94,"totalConfirmed":12650},{"loc":"Odisha","confirmedCasesIndian":377464,"confirmedCasesForeign":0,"discharged":349377,"deaths":1953,"totalConfirmed":377464},{"loc":"Puducherry","confirmedCasesIndian":48974,"confirmedCasesForeign":0,"discharged":43184,"deaths":717,"totalConfirmed":48974},{"loc":"Punjab","confirmedCasesIndian":309316,"confirmedCasesForeign":0,"discharged":264562,"deaths":8045,"t
What am I doing wrong?
package com.sudarshan.jsonparse2;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://api.rootnet.in/covid19-in/stats/latest";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONObject c = jsonObj.getJSONArray("unofficial-summary").getJSONObject(0);
String source = c.getString("source");
int total = c.getInt("total");
int recovered = c.getInt("recovered");
int deaths = c.getInt("deaths");
int active = c.getInt("active");
// tmp hash map for single contact
HashMap<String, String> summary = new HashMap<>();
// adding each child node to HashMap key => value
summary.put("source", "source: "+source);
summary.put("total", "total:" +String.valueOf(total));
summary.put("recovered", "recovered" +String.valueOf(recovered));
summary.put("deaths", "deaths" + String.valueOf(deaths));
summary.put("active", "active" + String.valueOf(active));
// adding contact to contact list
contactList.add(summary);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,
R.layout.list_item, new String[]{ "source","total","recovered","deaths","active"},
new int[]{R.id.source, R.id.total,R.id.recovered,R.id.deaths,R.id.active});
lv.setAdapter(adapter);
}
}
}
Json is like
{
"success": true,
"data": {
"summary": {
//...
},
"unofficial-summary": [
{
//...
}]
}
}
Shoud get data first:
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://api.rootnet.in/covid19-in/stats/latest";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
// Add: 2021/4/26 add get data first
JSONObject jsonObj = new JSONObject(jsonStr);
String data = jsonObj.getString("data");
Log.w(TAG, "doInBackground: " + data);
// Getting JSON Array node
JSONObject c = new JSONObject(data).getJSONArray("unofficial-summary").getJSONObject(0);
String source = c.getString("source");
int total = c.getInt("total");
int recovered = c.getInt("recovered");
int deaths = c.getInt("deaths");
int active = c.getInt("active");
// tmp hash map for single contact
HashMap<String, String> summary = new HashMap<>();
// adding each child node to HashMap key => value
summary.put("source", "source: " + source);
summary.put("total", "total:" + String.valueOf(total));
summary.put("recovered", "recovered" + String.valueOf(recovered));
summary.put("deaths", "deaths" + String.valueOf(deaths));
summary.put("active", "active" + String.valueOf(active));
// adding contact to contact list
contactList.add(summary);
} catch (final JSONException e) {
//...
}
} else {
//...
}
return null;
}
Related
Json Parsing error string converting
I wrote this code and ı wrote httphandler etc. But when ı ran the app ı saw error: ............. Java parsing error:Value of type java.lang.String cannot be converted to JSONObject ı searched on internet but ı cannot solve it. what is wrong? where should ı add code? MainActivity.java import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { private String TAG = MainActivity.class.getSimpleName(); private ListView lv; ArrayList<HashMap<String, String>> contactList; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contactList = new ArrayList<>(); lv = findViewById(R.id.list); new GetContacts().execute(); } private class GetContacts extends AsyncTask<Void, Void, Void> { #Override protected void onPreExecute() { super.onPreExecute(); Toast.makeText(MainActivity.this, "Json Data is downloading", Toast.LENGTH_LONG).show(); } #Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // Making a request to url and getting response String url = "http://api.androidhive.info/contacts/"; String jsonStr = sh.makeServiceCall(url); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node JSONArray contacts = jsonObj.getJSONArray("contacts"); // looping through All Contacts for (int i = 0; i < contacts.length(); i++) { JSONObject c = contacts.getJSONObject(i); String id = c.getString("id"); String name = c.getString("name"); String email = c.getString("email"); // Phone node is JSON Object JSONObject phone = c.getJSONObject("phone"); String mobile = phone.getString("mobile"); // tmp hash map for single contact HashMap<String, String> contact = new HashMap<>(); // adding each child node to HashMap key => value contact.put("id", id); contact.put("name", name); contact.put("email", email); contact.put("mobile", mobile); // adding contact to contact list contactList.add(contact); } } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { #Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { #Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show(); } }); } return null; } #Override protected void onPostExecute(Void result) { super.onPostExecute(result); ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList, R.layout.list_item, new String[]{"email", "mobile"}, new int[]{R.id.email, R.id.mobile}); lv.setAdapter(adapter); } } } HttpHandler.java import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; public class HttpHandler { private static final String TAG = HttpHandler.class.getSimpleName(); public HttpHandler() { } public String makeServiceCall(String reqUrl) { String response = null; try { URL url = new URL(reqUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); response = convertStreamToString(in); } catch (MalformedURLException e) { Log.e(TAG, "MalformedURLException: " + e.getMessage()); } catch (ProtocolException e) { Log.e(TAG, "ProtocolException: " + e.getMessage()); } catch (IOException e) { Log.e(TAG, "IOException: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } return response; } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } }
You need to receive JSON content but the server is returning HTML content. Modify your server and add application/json as content type: Content-type:application/json
How to display HTML in android app for this code?
Here is my code: #Override protected void onPostExecute(Void result) { super.onPostExecute(result); ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList, R.layout.list_item, new String[]{ "rendered", "renderedcont"}, new int[]{R.id.title, R.id.content}); //new int[]{R.id.title}); lv.setAdapter(adapter); } How I can show the text with HTML supported? Here is the full code: package com.codespeedy.jsonreader; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { private String TAG = MainActivity.class.getSimpleName(); private ListView lv; ArrayList<HashMap<String, String>> contactList; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contactList = new ArrayList<>(); lv = (ListView) findViewById(R.id.list); new GetContacts().execute(); } private class GetContacts extends AsyncTask<Void, Void, Void> { #Override protected void onPreExecute() { super.onPreExecute(); Toast.makeText(MainActivity.this, "JSON Is Downloading...", Toast.LENGTH_LONG).show(); } #Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // Making a request to url and getting response String url = "https://www.eyeswift.com/wp-json/wp/v2/posts/"; String jsonStr = sh.makeServiceCall(url); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { // JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node JSONArray jsnarray = new JSONArray(jsonStr); // looping through All Contacts for (int i = 0; i < jsnarray.length(); i++) { JSONObject c = jsnarray.getJSONObject(i); String id = c.getString("id"); String date = c.getString("date"); String type = c.getString("type"); String link = c.getString("link"); String author = c.getString("author"); // String gender = c.getString("title"); // Phone node is JSON Object JSONObject title = c.getJSONObject("title"); String rendered = title.getString("rendered"); JSONObject content = c.getJSONObject("content"); String renderedcont = content.getString("rendered"); // tmp hash map for single contact HashMap<String, String> contact = new HashMap<>(); // adding each child node to HashMap key => value contact.put("id", id); contact.put("date", date); contact.put("author", author); contact.put("link", link); contact.put("rendered", rendered); contact.put("renderedcont", renderedcont); // adding contact to contact list contactList.add(contact); } } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { #Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { #Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show(); } }); } return null; } #Override protected void onPostExecute(Void result) { super.onPostExecute(result); ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList, R.layout.list_item, new String[]{ "rendered", "renderedcont"}, new int[]{R.id.title, R.id.content}); //new int[]{R.id.title}); lv.setAdapter(adapter); } } }
How can i write Android Json parsing without array name
package info.androidhive.jsonparsing; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { private String TAG = MainActivity.class.getSimpleName(); private ProgressDialog pDialog; private ListView lv; // URL to get contacts JSON private static String url = "http://api.androidhive.info/contacts/"; ArrayList<HashMap<String, String>> contactList; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contactList = new ArrayList<>(); lv = (ListView) findViewById(R.id.list); new GetContacts().execute(); } /** * Async task class to get json by making HTTP call */ private class GetContacts extends AsyncTask<Void, Void, Void> { #Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); pDialog.show(); } #Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node JSONArray contacts = jsonObj.getJSONArray("contacts"); // looping through All Contacts for (int i = 0; i < contacts.length(); i++) { JSONObject c = contacts.getJSONObject(i); String id = c.getString("id"); String name = c.getString("name"); String email = c.getString("email"); String address = c.getString("address"); String gender = c.getString("gender"); // Phone node is JSON Object JSONObject phone = c.getJSONObject("phone"); String mobile = phone.getString("mobile"); String home = phone.getString("home"); String office = phone.getString("office"); // tmp hash map for single contact HashMap<String, String> contact = new HashMap<>(); // adding each child node to HashMap key => value contact.put("id", id); contact.put("name", name); contact.put("email", email); contact.put("mobile", mobile); // adding contact to contact list contactList.add(contact); } } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { #Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG) .show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { #Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG) .show(); } }); } return null; } #Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( MainActivity.this, contactList, R.layout.list_item, new String[]{"name", "email", "mobile"}, new int[]{R.id.name, R.id.email, R.id.mobile}); lv.setAdapter(adapter); } } } This is the code i found internet. It works well but my problem is it's getting arrays with an array name. Here is the Json url : http://api.androidhive.info/contacts/ And this app also has another class called HttpHandler: package info.androidhive.jsonparsing; import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; public class HttpHandler { private static final String TAG = HttpHandler.class.getSimpleName(); public HttpHandler() { } public String makeServiceCall(String reqUrl) { String response = null; try { URL url = new URL(reqUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); response = convertStreamToString(in); } catch (MalformedURLException e) { Log.e(TAG, "MalformedURLException: " + e.getMessage()); } catch (ProtocolException e) { Log.e(TAG, "ProtocolException: " + e.getMessage()); } catch (IOException e) { Log.e(TAG, "IOException: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } return response; } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } } My problem is how can i edit this codes to another url. My json url is here : http://mysafeinfo.com/api/data?list=englishmonarchs&format=json As you can see there is no array name. How can i manage with that ? Any help will welcome
It's really simple you just have to get JSONArray object directly like this: ` #Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { // Getting JSON Array node JSONArray contacts = new JSONArray(jsonStr); // looping through All Contacts for (int i = 0; i < contacts.length(); i++) { JSONObject c = contacts.getJSONObject(i); String id = c.getString("nm"); String name = c.getString("cty"); String email = c.getString("hse"); String address = c.getString("yrs"); // tmp hash map for single contact HashMap<String, String> contact = new HashMap<>(); // adding each child node to HashMap key => value contact.put("id", id); contact.put("name", name); contact.put("email", email); contact.put("address", address); // adding contact to contact list contactList.add(contact); } } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { #Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG) .show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { #Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG) .show(); } }); } return null; } ` Try this.....hope it will work for you.
Use JsonArray listItem = new JsonArray(responseString); No need name.
There is also a simple solution. You can use google Gson library to parse json. All you have to do is create a class according to the json format i-e variable names same as name of json objects in json string/file.
fetching JSON data from a url and then displaying it in a ListView in android
I am fetching JSON data from a URL and then displaying it in a ListView in the MainActivity. I have made proper connection to the JSON file URL and I am able to fetch the data from the URL into a string but now I am trying to display it in a ListView using ListAdapter but it's not displaying any data in it. My JSON data is like: { "result": 1, "data": [{ "id": 1, "name": "Aconitum", "url": "https:\/\/upload.wikimedia.org\/wikipedia\/commons\/7\/7e\/Aconitum_degenii.jpg" }, { "id": 2, "name": "African lily", "url": "http:\/\/i1.wp.com\/cottagegardenflowershop.co.uk\/wp-content\/uploads\/2014\/09\/1040668-90x90.jpg?ssl=1" }, { "id": 3, "name": "Alpine thistle", "url": "http:\/\/i1.wp.com\/cottagegardenflowershop.co.uk\/wp-content\/uploads\/2014\/09\/1040668-90x90.jpg?ssl=1" }, I am storing the data in the form of hashmap in the arrayList of this format. ArrayList> contactList; My main activity.java is: package com.example.hsports.flowers; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Display; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { public static String url="http://development.easystartup.org/NO/Backend/flower.php"; private String TAG = MainActivity.class.getSimpleName(); private ProgressDialog pDialog; private ListView lv; ArrayList<HashMap<String, String>> contactList; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contactList = new ArrayList<>(); lv = (ListView) findViewById(R.id.listview); new GetContacts().execute(); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { #Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String url=contactList.get(position).get("url"); System.out.println("hello"); } }); } private class GetContacts extends AsyncTask<Void, Void, Void> { #Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node JSONArray contacts = jsonObj.getJSONArray("data"); // looping through All Contacts for (int i = 0; i < 28; i++) { JSONObject c = contacts.getJSONObject(i); if(c==null) { continue; } String id = c.getString("id"); String name = c.getString("name"); String urlInjson = c.getString("url"); //String address = c.getString("address"); //String gender = c.getString("gender"); // tmp hash map for single contact HashMap<String, String> contact = new HashMap<>(); // adding each child node to HashMap key => value contact.put("id", id); contact.put("name", name); contact.put("url", urlInjson); // adding contact to contact list contactList.add(contact); } } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { #Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG) .show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { #Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG) .show(); } }); } return null; } #Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); pDialog.show(); } protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( MainActivity.this, contactList, R.layout.support_simple_spinner_dropdown_item, new String[]{"name"}, new int[]{R.id.flowerName}); lv.setAdapter(adapter); } } } how can I populate just the "name" from the Arraylist inside that ListView?
There should be a change in this statement: ListAdapter adapter = new SimpleAdapter( MainActivity.this, contactList, R.layout.support_simple_spinner_dropdown_item, new String[]{"name"}, new int[]{R.id.flowerName}); Where R.layout.list_view should be given where this is the view which defines the ListView layout.
Adding Searchview in Listview android
I want to add a searchview to filter results. Please help me with this. I have tried all the methods available online but all are for custom adapter and none seems to be working for my project. My MainActivity.class package info.androidhive.jsonparsing; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { private String TAG = MainActivity.class.getSimpleName(); private ProgressDialog pDialog; private ListView lv; // URL to get contacts JSON private static String url = "http://api.androidhive.info/contacts/"; ArrayList<HashMap<String, String>> contactList; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contactList = new ArrayList<>(); lv = (ListView) findViewById(R.id.list); new GetContacts().execute(); } /** * Async task class to get json by making HTTP call */ private class GetContacts extends AsyncTask<Void, Void, Void> { #Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); pDialog.show(); } #Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node JSONArray contacts = jsonObj.getJSONArray("contacts"); // looping through All Contacts for (int i = 0; i < contacts.length(); i++) { JSONObject c = contacts.getJSONObject(i); String id = c.getString("id"); String name = c.getString("name"); String email = c.getString("email"); String address = c.getString("address"); String gender = c.getString("gender"); // Phone node is JSON Object JSONObject phone = c.getJSONObject("phone"); String mobile = phone.getString("mobile"); String home = phone.getString("home"); String office = phone.getString("office"); // tmp hash map for single contact HashMap<String, String> contact = new HashMap<>(); // adding each child node to HashMap key => value contact.put("id", id); contact.put("name", name); contact.put("email", email); contact.put("mobile", mobile); // adding contact to contact list contactList.add(contact); } } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { #Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG) .show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { #Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG) .show(); } }); } return null; } #Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( MainActivity.this, contactList, R.layout.list_item, new String[]{"name", "email", "mobile"}, new int[]{R.id.name, R.id.email, R.id.mobile}); lv.setAdapter(adapter); } } } My HttpHandler.class package info.androidhive.jsonparsing; import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; /** * Created by Ravi Tamada on 01/09/16. * www.androidhive.info */ public class HttpHandler { private static final String TAG = HttpHandler.class.getSimpleName(); public HttpHandler() { } public String makeServiceCall(String reqUrl) { String response = null; try { URL url = new URL(reqUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); response = convertStreamToString(in); } catch (MalformedURLException e) { Log.e(TAG, "MalformedURLException: " + e.getMessage()); } catch (ProtocolException e) { Log.e(TAG, "ProtocolException: " + e.getMessage()); } catch (IOException e) { Log.e(TAG, "IOException: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } return response; } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } }
U can use latest recylerview to achieve this (robust and better performance) Or Easy way: try this MaterialSearchViewlibrary