How can I pass Strings from doInBackground to onPostExecute - android

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.

Related

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);
}
}
}

Detail view of listview

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

How to fetch data from json in android which does not have array name?

I want to get an url from this link:
"http://graph.facebook.com/10202459285618351/picture?type=large&redirect=false"
it gives result:
{
"data": {
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/t1.0- 1/s200x200/10342822_10202261537234765_3194866551853134720_n.jpg",
"is_silhouette": false
}
}
I tried,
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(AccountActivity.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();
String jsonStr = sh.makeServiceCall(fbPicURL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
fbRealURL = jsonObj.getString("url");
// Phone node is JSON Object
Toast.makeText(AccountActivity.this, fbRealURL,
Toast.LENGTH_LONG).show();
// tmp hashmap for single 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
* */
Toast.makeText(AccountActivity.this, fbRealURL,
Toast.LENGTH_LONG).show();
}
}
But returning null and its not crashing..
You have to get the data object first like this:
try {
JSONObject jsonObj = new JSONObject(jsonStr);
fbRealURLObj = jsonObj.getJSONObject("data");
fbRealURL = fbRealURLObj.getString("url");
// Phone node is JSON Object
Toast.makeText(AccountActivity.this, fbRealURL,
Toast.LENGTH_LONG).show();
// tmp hashmap for single contact
}

how to refresh the ListView in android when data i appended to ListView

I have made a ListView and made a custom adapter for it,I am calling two Asynctask one for getting all messages from webservice and another is for reply of the message,I want to append the replied message to the ListView. Currently i am not getting it right way. My code is as below:
main.java
import com.epe.yehki.adapter.ChatAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.uc.Header;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
public class ChatHistoryActivity extends Activity {
private ProgressDialog pDialog;
JSONArray msgArry;
JSONObject jsonObj;
private ChatAdapter chatContent;
ArrayList<HashMap<String, String>> msgList;
ListView lv;
JSONArray msgs = null;
String pro_id, pro_name, pro_img, grup_id, sender_id, cust_id;
TextView tv_switch;
public boolean flag = false;
Header header;
Menu menu;
Intent in;
Button reply;
RelativeLayout rl_reply;
EditText et_reply;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_chat_history);
lv = (ListView) findViewById(R.id.list);
tv_switch = (TextView) findViewById(R.id.tv_switch);
header = (Header) findViewById(R.id.header_msg);
menu = (Menu) findViewById(R.id.menu_msg);
reply = (Button) findViewById(R.id.btn_reply);
rl_reply = (RelativeLayout) findViewById(R.id.rl_reply);
rl_reply.setVisibility(View.GONE);
et_reply = (EditText) findViewById(R.id.et_reply);
menu.setSelectedTab(3);
header.title.setText("Conversation");
msgList = new ArrayList<HashMap<String, String>>();
pro_id = getIntent().getStringExtra(Const.TAG_PRODUCT_ID);
sender_id = getIntent().getStringExtra(Const.TAG_CUSTOMER_ID);
grup_id = getIntent().getStringExtra(Const.TAG_GROUP_ID);
cust_id = Pref.getValue(ChatHistoryActivity.this, Const.PREF_CUSTOMER_ID, "");
/* new GetChatHistory().execute(); */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
rl_reply.setVisibility(View.VISIBLE);
}
});
// message reply ...!!Chat api(conversation)
reply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new DoReply().execute();
// new GetChatHistory().execute();
}
});
}
#Override
protected void onResume() {
super.onResume();
new GetChatHistory().execute();
}
private class GetChatHistory extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ChatHistoryActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
String query = Const.API_CHAT_HISTORY;
url = "?customer_id=" + cust_id + "&group_id=" + grup_id + "&sender_id=" + sender_id + "&product_id=" + pro_id;
url = url.replace(" ", "%20");
url = query + url;
System.out.println(":::::::::::::My MESSGES URL::::::::::::::" + url);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
msgArry = new JSONArray(jsonStr);
if (msgArry != null && msgArry.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + msgArry.length());
for (int i = 0; i < msgArry.length(); i++) {
JSONObject c = msgArry.getJSONObject(i);
String custID = c.getString(Const.TAG_CUSTOMER_ID);
String custName = c.getString(Const.TAG_CUSTOMER_NAME);
String proID = c.getString(Const.TAG_PRODUCT_ID);
String email = c.getString(Const.TAG_CUSTOMER_EMAIL);
String photo = Const.API_HOST + "/" + c.getString(Const.TAG_PHOTO);
String msg_body = c.getString(Const.TAG_MESSAGE_BODY);
HashMap<String, String> message = new HashMap<String, String>();
message.put(Const.TAG_CUSTOMER_ID, custID);
message.put(Const.TAG_CUSTOMER_NAME, custName);
message.put(Const.TAG_PRODUCT_ID, proID);
message.put(Const.TAG_CUSTOMER_EMAIL, email);
message.put(Const.TAG_PHOTO, photo);
message.put(Const.TAG_MESSAGE_BODY, msg_body);
msgList.add(message);
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Utils.showCustomeAlertValidation(ChatHistoryActivity.this, "No messgaes found", "yehki", "Ok");
msgList.clear();
}
});
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog != null)
pDialog.dismiss();
System.out.println("::::::::::::inside post:::::::::::");
chatContent = new ChatAdapter(ChatHistoryActivity.this, msgList);
chatContent.notifyDataSetChanged();
lv.setAdapter(chatContent);
}
}
/*
* GET CONVERSATION LIST.........REPLY
*/
private class DoReply extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ChatHistoryActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
String query = Const.API_MESSAGE_REPLY;
url = "?customer_id=" + cust_id + "&group_id=" + grup_id + "&receiver_id=" + sender_id + "&product_id=" + pro_id + "&message=" + et_reply.getText().toString().trim();
url = url.replace(" ", "%20");
url = query + url;
System.out.println(":::::::::::::My MESSGES URL::::::::::::::" + url);
System.out.println(":::::::::::::::get chat history called:::::::::::::;;");
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.getString("status").equals("sucess")) {
// et_reply.setText("");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ChatHistoryActivity.this, "Message has been sent", Toast.LENGTH_SHORT).show();
}
});
} else {
// et_reply.setText("");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ChatHistoryActivity.this, "Message has not been sent", Toast.LENGTH_SHORT).show();
}
});
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
System.out.println("::::::::::::inside post:::::::::::");
// Dismiss the progress dialog
if (pDialog != null)
pDialog.dismiss();
chatContent = new ChatAdapter(ChatHistoryActivity.this, msgList);
chatContent.notifyDataSetChanged();
lv.setAdapter(chatContent);
new GetChatHistory().execute();
}
}
}

How to execute Asynctask simultaneously

I have two asynctask in one class and i am having trouble in executing them at the same time.
Here is my scenario, my the user clicks the view january calendar button it will show up the events for the month of calendar and the comments for it. The events and comments are stored in mysql database so i have to fetch different url. I used asyctask to fetch the url. Whenever i call the other asynctask it cannot be resolved. help me out!
Here is my code:
package sscr.stag;
#SuppressLint("ShowToast")
public class Calendar extends ListActivity {
// All xml labels
TextView txtEvent;
// Progress Dialog
private ProgressDialog pDialog;
JSONArray user;
JSONObject hay;
private static final String CALENDAR_URL = "http://www.stagconnect.com/StagConnect/calendar/januaryCalendar.php";
private static final String COMMENT_URL = "http://www.stagconnect.com/StagConnect/calendar/januaryReadComment.php";
private static final String TAG_USER = "username";
private static final String TAG_MESSAGE = "message";
private static final String TAG_TIME = "time";
private static final String TAG_ARRAY = "posts";
private JSONArray mCalendar = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendaradmin);
txtEvent = (TextView) findViewById(R.id.event);
new LoadCalendar().execute();
new LoadCommentCal().execute(); // error here, says cannot be resolved in this type
}
private class LoadCalendar extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Calendar.this);
pDialog.setMessage("Loading Calendar.. ");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
String json = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(CALENDAR_URL);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("Profile JSON: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
pDialog.dismiss();
try
{
hay = new JSONObject(json);
JSONArray user = hay.getJSONArray("posts");
JSONObject jb= user.getJSONObject(0);
String event = jb.getString("activities");
txtEvent.setText(event);
}catch(Exception e)
{
e.printStackTrace();
}
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(COMMENT_URL);
try {
mCalendar = json.getJSONArray(TAG_ARRAY);
for (int i = 0; i < mCalendar.length(); i++) {
JSONObject c = mCalendar.getJSONObject(i);
String username = c.getString(TAG_USER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_USER, username);
mCommentList.add(0, map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(Calendar.this, mCommentList,
R.layout.calendar_comment, new String[] { TAG_MESSAGE,
TAG_USER, TAG_TIME }, new int[] { R.id.message,
R.id.username, R.id.time });
setListAdapter(adapter);
ListView lv = getListView();
lv.scrollTo(0, 0);
}
public class LoadCommentCal extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Calendar.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(Void... args) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
}
Your second asynctask public class LoadCommentCal extends AsyncTask is inside the first asynctask!
You need to move it out of the first asynctask.
private class LoadCalendar extends AsyncTask<String, String, String> {
...
}
... other functions
private class LoadCommentCal extends AsyncTask<Void, Void, String> {
...
}
You are declaring lots of things inside the first AsyncTask I strongly reccomend to close your AsyncTask after the onPostExecute
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
pDialog.dismiss();
try
{
hay = new JSONObject(json);
JSONArray user = hay.getJSONArray("posts");
JSONObject jb= user.getJSONObject(0);
String event = jb.getString("activities");
txtEvent.setText(event);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
and then removing one } at the end of the java file (and also reindent if you wish)

Categories

Resources