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;
}
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
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);
}
}
}
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.
how is it possible to parse some Json Data from web and put them in a listview.
Inside of them i would like to search something, I'm searching now for a while in the internet but I wasn't successfull.
I still can Parse JSON and pu them in a listview but how can I search?
Here my Code
MainAct.:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "*****";
//JSON Node Names
private static final String TAG_OS = "android";
private static final String TAG_VER = "ver";
private static final String TAG_NAME = "name";
private static final String TAG_API = "api";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
List<list> varr = yourlist;
for (list result : varr) {
// action such as.. if result
}
hope this help