hi guys i don't know why but i get this error: JSONArray cannot be converted to JSONObject.
I show you my code!I hope that you can help me! thanks in advance everybody!
Sorry, but i am new to JSON.
MAIN ACTIVITY:
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://v1.tvguideapi.com/programs?channels[]=2161&channels[]=2162&start=1484598600&stop=1484605799";
//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);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("programs");
// 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");*/
String title=c.getString("title");
// 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);*/
contact.put("title",title);
// 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});*/
MainActivity.this, contactList,
R.layout.list_item, new String[]{"title"}, new int[]{R.id.title});
lv.setAdapter(adapter);
}
}
}
JSON:
[
{
"id": "18879971",
"start": "2017-01-16 20:20:00",
"stop": "2017-01-16 22:30:00",
"lang": "",
"title": "Il Collegio</td>",
"subtitle": "",
"description": "",
"category": "",
"channel_id": "2162",
"icon": null,
"ts_start": 1484598000,
"ts_stop": 1484605800
},
{
"id": "18879856",
"start": "2017-01-16 20:25:00",
"stop": "2017-01-16 22:40:00",
"lang": "",
"title": "I Bastardi di Pizzofalcone",
"subtitle": "",
"description": "Ep.3 - In un fatiscente condominio di Pizzofalcone viene rinvenuto il cadavere di una camariera. Le indagini della squadra portano al marito della donna, ma per Lojacono il caso si complica ulteriormente.",
"category": "",
"channel_id": "2161",
"icon": null,
"ts_start": 1484598300,
"ts_stop": 1484606400
}
]
You should use you have Json Array.
you have [{ },{}] format Here [] shows JsonArray and {} this is json object.
you can have Json array loop through array and get Json object.
JSONArray contacts = new JSONArray(jsonStr);
Instead of using
JSONObject jsonObj = new JSONObject(jsonStr);
Now you can fetch data
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
//Get all required data using c.
String id = c.getString("id");
String name = c.getString("start");
}
Related
The JSON is simple as,
[{"kw":"48.90","kva":"51.20","pf":"-0.96"}]
The error I get is,
08-26 02:28:49.130 13605-13641/com.whatever.emshive E/MainActivity:
Response from url: [{"kw":"48.90","kva":"51.20","pf":"-0.96"}]
Json parsing error: Value [{"kw":"48.90","kva":"51.20","pf":"-0.96"}] of type org.json.JSONArray
cannot be converted to JSONObject 08-26 02:28:49.130
13605-13641/com.whatever.emshive E/JSON Parser: Error parsing data
org.json.JSONException: Value
[{"kw":"48.90","kva":"51.20","pf":"-0.96"}] of type org.json.JSONArray
cannot be converted to JSONObject
Code is,
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://simpleasthat.com/s.php";
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(0);
String kw = c.getString("kw");
String kva = c.getString("kva");
String pf = c.getString("pf");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("kw", kw);
contact.put("kva", kva);
contact.put("pf", pf);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Log.e("JSON Parser", "Error parsing data " + e.toString());
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[]{"kw", "kva",
"pf"}, new int[]{R.id.kw,
R.id.kva, R.id.pf});
lv.setAdapter(adapter);
}
}
}
I have tried looking at other similar answers in StackOverflow, couldn't get it. Help is much appreciated. Thank You
Please change the code in GetContacts.doInBackground from
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
to
JSONArray contacts = new JSONArray(jsonStr);
As the message says, you're trying to cast a JSON array into a JSON object. Your JSON is an array...
i'm trying to parse this json
{
"data": [
{ "name": "4th Floor",
"is_broken": true,
"is_repaired": false,
"is_ok": false,
"asset_parent": {
"name": "Buni Building",
"is_broken": true,
"is_repaired": false,
"is_ok": false
}
}
]
}
with this code
class daftarAset extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Sedang menampilkan...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
String link_url = "https://example.com/api/assets";
HttpHandler sh = new HttpHandler();
String json = sh.makeServiceCall(link_url);
Log.e(TAG, "Response from url: " + json);
if (json != null) {
try {
JSONObject jsonObject = new JSONObject();
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject ar = data.getJSONObject(i);
String aset = ar.getString("name");
JSONObject parent = ar.getJSONObject("asset_parent");
String nama = parent.getString("name");
HashMap map = new HashMap();
map.put(in_aset, aset);
map.put(in_ruang, nama);
data_map.add(map);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
list = (ListView) getView().findViewById(R.id.baik_list);
adapter = new AssetsAdapter(getActivity(), data_map);
list.setAdapter(adapter);
setListViewHeightBasedOnChildren(list);
}
});
}
return null;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
}
and it says error that no value for data. i dont know why the data said no value where i already call it before with JSONArray. it must be nothing to do with the listview where i have to put the value.
please help why it says has no value for data but it actualy has
You're getting error because you aren't passing the json string to your json object.
it should be
JSONObject jsonObject = new JSONObject(json);
instead of
JSONObject jsonObject = new JSONObject(); //json is missing here
i am not getting Json response in my listactivity.i tried everything but its not showing the result..in logcat i got successful connection and data also i can see..but in my listview its says this exception.
here is my code
public class TypeMenu extends AppCompatActivity {
private String TAG = TypeMenu.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://cloud.granddubai.com/brtemp/index.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_menu);
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(TypeMenu.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
Toast.makeText(getApplicationContext(),
"Toast",
Toast.LENGTH_LONG)
.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("menu_type");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
//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", type);
//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(
TypeMenu.this, contactList,
R.layout.list_item, new String[]{"id", "type"}, new int[] {R.id.id,
R.id.type});
lv.setAdapter(adapter);
}
}
}
here is my logcat msg
12-15 14:25:26.092 549-962/com.example.zass.broccoli E/TypeMenu:
Response from url: connection
successful[{"id":"1","type":"pizza"}, {"id":"8","type":"Special
Offer"},{"id":"2","type":"Pasta"},{"id":"7","type":"Soup"},{"id":"6","type":"Beverages"},{"id":"5","type":"Breakfast"},{"id":"3","type":"Lasagna"},{"id":"4","type":"Salad"}]
12-15 14:25:26.092 549-962/com.example.zass.broccoli E/TypeMenu: Json parsing error: Value connection of type java.lang.String cannot
be converted to JSONObject
this is the output from url which i wanted in my listview
[{"id":"1","type":"pizza"},{"id":"8","type":"Special Offer"}, {"id":"6","type":"Beverages"},{"id":"5","type":"Breakfast"}, {"id":"3","type":"Lasagna"},{"id":"4","type":"Salad"}]
here is my json file which works fine on server
<?php
include ('config.php');
$id = $_GET['id'];
$sql = mysqli_query($conn,"SELECT * FROM menu_type ");
$i=0;
while($result = mysqli_fetch_array($sql))
{
$arr[$i]['id']= $result['id'];
$arr[$i]['type']= $result['type'];
}
echo json_encode($arr);
?>
here is my list_item.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/id"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/type"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Apply this code
JSONArray jsonArry = new JSONArray(jsonStr);
for (int i = 0; i < jsonArry.length(); i++) {
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", type);
contactList.add(contact);
}
Change below code
ListAdapter adapter = new SimpleAdapter(
TypeMenu.this, contactList,
R.layout.list_item, new String[]{"id", "type"}, new int[] {R.id.id,
R.id.type});
with
ListAdapter adapter = new SimpleAdapter(
TypeMenu.this, contactList,
R.layout.list_item, new String[]{"id", "name"}, new int[] {R.id.id,
R.id.type});
edited some of your code try this below code.
try {
JSONArray jsonArry = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < jsonArry.length(); i++) {
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
// 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", type);
// 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();
}
});
}
And I can give one more little easy and feasible solution,
Change your server File to be like below,
<?php
include ('config.php');
$id = $_GET['id'];
$sql = mysqli_query($conn,"SELECT * FROM menu_type ");
$response['details'] = array();
$i=0;
while($result = mysqli_fetch_array($sql))
{
$arr['id']= $result['id'];
$arr['type']= $result['type'];
array_push($response['details'],$arr);
}
echo json_encode($response);
?>
And your Java code will be like,
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray detailArray = jsonObj.optJSONArray("details");
for (int i = 0; i < detailArray.length(); i++) {
JSONObject c = detailArray.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", type);
contactList.add(contact);
}
I have two Listview,I am getting two JSONArray from server,I am getting following response
[
[
{
"user_status": "1",
"pooja_name": "Festival Sevas",
"sess_date": "Mon Nov 30 2015",
"session_status": "Completed",
"message": "What ever message you want"
}
],
[
{
"user_status": "1",
"pooja_name": "Pushpalankara Seva",
"sess_date": "Tue Dec 15 2015",
"session_status": "Pending",
"message": "What ever message you want"
}
]
]
I am able to parse both the arrays,but in my both listview it display Pushpalankara Seva,what i am trying is in my first listview i want to display Pushpalankara Seva and in second Festival Sevas
class LoadPoojas extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AboutUsFragment.this.getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String,String>> upcomingdata = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(POOJA_LISTING_URL, ServiceHandler.GET);
map = new HashMap<String, String>();
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonObj = new JSONArray(jsonStr);
// Getting JSON Array node
JSONArray pastarray = jsonObj.getJSONArray(0);
for (int i = 0; i < pastarray.length(); i++) {
JSONObject c = pastarray.getJSONObject(i);
// creating new HashMap
// adding each child node to HashMap key => value
map.put(POOJA_LISTING_NAME, c.getString(POOJA_LISTING_NAME));
}
JSONArray upcoming = jsonObj.getJSONArray(1);
for (int i = 0; i < upcoming.length(); i++) {
JSONObject c = upcoming.getJSONObject(i);
// creating new HashMap
// HashMap<String, String> upcomingmap = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(POOJA_LISTING_NAME, c.getString(POOJA_LISTING_NAME));
}
data.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
/*if(interestaccept == null || interestaccept.length() == 0){
// Toast.makeText(getApplicationContext(), "No response", Toast.LENGTH_SHORT).show();
noacpt.setText(" No Accepted List ");
}
else
{
noacpt.setVisibility(View.INVISIBLE);
}*/
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
aList = new ArrayList<HashMap<String, String>>();
aList.addAll(result);
adapter = new CustomAdapterPooja(getActivity(),result);
completedpooja.setAdapter(adapter);
adapterupcoming = new CustomAdapterPoojaUpcoming(getActivity(),result);
notcompletedpooja.setAdapter(adapterupcoming);
adapter.notifyDataSetChanged();
adapterupcoming.notifyDataSetChanged();
completedpooja.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
/* upcomingaList = new ArrayList<HashMap<String, String>>();
upcomingaList.addAll(result);
adapterupcoming = new CustomAdapterPoojaUpcoming(getActivity(),result);
notcompletedpooja.setAdapter(adapterupcoming);
adapterupcoming.notifyDataSetChanged();
notcompletedpooja.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});*/
}
}
I checked you code and found you did mistake in hashmap with same key in both array(inside both For loop). So it overwrite with latest value as per rules of hashmap.
Solution :
Option 1: Take arraylist of hashmap and create new hashmap each new record.
Option 2: Take arraylist of POJO class.
Edit :
public class UserPOJO {
public String user_status;
public String pooja_name;
public String sess_date;
public String session_status;
public String message;
}
Take arraylist of POJO class like below
public ArrayList<UserPOJO> userPOJOs = new ArrayList<UserPOJO>();
Now insert data in arraylist from JSONArray.
I am working with a parsing json and fetching my json data from kimono.I am fetching json from following url:
http://www.brankart.com/test/tra.json
My mainactivity goes as follows:
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://www.brankart.com/test/tra.json";
// JSON Node names
private static final String lnk = "href";
private static final String d1 = "text";
private static final String dt = "property2";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(lnk, name);
in.putExtra(dt, cost);
in.putExtra(d1, description);
startActivity(in);
}
});
// Calling async task to get json
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) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject nsb = jsonObj.getJSONObject("results");
// Getting JSON Array node
contacts = nsb.getJSONArray("collection1");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
JSONObject p1 = c.getJSONObject("property1");
String link = p1.getString(lnk);
String descp = p1.getString(d1);
String detail = p1.getString(dt);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(lnk, link);
contact.put(d1, descp);
contact.put(dt, detail);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
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[] { d1, dt,
lnk }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}
I am still not able to fetch my json in listview.Please help
Try change doInBackground like below
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject nsb = jsonObj.getJSONObject("results");
// Getting JSON Array node
contacts = nsb.getJSONArray("collection1");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
JSONObject p1 = c.getJSONObject("property1");
String link = p1.getString(lnk);
String descp = p1.getString(d1);
//change here !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
String detail = c.getString(dt);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(lnk, link);
contact.put(d1, descp);
contact.put(dt, detail);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}