Detail view of listview - android

Here is my async task.i want display the detailview of a listview click.there is some error in displaying data in text view.i know we cant access UI inside doInBackground.i dont know how to do in OnpostExecute.help me
class Enquiryview extends AsyncTask<String, Void, JSONObject> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EnquiryDetail.this);
// pDialog.setMessage("Loding...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected JSONObject doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
// final String URL_LIST = "http://staging.homeneedsonline.com/ws/ws_address_detail.php?user_id="+ userid1+"";
final String URL_LIST = "http://staging.homeneedsonline.com/ws/ws_enq_detail.php?ser_enq_id="+ enq_id+"";
System.out.println(URL_LIST);
JSONParser jsonParser = new JSONParser();
final JSONObject json = jsonParser.getJSONFromUrl(URL_LIST, get, params);
System.out.println("enq----do in ---"+json);
try {
String res = json.getString(KEY_SUCCESS);
System.out.println("enq---------------is"+enq_id);
int res1 = Integer.parseInt(res);
if (res1 == 1) {
// String res = json.getString(KEY_SUCCESS);
//System.out.println(res);
JSONObject jsonObject = json.getJSONObject("detail");
// setListAdapter(mAdapter);
// JSONArray json1=new JSONArray("data");
//Log.d("Address JSON: ", "> " + albums);
// Storing each json item values in variable
final String enqid = jsonObject.getString(ENQID);
String enqdate = jsonObject.getString(ENQ_DATE);
String status = jsonObject.getString(STATUS);
String usc = jsonObject.getString(USC);
String amount = jsonObject.getString(AMOUNT);
String address = jsonObject.getString(ENQ_ADDRESS);
String city = jsonObject.getString(CITY);
String state = jsonObject.getString(STATE);
System.out.println(enqid);
System.out.println(enqdate);
System.out.println(usc);
System.out.println(address);
System.out.println(city);
System.out.println(state);
// service.setText();
amounttext.setText(amount);
//exname.setText();
statustext.setText(status);
addresstext.setText(address);
citytext.setText(city);
statetext.setText(state);
//billno.setText();
usctext.setText(usc);
date.setText(enqdate);
enqidtext.setText(enqid);
}
else
{
Log.d("Addressssssssssssssssssssssssssssssssss: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
}
protected void onPostExecute(final JSONObject json1) {
// check for login response
/// System.out.println("enq----on post ---"+json);
pDialog.dismiss();
// Check your log cat for JSON reponse
}

class Enquiryview extends AsyncTask<String, Void, JSONObject> {
final JSONObject json;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EnquiryDetail.this);
// pDialog.setMessage("Loding...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected JSONObject doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
// final String URL_LIST = "http://staging.homeneedsonline.com/ws/ws_address_detail.php?user_id="+ userid1+"";
final String URL_LIST = "http://staging.homeneedsonline.com/ws/ws_enq_detail.php?ser_enq_id="+ enq_id+"";
System.out.println(URL_LIST);
JSONParser jsonParser = new JSONParser();
json = jsonParser.getJSONFromUrl(URL_LIST, get, params);
return null;
}
protected void onPostExecute(final JSONObject json1) {
// check for login response
/// System.out.println("enq----on post ---"+json);
System.out.println("enq----do in ---"+json);
try {
String res = json.getString(KEY_SUCCESS);
System.out.println("enq---------------is"+enq_id);
int res1 = Integer.parseInt(res);
if (res1 == 1) {
// String res = json.getString(KEY_SUCCESS);
//System.out.println(res);
JSONObject jsonObject = json.getJSONObject("detail");
// setListAdapter(mAdapter);
// JSONArray json1=new JSONArray("data");
//Log.d("Address JSON: ", "> " + albums);
// Storing each json item values in variable
final String enqid = jsonObject.getString(ENQID);
String enqdate = jsonObject.getString(ENQ_DATE);
String status = jsonObject.getString(STATUS);
String usc = jsonObject.getString(USC);
String amount = jsonObject.getString(AMOUNT);
String address = jsonObject.getString(ENQ_ADDRESS);
String city = jsonObject.getString(CITY);
String state = jsonObject.getString(STATE);
System.out.println(enqid);
System.out.println(enqdate);
System.out.println(usc);
System.out.println(address);
System.out.println(city);
System.out.println(state);
// service.setText();
amounttext.setText(amount);
//exname.setText();
statustext.setText(status);
addresstext.setText(address);
citytext.setText(city);
statetext.setText(state);
//billno.setText();
usctext.setText(usc);
date.setText(enqdate);
enqidtext.setText(enqid);
}
else
{
Log.d("Addressssssssssssssssssssssssssssssssss: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return ;
}
pDialog.dismiss();
// Check your log cat for JSON reponse
}
Try this

You need to return JsonObject from doInBackground method and whatever json parsing you are doing the doInBackground you need to move it to the onPostExecute() method.
Let me know if it helps you

Related

How to solve org.json.JSONException: Index 0 out of range [0..0) using android

I am developing an app, here i want to display fetched items of table I tried following code but it gives error at this line JSONObject c = result.getJSONObject(0);.
How do i solve this?
//java file
public class Details extends Activity {
TextView uid;
TextView name1, amount1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://example.in/ticket1.php";
//JSON Node Names
private static final String TAG_USER = "result";
// private static final String TAG_ID = "id";
private static final String TAG_NAME = "pname";
private static final String TAG_AMOUNT = "pamount";
JSONArray result = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
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();
uid = (TextView)findViewById(R.id.uid);
name1 = (TextView)findViewById(R.id.name);
amount1 = (TextView)findViewById(R.id.email);
pDialog = new ProgressDialog(Details.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
result = json.getJSONArray(TAG_USER);
JSONObject c = result.getJSONObject(0);
// Storing JSON item in a Variable
// String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String amount = c.getString(TAG_AMOUNT);
//Set JSON Data in TextView
// uid.setText(id);
name1.setText(name);
amount1.setText(amount);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Check the size of the result array before you iterate over it.
#Override
protected void onPostExecute(JSONObject json) {
{
pDialog.dismiss();
try {
// Getting JSON Array
result = json.getJSONArray(TAG_USER);
if (result.length() > 0) {
JSONObject c = result.getJSONObject(0);
// Storing JSON item in a Variable
// String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String amount = c.getString(TAG_AMOUNT);
//Set JSON Data in TextView
// uid.setText(id);
name1.setText(name);
amount1.setText(amount);
}
} catch (JSONException e) {
e.printStackTrace();
}
}

How can I pass Strings from doInBackground to onPostExecute

I want to send 3 strings from doInBackground to onPostExecute.
I managed to fetch the data and I can see them in Logs. Now how to use the data stored in Strings once the doInBackground completed its execution.
Here is my code.
public class MainActivity extends AppCompatActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://example.com/test.php";
// JSON Node names
private static final String tag_info = "info";
private static final String tag_success = "Success";
private static final String tag_message = "message";
private static final String tag_output = "output";
// contacts JSONArray
JSONArray info = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Calling async task to get json
new fetchInfo().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class fetchInfo 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
info = jsonObj.getJSONArray(tag_info);
JSONObject c = info.getJSONObject(0);
// I want to use these 3 strings in onPostExecute
String success = c.getString(tag_success);
String message = c.getString(tag_message);
String output = c.getString(tag_output);
} 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();
TextView successView = (TextView) findViewById(R.id.success_field);
successView.setText(success + " " + message + " " + output); // I want to print them here
}
}
}
Use String Array
protected String[] doInBackground(String[]... passing) {
String[] result = new String[3];
result[0]= c.getString(tag_success);
result[1] = c.getString(tag_message);
result[2] = c.getString(tag_output);
return result; //return result
}
protected void onPostExecute(String result[]) {
String a = result[0];
}
Bean class
public class BeanClass{
String message,success,output;
public BeanClass(String message,String success,String output){
this.message = message;
this.success = success;
this.output = output;
}
public String getMessage(){ return message;}
public String getSuccess(){ return success;}
public String getOutput(){ return output;}
}
change your async task to
private class fetchInfo extends AsyncTask<Void, Void, BeanClass> {
#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 Bean doInBackground(Void... arg0) {
// Creating service handler class instance
Bean result=null;
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
info = jsonObj.getJSONArray(tag_info);
JSONObject c = info.getJSONObject(0);
// I want to use these 3 strings in onPostExecute
String success = c.getString(tag_success);
String message = c.getString(tag_message);
String output = c.getString(tag_output);
result = new Bean(sucess,message,output);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return result;
}
#Override
protected void onPostExecute(Bean result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
if(result!=null){
TextView successView = (TextView) findViewById(R.id.success_field);
successView.setText(result.getSuccess() + " " + result.getMessage() + " " + result.getOutput()); // I want to print them here
}
}
}
try the simply this....... do not need to pass
public class MainActivity extends AppCompatActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://example.com/test.php";
// JSON Node names
private static final String tag_info = "info";
private static final String tag_success = "Success";
private static final String tag_message = "message";
private static final String tag_output = "output";
// contacts JSONArray
JSONArray info = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Calling async task to get json
new fetchInfo().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class fetchInfo extends AsyncTask<Void, Void, Void> {
String success = "";
String message = "";
String output = "";
#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
info = jsonObj.getJSONArray(tag_info);
JSONObject c = info.getJSONObject(0);
// I want to use these 3 strings in onPostExecute
success = c.getString(tag_success);
message = c.getString(tag_message);
output = c.getString(tag_output);
} 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();
TextView successView = (TextView) findViewById(R.id.success_field);
successView.setText(success + " " + message + " " + output); // I want to print them here
Log.e("First Value", success);
Log.e("Second Value", message);
Log.e("Third Value", output);
}
}
}
public class fetchInfo extends AsyncTask<Void, Void, String> {
#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 String doInBackground(Void... params) {
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
info = jsonObj.getJSONArray(tag_info);
JSONObject c = info.getJSONObject(0);
// I want to use these 3 strings in onPostExecute
String success = c.getString(tag_success);
String message = c.getString(tag_message);
String output = c.getString(tag_output);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return output;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (pDialog.isShowing())
pDialog.dismiss();
TextView successView = (TextView) findViewById(R.id.success_field);
successView.setText(s); // I want to print them here
}
}
Do this while declaring
Public class Do Task extends AsyncTask<Void, Void, String>{
then in doInBackground method
protected String[] doInBackground(String[]... passing) {
return result; //change it to a string from null
}
then in onPostExecute result is your string that you want
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
Let me know if you still face an issue.Mark this up if it helps.

When we click on item in listview then how we get id of that item

I have a json in which i have product_id and product_name through the Json products are showing in listview now i want that when clicked on item then id of that product should be show in toast. I am new to android i am unable to do this
can anyone tell me how can i do this please
public class CityNameActivity extends ListActivity{
ListView list;
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
//ArrayList<String> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cityname_activity_main);
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
// list.setOnClickListener(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(),
Specialities_Activity.class);
startActivity(in);}
});
new GetCities().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.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
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} 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();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
Code of Service Handlerclass:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
code of Hospital Activity in which hospital is showing in listview i want that not all hospitals show only show hospital of specific city
public class HospitalList_Activity extends ListActivity {
private ProgressDialog pDialog;
// URL to get Hospitals JSON
private static String url = "http://14.140.200.186/hospital/get_hospital.php";
// JSON Node names
private static final String TAG_HOSPITAL = "Hospitals";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "hospital_name";
// Hospitals JSONArray
JSONArray Hospitals = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> hospitallist;
//ArrayList<String> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospital_list_);
ListView listView=getListView();
hospitallist = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(), Specialities_Activity.class);
startActivity(in);
}
});
new GetHospitals().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetHospitals extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(HospitalList_Activity.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
Hospitals = jsonObj.getJSONArray(TAG_HOSPITAL);
// looping through All Cities
for (int i = 0; i < Hospitals.length(); i++) {
JSONObject c = Hospitals.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Hospitals = new HashMap<String, String>();
Hospitals.put(TAG_NAME, name);
// adding contact to Cities list
hospitallist.add(Hospitals);
}
} 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();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(HospitalList_Activity.this, hospitallist, R.layout.hospital_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
public class CityNameActivity extends ListActivity {
ListView list;
Map <String, String> cityListWithId = new HashMap<String, String>();
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
private static final String TAG_ID = "city_id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cityname_activity_main);
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String tagname = ((TextView) findViewById(R.id.name)).getText().toString();
Map<String, String> tempHashmap = (Map<String, String>) parent.getItemAtPosition(position);
String tagName = tempHashmap.get(TAG_NAME);
System.out.println("tagname" + tagName);
String tagId = (String)cityListWithId.get(tagName);
System.out.println("tagId" + tagId);
Toast.makeText(CityNameActivity.this, tagId,Toast.LENGTH_SHORT).show();
}
});
new GetCities().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.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
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
cityListWithId.put(c.getString(TAG_NAME), c.getString(TAG_ID));
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} 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();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
}
On ItemClick() method you can add this to get the id of the product.
HashMap<String,String> data = cityList.get(position);
//position is the paramater from ItemClick
String id = data.get("your key for Id");
why you every time hit the service . as per my opinion don't call service in onItemClick . when you start activity or app start Async task and pass data to list view .
please find below code . i am just refactor few thing so please let me if there some thing wrong
public class CityNameActivity extends ListActivity
{
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new GetCities().execute();
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
// list.setOnClickListener(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(citylist!=null && !citylist.isEmpty())
{
Toast.makeText(CityNameActivity.this,""+citylist.get(position).get(TAG_NAME).toString(),Toast.LENGTH_SHORT).show();
}
}
});
new GetCities().execute();
}
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.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
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} 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();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
}

error parsing data org.json.exeception

here is my doInbackground code from a class that extends Asynctask
protected String doInBackground(String... args) {
List<NameValuePair> paramss = new ArrayList<NameValuePair>();
paramss.add(new BasicNameValuePair(TAG_EMAIL, emailMember));
JSONObject json = parser.makeHttpRequest(url_get_pembayaran, "POST", paramss);
Log.d("shopping chart", json.toString());
return json.toString();
}
actually in always work at another code
this is my oncreate code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bayar);
txt_total_harga = (TextView) findViewById(R.id.txt_total_harga);
txt_ongkos_kirim = (TextView) findViewById(R.id.txt_ongkos_kirim);
txt_jumlah_barang = (TextView) findViewById(R.id.txt_jumlah_barang);
txt_status = (TextView) findViewById(R.id.txt_status);
btnBayar = (Button) findViewById(R.id.btnBayarSemua);
Intent ambil = getIntent();
idChart = ambil.getStringExtra("idShopping");
prefs = getSharedPreferences("login", Context.MODE_PRIVATE);
emailMember = prefs.getString("emailMember", "");
new DetailSC().execute();
}
this is my class that extends to Asynctask
class DetailSC extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... args) {
List<NameValuePair> paramss = new ArrayList<NameValuePair>();
paramss.add(new BasicNameValuePair(TAG_EMAIL, emailMember));
JSONObject json = parser.makeHttpRequest(url_get_pembayaran, "POST", paramss);
Log.d("shopping chart", json.toString());
return json.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
pDialog = null;
try{
JSONObject json = new JSONObject(result);
int success = json.getInt(TAG_SUCCESS);
if(success == 1){
shopping_detail = json.getJSONArray(TAG_SHOPPING);
JSONObject jObject = shopping_detail.getJSONObject(0);
int totalHarga = jObject.getInt(TAG_TOTAL_HARGA);
int berat = json.getInt(TAG_BERAT);
String ongkos = json.getString(TAG_ONGKOS_KIRIM);
int ongkosK = Integer.parseInt(ongkos);
totalHarga = ( berat * ongkosK ) / 1000;
txt_jumlah_barang.setText(jObject.getString(TAG_JUMLAH_BARANG));
txt_ongkos_kirim.setText(ongkos);
txt_status.setText(jObject.getString(TAG_STATUS));
txt_total_harga.setText("IDR " + totalHarga);
}
}catch(JSONException ex){
ex.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Bayar.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setMessage("Downloading Data . . .");
pDialog.show();
}
}
the error in logcat is :
eror parsing data org.json.JSONException : value email of type java.lang.String cannot be converted to JSONObject

retrieve data using json in android

I need to display the result in android text view that I obtained by json result. I only get the success message when I run the app. I want to get the textview displayed.
Java Code:
JSONObject hay;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "////////////////////// "; // change to the webhost
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setup input fields
user = (EditText) findViewById(R.id.user);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);
//setup buttons
get = (Button) findViewById(R.id.get);
//register listeners
get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
class AttemptLogin extends AsyncTask < String, String, String > {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempt login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String...args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
try {
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("username", username));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
//
//Intent i = new Intent(Login.this, MainActivity.class);
//finish();
//startActivity(i);
//finish();
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
try {
JSONObject json = null;
JSONObject hay = new JSONObject((Map) json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
} catch (Exception e) {
e.printStackTrace();
}
if (file_url != null) {
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
PHP Code:
<?php
require('config.inc.php');
if (!empty($_POST)) {
//initial query
$query = "Select last_name, first_name, middle_initial FROM admin where username = :user";
$query_params = array(':user' => $_POST['username']);
//execute query
try {
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt -> fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["user"] = array();
foreach($rows as $row) {
$user = array();
// $user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];
//update our repsonse JSON data
array_push($response["user"], $user);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user available!";
die(json_encode($response));
}
} else {}
?>
<form action="test.php" method="POST">
Username: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
sorry can't comment but what you getting at post execute from background task is file_url as string which is your param at on post execute......i think if you are getting result all params like first name ,lastName etc then you needed to pass jsonObject at onpost Execute
so you can parse at onPostExecute...your jsonResult and display it in textbox
Problem is in you current code is
txtFname.setText("Firstname: " + firstname);
in which firstName is from
String firstname = jb.getString("firstname");
JSONObject jb= user.getJSONObject(0);
JSONArray user = hay.getJSONArray("user");
JSONObject hay = new JSONObject ((Map) json);
JSONObject json = null;
i have reversed it so you can find problem here json is null so here is problem and pls try logging at each point and let we know so we and you can have exact idea....or give us json format...
the problem is with your this code segment:
JSONObject json = null;
JSONObject hay = new JSONObject((Map) json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
here what you are doing is: making another JSONObject as
JSONObject json = null;
that is creating a variable with local scope, the local variable will have more priority than global, that you understood. actually you need the json which is created from doInBackgrounnd(). so pass the json from doInBackground to onPostExecute: it is simple,
change the statements:
return json.getString(TAG_MESSAGE); => return json;
return json.getString(TAG_MESSAGE); => return json;
also change the type of doInBackground to JSONObject and avoid making a new local JSONObject and trying to get datafrom that (bcz it is null you initialized with).
JSONObject json = null; //remove this
JSONObject hay = new JSONObject((Map) json); //remove this
JSONArray user = hay.getJSONArray("user"); // change hay to json
also change the
protected void onPostExecute(String file_url)// to protected void onPostExecute(JSONObject json)
EDIT 2
here is your changed code, let me know what you are getting if some errors.
//edited1
public static JSONObject json = null;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "////////////////////// "; // change to the webhost
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_USER = "user";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setup input fields
user = (EditText) findViewById(R.id.user);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);
//setup buttons
get = (Button) findViewById(R.id.get);
//register listeners
get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
class AttemptLogin extends AsyncTask < String, String, String > {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempt login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String...args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
try {
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("username", username));
Log.d("request!", "starting");
// getting product details by making HTTP request
// edited2
json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
//
//Intent i = new Intent(Login.this, MainActivity.class);
//finish();
//startActivity(i);
//finish();
//edited3
return json.getString(TAG_MESSAGE);
//return json;
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
//edited4
return json.getString(TAG_MESSAGE);
//return json;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String message) {
// dismiss the dialog once product deleted
pDialog.dismiss();
try {
//JSONObject json = null;
//JSONObject hay = new JSONObject((Map) json);
JSONArray user = json.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
} catch (Exception e) {
e.printStackTrace();
}
if (file_url != null) {
Toast.makeText(MainActivity.this, json.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
}
}
did four changes in total: mentioned as edited# wherever I did. please fins them and make it in your file,

Categories

Resources