The Class:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Read().execute("masjids");
}
public JSONObject retrieveInfo(String radius) throws ClientProtocolException,
IOException, JSONException {
StringBuilder url = new StringBuilder(
"http://iqamah.org/api/index.php?lat=43&long=-79&radius=");
url.append(radius);
HttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(url.toString());
HttpResponse r = httpclient.execute(get);
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject timeline = new JSONObject(data);
return timeline.getJSONObject("1");
}
private class Read extends AsyncTask<String, Integer, String> {
ProgressDialog pd = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Loading...");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
JSONObject json = retrieveInfo("200");
return json.getString(arg0[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String status) {
super.onPostExecute(status);
pd.dismiss();
TextView day = (TextView) findViewById(R.id.displayDay);
day.setText("Masjid: " + status);
}
}
}
The JSON:
{
"status": "ok",
"masjids": [
{
"id": "44|Madina Masjid|1200 Danforth Ave, Toronto|49.99"
},
{
"id": "39|Darul Taqwa|1 Thorncliffe Park Drive, Toronto|51.59"
},
{
"id": "43|Darul Khair|25 St Dennis, Toronto|52.12"
}
]
}
I am trying to access the masjids->id[0] array, how can I do this with the above code?
String data = "{ "status": "ok", "masjids": [ { "id": "44|Madina Masjid|1200 Danforth Ave, Toronto|49.99" }, { "id": "39|Darul Taqwa|1 Thorncliffe Park Drive, Toronto|51.59" }, { "id": "43|Darul Khair|25 St Dennis, Toronto|52.12" } ] }";
JSONObject jObj = new JSONObject(data);
JSONArray jArray_masjids = jObj.getJSONArray("masjids");
String address = jArray_masjids.getJSONObject(0).getString("id");
JSONObject timeline = new JSONObject(data);
JasonArry jarry=timeline.getJsonArray("masjids");
for (int i = 0; i < jarry.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
String newStr = explrObject.getString("id");
}
Try this,
String data = "{ "status": "ok", "masjids": [ { "id": "44|Madina Masjid|1200 Danforth Ave, Toronto|49.99" }, { "id": "39|Darul Taqwa|1 Thorncliffe Park Drive, Toronto|51.59" }, { "id": "43|Darul Khair|25 St Dennis, Toronto|52.12" } ] }";
JSONObject jObj = new JSONObject(data);
JSONArray jArray_masjids = jObj.getJSONArray("masjids");
for(int i = 0 ;i<jArray_masjids;i++){
String address = jsonArray.getJSONObject(i).getString("id");
}
Related
I want to show the userlist from JSON object url with POST method but its show me the error some thing like this :- Value null of type org.json.JSONObject$1 cannot be converted to JSONObject . and show the blank data in the activity. In this api link its shows :-
{
"data": [{
"id": "38",
"username": "atif"
}, {
"id": "37",
"username": "ajay1"
}, {
"id": "36",
"username": "akki"
}, {
"id": "35",
"username": "a"
}, {
"id": "34",
"username": "abc"
}, {
"id": "33",
"username": "ankit"
}, {
"id": "32",
"username": "riya"
}, {
"id": "31",
"username": "akshay"
}, {
"id": "5",
"username": "chitran"
}, {
"id": "4",
"username": "kunal"
}, {
"id": "3",
"username": "anshul"
}, {
"id": "2",
"username": "XYZ"
}, {
"id": "1",
"username": "XYZ"
}],
"resp_msg": "Success",
"resp_code": 200
}
Here is my code for showing the list from the json parsing.
parsing data
http://codexpertise.com/codexpertise.com/apitest/service.php
{
"type":"online_user"
}
Userlist.java
public class Userlist extends AppCompatActivity {
private String TAG = Userlist.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://codexpertise.com/codexpertise.com/apitest/service.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userlist);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.listView1);
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(Userlist.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("data");
// 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("username");
// 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);
// 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(
Userlist.this, contactList,
R.layout.list_items, new String[]{"id", "username"}, new int[]{R.id.name,
R.id.email});
lv.setAdapter(adapter);
}
}
}
HttpHandler.java
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("POST");
// 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();
}
}
list_items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#color/colorPrimaryDark"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#color/colorAccent" />
</LinearLayout>
activity_userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Userlist" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
According to your JSON check below try block
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("data");
// 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("username");//change here
// Phone node is JSON Object
// JSONObject phone = c.getJSONObject("phone"); //this object not in JSON so remove it..
//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);
// adding contact to contact list
contactList.add(contact);
}
This is my android code. When I am trying to parse my jsonArray it gives me an error that string cannot be converted to Jsonarray through my response is json array:
public class Main2Activity extends AppCompatActivity {
EditText tv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tv1= (EditText) findViewById(R.id.textView);
DefaultOAuthConsumer defaultOAuthConsumer = new DefaultOAuthConsumer("my consumer key","my secret key");
//REQUEST URL
String url = "http://back.unaux.com/wp-json/wc/v2/products";
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
try {
url = defaultOAuthConsumer.sign(url);
Toast.makeText(this, url, Toast.LENGTH_SHORT).show();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
JsonArrayRequest req=new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(Main2Activity.this, response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main2Activity.this,"Error"+error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(req);
}
}
This is my response for json
[
{
"id":685,
"name":"Caramel-min",
"slug":"caramel-min",
"permalink":"http:\/\/back.unaux.com\/product\/caramel-min\/",
"date_created":"2017-09-26T18:56:01",
"date_created_gmt":"2017-09-26T18:56:01",
"date_modified":"2017-09-27T12:27:56",
"date_modified_gmt":"2017-09-27T12:27:56",
"type":"variable",
"status":"publish",
"featured":false,
"catalog_visibility":"visible",
"description":"",
"short_description":"",
"sku":"",
"price":"350",
"regular_price":"350",
"sale_price":"",
"date_on_sale_from":null,
"date_on_sale_from_gmt":null,
"date_on_sale_to":null,
"date_on_sale_to_gmt":null,
"price_html":"<span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">₹<\/span>350.00<\/span> – <span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">₹<\/span>500.00<\/span>",
"on_sale":false,
"purchasable":true,
"total_sales":2,
"virtual":false,
"downloadable":false,
"downloads":[
],
"download_limit":-1,
"download_expiry":-1,
"external_url":"",
"button_text":"",
"tax_status":"taxable",
"tax_class":"",
"manage_stock":false,
"stock_quantity":null,
"in_stock":true,
"backorders":"no",
"backorders_allowed":false,
"backordered":false,
"sold_individually":false,
"weight":"1.0",
"dimensions":{
"length":"",
"width":"",
"height":""
},
"shipping_required":true,
"shipping_taxable":true,
"shipping_class":"",
"shipping_class_id":0,
"reviews_allowed":true,
"average_rating":"0.00",
"rating_count":0,
"related_ids":[
],
"upsell_ids":[
],
"cross_sell_ids":[
],
"parent_id":0,
"purchase_note":"",
"categories":[
{
"id":43,
"name":"Chocolate",
"slug":"chocolate"
}
],
"tags":[
],
"images":[
{
"id":710,
"date_created":"2017-09-27T12:25:19",
"date_created_gmt":"2017-09-27T12:25:19",
"date_modified":"2017-09-27T12:25:19",
"date_modified_gmt":"2017-09-27T12:25:19",
"src":"http:\/\/back.unaux.com\/wp-content\/uploads\/2015\/08\/Caramel-min-1.jpg",
"name":"Caramel-min-1",
"alt":"",
"position":0
},
{
"id":710,
"date_created":"2017-09-27T12:25:19",
"date_created_gmt":"2017-09-27T12:25:19",
"date_modified":"2017-09-27T12:25:19",
"date_modified_gmt":"2017-09-27T12:25:19",
"src":"http:\/\/back.unaux.com\/wp-content\/uploads\/2015\/08\/Caramel-min-1.jpg",
"name":"Caramel-min-1",
"alt":"",
"position":1
}
],
"attributes":[
{
"id":0,
"name":"Kg",
"position":0,
"visible":true,
"variation":true,
"options":[
"1\/2",
"1.0",
"2.0",
"3.0",
"4.0",
"5.0"
]
}
],
"default_attributes":[
],
"variations":[
705,
704
],
"grouped_products":[
],
"menu_order":0,
"meta_data":[
{
"id":1369,
"key":"_vc_post_settings",
"value":{
"vc_grid_id":[
]
}
},
{
"id":1404,
"key":"slide_template",
"value":"default"
}
],
"_links":{
"self":[
{
"href":"http:\/\/back.unaux.com\/wp-json\/wc\/v2\/products\/685"
}
],
"collection":[
{
"href":"http:\/\/back.unaux.com\/wp-json\/wc\/v2\/products"
}
]
}
}
]
you have array inside array.Test like that : add volley library
oncreate(){
sendRequest(); }
private void sendRequest() {
try {
StringRequest stringRequest = new StringRequest(test_urls,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("respnose", "" + response);
parseJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(Page_details_bkp.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(Page_details_bkp.this);
requestQueue.add(stringRequest);
} catch (Exception e) {
progressDialog.dismiss();
Log.e("sendreq:", e.toString());
}
}
public void parseJSON(String json) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
try {
userID = jsonObject.getString("api_status");
//ids = new String[jsonArray.length()];
if (userID.equals("success")) {
ids = new String[users.length()];
names = new String[users.length()];
emails = new String[users.length()];
sub_images1 = new String[users.length()][3];
sub_ids = new String[users.length()][3];
// images = new String[users.length()];
//log.e("length :", users.length() + "");
for (int i = 0; i < users.length(); i++) {
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString(KEY_ID);
names[i] = jo.getString(KEY_NAME);
emails[i] = jo.getString(KEY_EMAIL);
try {
JSONObject locArrObj = users.getJSONObject(i); // cotains one "out" array
JSONArray conferenceLocArr = locArrObj.getJSONArray("posts");
if (conferenceLocArr.length() > 0) {
// this array has two objects and each object has array
JSONObject o = null;
for (int ii = 0; ii < conferenceLocArr.length(); ii++) {
o = conferenceLocArr.getJSONObject(ii); // it has one array
try {
// if (!o.getString("image").equals("")) {
sub_images1[i][ii] = o.getString("image");
sub_ids[i][ii] = o.getString("id");
//log.e("Main response:", ids[i] + "," + ids[i] + "," + names[i] + "," + emails[i]);
//}
} catch (JSONException e) {
e.printStackTrace();
//log.e("sub response:", e.toString());
}
// sub_images1[i] = o.getString("image");
// do your work with Stage 1 and guests
// and for second object for Stage 2 and guests.
}
Categories movie = new Categories(ids[i], names[i], emails[i], "2015", sub_images1[i][0],
sub_ids[i][0], sub_images1[i][1], sub_ids[i][1], sub_images1[i][2],
sub_ids[i][2]);
movieList.add(movie);
}
} catch (JSONException e) {
//log.e("response:", e.toString());
e.printStackTrace();
}
}
} else {
}
} catch (JSONException e) {
//log.e("response:", e.toString());
e.printStackTrace();
} finally {
prepareMovieData();
}
} catch (JSONException e) {
//log.e("parse:", e.toString());
}
}
public class FindPlaces extends AppCompatActivity {
private static final String MAP_API_URL = "https://api.foursquare.com/v2/venues/categories?client_id=AW31XQWUOLJWFZCFNZZ04I4IQFUFYIFAFDEHEYITEBBDHIVB&client_secret=R10S3ACA5VFOTGVG2LW1N4YONU30LQ3IE0DKIG1JNHN2QNWE&v=20170811&m=foursquare";
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> categoriesList;
ArrayList<Categories> categories;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_places);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Locate the Categories Class
categories = new ArrayList<Categories>();
// Create an array to populate the spinner
categoriesList = new ArrayList<String>();
// JSON file URL address
jsonobject = JSONfunctions
.getJSONfromURL("https://api.foursquare.com/v2/venues/categories?client_id=CONSUMER_KEY&client_secret=CONSUMER_SECRET&v=20170811&m=foursquare");
try {
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("categories");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Categories cat = new Categories();
cat.setName(jsonobject.optString("name"));
categories.add(cat);
// Populate spinner with country names
categoriesList.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in activity_main.xml
Spinner mySpinner = (Spinner) findViewById(R.id.spinnerCategories);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(FindPlaces.this,
android.R.layout.simple_spinner_dropdown_item,
categoriesList));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
TextView txtname = (TextView) findViewById(R.id.tvName);
txtname.setText(categories.get(position).getName());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
This is my class to inflate the spinner.
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
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();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
This is where i handle with the http request
{ "response": {
"categories": [
{
"id": "4d4b7104d754a06370d81259",
"name": "Arts & Entertainment",
"pluralName": "Arts & Entertainment",
"shortName": "Arts & Entertainment",
"icon": {
"prefix": "https://ss3.4sqi.net/img/categories_v2/arts_entertainment/default_",
"suffix": ".png"
},
"categories": [
{
"id": "56aa371be4b08b9a8d5734db",
"name": "Amphitheater",
"pluralName": "Amphitheaters",
"shortName": "Amphitheater",
"icon": {
"prefix": "https://ss3.4sqi.net/img/categories_v2/arts_entertainment/default_",
"suffix": ".png"
}
and this is the json.
How can i change to get request instead a post request?
and how can i populate my spinner?
Thanks in advance.
I have a jsonArray which I want to parse in my android app.
The array:-
[
{
"id": 96905,
"category": "topup",
"detail": "Full talktime of Rs.55 + 1 local airtel SMS free for 1 day",
"price": 55,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"validity": "7 days",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 55
},
{
"id": 90397,
"category": "topup",
"price": 510,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 520
},
{
"id": 90399,
"category": "topup",
"price": 1000,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 1020
}]
My android Code:-
Asynctask:-
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Android JSON Parse Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
JSONObject jo;
JSONArray ja2 = JSONfunctions.getJSONfromURL("http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam");
for (int i = 0; i < ja2.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jo = ja2.getJSONObject(i);
map.put("rank", jo.getString("price"));
map.put("country", jo.getString("validity"));
map.put("population", jo.getString("talktime"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listview = (ListView) findViewById(R.id.listview);
adapter = new ListViewAdapter(MainActivity.this, arraylist);
listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
JsonFunctions.java
public class JSONfunctions {
public static JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
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();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
The error I get:-
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:67)
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:39)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
The json is hosted here
I was following this tutorial for learning json parsing, but this tutorial uses jsonObject and I am not able to parse the json array.
Not a duplicate to this :-Sending and Parsing JSON Objects or this How to parse this JSON Array in android?
Let me offer an alternate solution (of sorts). A much simpler version of your existing code would be:
Updated code:
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist = new ArrayList<>();
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(TestListActivity.this);
mProgressDialog.setTitle("Android JSON Parse Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam";
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
okHttpClient.setRetryOnConnectionFailure(true);
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
String strResult = response.body().string();
JSONArray JARoot = new JSONArray(strResult);
for (int i = 0; i < JARoot.length(); i++) {
JSONObject JORoot = JARoot.getJSONObject(i);
HashMap<String, String> map = new HashMap<>();
if (JORoot.has("category") && JORoot.getString("category").equals("topup")) {
if (JORoot.has("id")) {
map.put("id", JORoot.getString("id"));
}
if (JORoot.has("category")) {
map.put("category", JORoot.getString("category"));
}
if (JORoot.has("detail")) {
map.put("detail", JORoot.getString("detail"));
} else {
map.put("detail", null);
}
if (JORoot.has("price")) {
map.put("price", JORoot.getString("price"));
}
/** ADD THE COLLECTED DATA TO THE ARRAY LIST **/
arraylist.add(map); /* THE DATA WILL ONLY BE ADDED IF THE CATEGORY = "topup" */
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ListView testList = (ListView) findViewById(R.id.testList);
TestListAdapter adapter = new TestListAdapter(TestListActivity.this, arraylist);
testList.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
private class TestListAdapter extends BaseAdapter {
Activity activity;
// LAYOUTINFLATER TO USE A CUSTOM LAYOUT
LayoutInflater inflater = null;
// ARRAYLIST TO GET DATA FROM THE ACTIVITY
ArrayList<HashMap<String, String>> arrItem;
public TestListAdapter(Activity activity, ArrayList<HashMap<String, String>> arrItem) {
this.activity = activity;
// CAST THE CONTENTS OF THE ARRAYLIST IN THE METHOD TO THE LOCAL INSTANCE
this.arrItem = arrItem;
// INSTANTIATE THE LAYOUTINFLATER
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrItem.size();
}
#Override
public Object getItem(int position) {
return arrItem.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// A VIEWHOLDER INSTANCE
ViewHolder holder;
// CAST THE CONVERTVIEW IN A VIEW INSTANCE
View vi = convertView;
// CHECK CONVERTVIEW STATUS
if (convertView == null) {
// CAST THE CONVERTVIEW INTO THE VIEW INSTANCE vi
vi = inflater.inflate(R.layout.test_item, null);
// INSTANTIATE THE VIEWHOLDER INSTANCE
holder = new ViewHolder();
/***** CAST THE LAYOUT ELEMENTS *****/
/* TOP (PRIMARY) ELEMENTS */
holder.txtPrice = (TextView) vi.findViewById(R.id.txtPrice);
holder.txtDetail = (TextView) vi.findViewById(R.id.txtDetail);
// SET THE TAG TO "vi"
vi.setTag(holder);
} else {
// CAST THE VIEWHOLDER INSTANCE
holder = (ViewHolder) vi.getTag();
}
if (arrItem.get(position).get("price") != null) {
String strPrice = arrItem.get(position).get("price");
holder.txtPrice.setText("PRICE: " + strPrice);
}
if (arrItem.get(position).get("detail") != null) {
String strDetail = arrItem.get(position).get("detail");
holder.txtDetail.setText("DETAIL: " + strDetail);
} else {
holder.txtDetail.setText("DETAIL: NA");
}
return vi;
}
private class ViewHolder {
/* TOP (PRIMARY) ELEMENTS */
TextView txtPrice;
TextView txtDetail;
}
}
For the sake of completeness, I am also including the code for the adapter. It is a simple implementation. Do clean it up / optimize it / customize as per your requirement.
This piece of code has been tested prior to being posted (see screenshot of Logs at the bottom)
This uses the OkHttp library. Add this compile statement to the dependencies section of the module's gradle file: compile 'com.squareup.okhttp:okhttp:2.5.0'. Check the link for an updated version.
The example code uses if statements considering that not every record has the same set of nodes.
You BufferReader is not working as expected in your class JSONfunctions , do some changes in your class and it should looks like
JSONfunctions.java
public class JSONfunctions {
public static JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
StringBuffer sb = new StringBuffer("");
try {
URL urls = new URL(url);
URLConnection urlConnection;
urlConnection = urls.openConnection();
InputStream in = urlConnection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
result=sb.toString();
} catch (IOException e) {}
catch (Exception e) {}
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
and to avoid Exception check if JSONArray is not null then only it goes to run for loop like this :
JSONArray ja2 = JSONfunctions.getJSONfromURL("http://app.ireff.in:9090/IreffWeb/android? service=airtel&circle=assam");
if(ja2!=null)
for (int i = 0; i < ja2.length(); i++) {}
jsonResponse="";
for(int i = 0; i<response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String id = person.getString("id");
String category = person.getString("category");
}
I am parsing JSON data into ListView, and successfully parsed first level of JSON in MainActivity.java, where i am showing list of Main Locations, like:
Inner Locations
Outer Locations
Now i want whenever i do tap on Inner Locations then in SecondActivity it should show Delhi and NCR in a List, same goes for Outer Locations as well, in this case whenever user do tap need to show USA
JSON look like:
{
"all": [
{
"title": "Inner Locations",
"maps": [
{
"title": "Delhi",
"markers": [
{
"name": "Connaught Place",
"latitude": 28.632777800000000000,
"longitude": 77.219722199999980000
},
{
"name": "Lajpat Nagar",
"latitude": 28.565617900000000000,
"longitude": 77.243389100000060000
}
]
},
{
"title": "NCR",
"markers": [
{
"name": "Gurgaon",
"latitude": 28.440658300000000000,
"longitude": 76.987347699999990000
},
{
"name": "Noida",
"latitude": 28.570000000000000000,
"longitude": 77.319999999999940000
}
]
}
]
},
{
"title": "Outer Locations",
"maps": [
{
"title": "United States",
"markers": [
{
"name": "Virgin Islands",
"latitude": 18.335765000000000000,
"longitude": -64.896335000000020000
},
{
"name": "Vegas",
"latitude": 36.114646000000000000,
"longitude": -115.172816000000010000
}
]
}
]
}
]
}
Note: But whenever i do tap on any of the ListItem in first activity, not getting any list in SecondActivity, why ?
MainActivity.java:-
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://10.0.2.2/locations.json");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("all");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("title", jsonobject.getString("title"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
Intent sendtosecond = new Intent(MainActivity.this, SecondActivity.class);
// Pass all data rank
sendtosecond.putExtra("title", arraylist.get(position).get(MainActivity.TITLE));
Log.d("Tapped Item::", arraylist.get(position).get(MainActivity.TITLE));
startActivity(sendtosecond);
}
});
}
}
}
SecondActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
Intent in = getIntent();
strReceived = in.getStringExtra("title");
Log.d("Received Data::", strReceived);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://10.0.2.2/locations.json");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("maps");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("title", jsonobject.getString("title"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
try below method:-
try
{
JSONObject j = new JSONObject("your json response");
JSONArray all = j.getJSONArray("all");
for (int i = 0; i < all.length(); i++)
{
JSONObject data = all.getJSONObject(i);
System.out.println("title =>"+data.getString("title"));
JSONArray maps = data.getJSONArray("maps");
for (int k = 0; k < maps.length(); k++)
{
JSONObject data_sec = maps.getJSONObject(k);
System.out.println("name => "+data_sec.getString("name"));
System.out.println("latitude => "+data_sec.getString("latitude"));
System.out.println("longitude => "+data_sec.getString("longitude"));
}
}
}
catch (Exception e)
{
// TODO: handle exception
}
// Try this way,hope this will help you to solve your problem.
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://10.0.2.2/locations.json");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("all");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("title", jsonobject.getString("title"));
map.put("index", i);
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
Intent sendtosecond = new Intent(MainActivity.this, SecondActivity.class);
// Pass all data rank
sendtosecond.putExtra("title", arraylist.get(position).get(MainActivity.TITLE));
sendtosecond.putExtra("index", arraylist.get(position).get(MainActivity.INDEX));
Log.d("Tapped Item::", arraylist.get(position).get(MainActivity.TITLE));
Log.d("Tapped Item Index::", arraylist.get(position).get(MainActivity.INDEX));
startActivity(sendtosecond);
}
});
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
Intent in = getIntent();
strReceived = in.getStringExtra("title");
strReceivedIndex = in.getStringExtra("index");
Log.d("Received Data::", strReceived);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://10.0.2.2/locations.json");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("all").getJSONObject(Integer.parseInt(strReceivedIndex)).getgetJSONArray("maps");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("title", jsonobject.getString("title"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}