I'm new in android. I'm trying to get json but I got this error.
I trying following this tutorial http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
I already search the solution, but I still don't get it how to use the JSONArray.
Here is my Json example
[{"id":"152","category_id":"14","item_name":"Restaurant1","cuisine_id":"3","cuisine_name":"Chinese"},{"id":"161","category_id":"14","item_name":"Restaurant10","cuisine_id":"17","cuisine_name":"Middle Eastern"},{"id":"153","category_id":"14","item_name":"Restaurant2","cuisine_id":"17","cuisine_name":"Middle Eastern"},{"id":"154","category_id":"14","item_name":"Restaurant3","cuisine_id":"7","cuisine_name":"American"},{"id":"155","category_id":"14","item_name":"Restaurant4","cuisine_id":"3","cuisine_name":"Chinese"},{"id":"156","category_id":"14","item_name":"Restaurant5","cuisine_id":"8","cuisine_name":"Coffee"},{"id":"157","category_id":"14","item_name":"Restaurant6","cuisine_id":"8","cuisine_name":"Coffee"},{"id":"158","category_id":"14","item_name":"Restaurant7","cuisine_id":"17","cuisine_name":"Middle Eastern"},{"id":"159","category_id":"14","item_name":"Restaurant8","cuisine_id":"6","cuisine_name":"Indonesian"},{"id":"160","category_id":"14","item_name":"Restaurant9","cuisine_id":"3","cuisine_name":"Chinese"}]
And Here the class
/**
* Async task class to get json by making HTTP call
* */
private class GetRestaurant extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Attractions.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);
// Getting JSON Array node
restaurant = jsonObj.getJSONArray(TAG_ITEM_NAME);
// looping through All Contacts
for (int i = 0; i < restaurant.length(); i++) {
JSONObject c = restaurant.getJSONObject(i);
String id = c.getString(TAG_CUISINE_NAME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_CUISINE_NAME, id);
// adding contact to contact list
restaurantList.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(
Attractions.this, restaurantList,
R.layout.attractionslayout, new String[] { TAG_ITEM_NAME, TAG_CUISINE_NAME }, new int[] { R.id.item_name,
R.id.cuisine_name});
// Assign adapter to ListView
listview.setAdapter(adapter);
}
}
Thanks Before.
Try this..
Your response starts with JSONArray
[ ==> JSONArray
{ ==> JSONObject
Change this..
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
restaurant = jsonObj.getJSONArray(TAG_ITEM_NAME);
to
restaurant = new JSONArray(jsonStr);
Your string is not json object , it is json array because the string are start via third bracket
so, try this
restaurant = new JSONArray(jsonStr);
you do not need to convert it as a josn object,
JSONObject jsonObj = new JSONObject(jsonStr);
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 need to get an image using webservice which is rest.And most of the tutorials are about click the button in order to trigger the process.I need to implement this such a way that when activity opens images has to be loaded immediately without trigger or clicking the button or something.I just need a source or idea.
Any help will be appreciated.
Implement an Asynctask and call it onCreate.
Here is an example on how to do it;
public class MainActivity extends ListActivity {
.
.
.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.
.
.
// 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);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// 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[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}
As you can see, you only need to call the asynctask (new GetContacts().execute();) onCreate and it will behave as you design it.
References: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Write your code in onCreate() or onResume() method of activity.
For downloading images you can use Picasso and Glide.
For communication between app and webservice you can use Retrofit.
Also for more information you can read this tutorial Retrofit - Getting Started and Create an Android Client
Write your code for loading image in onCreate() method of Activity. So user don't need to trigger or clicking the button or something.
I want show server json responce in listview.i get all value in hashmap i am confused about how to set that data in custom listview.please help me and show me the code
class viewticket extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pdialog = new ProgressDialog(UserLogedIn.this);
pdialog.setMessage("Loading....");
pdialog.setIndeterminate(false);
pdialog.setCancelable(false);
pdialog.show();
}
#Override
protected Void doInBackground(Void... params) {
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("userid", u_id));
JSONObject jsonArray = jpar.makeHttpRequest(URLMyTicket, "POST", param);
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URLMyTicket, ServiceHandler.POST, param);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
contacts = new JSONArray(jsonStr);
int a=contacts.length();
Log.v(TAG,""+a);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_PROB);
String email = c.getString(TAG_DESC);
HashMap<String, String> contact = new HashMap<String, String>();
contact.put(TAG_ID, id);
contact.put(TAG_PROB, name);
contact.put(TAG_DESC, email);
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();
//What code to write
}
}
what should i write in onpost method and custom list class
Ticket_list.java
public class Ticket_list extends ArrayAdapter< String> {
HashMap<String, String> objects;
public Ticket_list(Context context, int resource, HashMap<String,String> objects) {
super(???? //what );
}
//What
}
Please help me to write onpost method code and code of Ticket_list
I highly recommend you to use RecyclerView instead of ListView and use Retrofit to send request and get the response as json.Take a look at these documents For RecyclerView.
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;
}
I am following this to store JSON parsed data into SQLite Database, but whenever i use my app offline not getting stored data into ListView.
Is there anything left to implement in my existing code ?
MainActivity.java:-
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper=new CategoryHelper(MainActivity.this);
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) {
}
});
// 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);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
databaseHelper.saveCategoryRecord(id,name);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
// 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[] { TAG_NAME }, new int[] { R.id.name });
setListAdapter(adapter);
}
}
I don't know what that ServiceHandler thing is, but I'm guessing the call to makeServiceCall() returns null when you're offline. This means you aren't populating the contactList, which means it's empty when you're creating the ListAdapter.
I'm guessing what you want to do, is add an else clause to if (jsonStr != null) that populates contactList with records from your DB. How to do this depends on the implementation details of CategoryHelper.
Using shared preference would be a better approach for that. Follow these steps:
search and download GSON library. This will simplify our task for saving and retrieving JSON to/from shared preferences and let your app use the GSON library
example:
SharedPreferences prefs = getSharedPreferences("mySharedPreferenceKey");
Editor editor = prefs.edit();
Gson gson = new Gson();
//convert your object to string and save it to shared preference
ArrayList<Integer> myIntArrs = new ArrayList<Integer>();
editor.putString("myJSONKey", new Gson().toJson(myIntArrs)).commit();
//get your json string from shared preferences
public final Type ARRAYLIST_INTEGER = new TypeToken<ArrayList<Integer>>(){}.getType();
ArrayList<Integer> intArrs = gson.fromJson(prefs.getString("myJSONKey", "{}"), ARRAYLIST_INTEGER);
//do something with your intArrs
Hope this helps!