Progress Dialog not showing in Android - android

Progress Dialog is not showing in AsyncTask Class In Android.
My AsyncTask Class Code:
class SyncData1 {
Context context;
DatabaseHelper myDbHelper;
ArrayList<String> ItemNo= new ArrayList<String>();
ArrayList<String> RepReceivedQty= new ArrayList<String>();
ArrayList<String> HotelReceivedQty= new ArrayList<String>();
ArrayList<String> IStatus= new ArrayList<String>();
String jsodata;
String ChallanNo="",HotelRepReceivedOn="",HotelReceivedOn="",Status="";
String url=null;
Commans com;
public SyncData1(Context context)
{
this.context=context;
}
public void fetchData()
{
ItemNo.clear();
IStatus.clear();
RepReceivedQty.clear();
HotelReceivedQty.clear();
com= new Commans(context);
myDbHelper =new DatabaseHelper(context);
com.connectdb(myDbHelper);
Cursor curval= myDbHelper.dbQery("Select * from Challan_R where Flag=1 limit 1");
if(curval != null && curval.moveToFirst()) {
ChallanNo= curval.getString(0);
Status=curval.getString(5);
HotelRepReceivedOn=curval.getString(6);
HotelReceivedOn= curval.getString(7);
}
curval.close();
Cursor curItem= myDbHelper.dbQery("Select * from ChallanItems where ChallanNo= "+"'"+ChallanNo+"'");
if(curItem != null && curItem.moveToFirst()) {
while( !curItem.isAfterLast())
{
ItemNo.add(curItem.getString(0));
IStatus.add(curItem.getString(2));
RepReceivedQty.add(curItem.getString(9));
HotelReceivedQty.add(curItem.getString(1));
curItem.moveToNext();
}
}
curItem.close();
if(ChallanNo.length()>1)
{
jsodata=com.reciveJson(ChallanNo, HotelRepReceivedOn, HotelReceivedOn, Status, ItemNo, RepReceivedQty, HotelReceivedQty, IStatus);
Log.d("Json", jsodata);
ReciveChallanAsyn task = new ReciveChallanAsyn();
task.execute("");
}
}
private class ReciveChallanAsyn extends AsyncTask<String, Void, String> {
public static final int HTTP_TIMEOUT = 30 * 1000;
#Override
protected String doInBackground(String... urls) {
String response = "";
HttpEntity resEntity;
try {
//url=urls[0].getUrl();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.SERVICE_SYNC_DATA);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("data",jsodata));
nameValuePairs.add(new BasicNameValuePair("token",CreateChallan.token));
nameValuePairs.add(new BasicNameValuePair("customer_code",CreateChallan.strcustomer_code));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse responsePOST = httpclient.execute(httppost);
resEntity = responsePOST.getEntity();
response=EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#SuppressLint("DefaultLocale")
#Override
protected void onPostExecute(String result) {
Log.d("Result", result);
pd.dismiss();
if(result!=null)
{
if(result.contentEquals("1") && result!=null)
{ com.connectdb(myDbHelper);
Toast.makeText(context, " Challan Sent ", Toast.LENGTH_LONG).show();
myDbHelper.ChallN_Updateb("", "2", ChallanNo,"");
Cursor curval1= myDbHelper.dbQery("Select * from Challan_R where Flag=1 limit 1");
if(curval1 != null && curval1.moveToFirst()) {
fetchData();
}
curval1.close();
com.disconnectdb();
}
else
Toast.makeText(context, "Error In Sending Challan", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "Data Not Fount", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPreExecute()
{
// pd = ProgressDialog.show(HomeChallan.this, ""," Please wait...");
pd = new ProgressDialog(HomeChallan.this);
pd.setMessage(" Please wait... ");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
It's a subclass of my main class where I am using the Async Task class
I am using the class SyncData1 class on onclickListerner Method
Cursor curval1= myDbHelper.dbQery("Select * from Challan_R where Flag=1 limit 1");
if(curval1 != null && curval1.moveToFirst()) {
SyncData1 data= new SyncData1(context);
data.fetchData();

Hope this can solve your issue, do some editing as per your requirment..
private final Handler handler = new Handler();
private Thread thread;
private QueueRunner runner = new QueueRunner();
private CustomProgressDialog mProgressBar;
private class QueueRunner implements Runnable
{
public void run()
{
try
{
synchronized(this)
{
handler.post(new Runnable()
{
public void run()
{
if (((Activity) AsyncWebPostClient.this.context).isFinishing() == false)
mProgressBar = CustomProgressDialog.show(AsyncWebPostClient.this.context,
null,null,true,true );
}
});
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
in your preExecute call this..
thread = new Thread(runner);
thread.start();
in your onpost call this..
mProgressBar.dismiss();
Edit: I have use customeProgress Dialog you can use Progress Dialog

this is your asynctask method,copy and paste it hope it's worked:
private class ReciveChallanAsyn extends AsyncTask<String, Void, String> {
public static final int HTTP_TIMEOUT = 30 * 1000;
#Override
protected void onPreExecute()
{
// pd = ProgressDialog.show(HomeChallan.this, ""," Please wait...");
pd = new ProgressDialog(HomeChallan.this);
pd.setMessage(" Please wait... ");
pd.setIndeterminate(false);
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... urls) {
String response = "";
HttpEntity resEntity;
try {
//url=urls[0].getUrl();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.SERVICE_SYNC_DATA);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("data",jsodata));
nameValuePairs.add(new BasicNameValuePair("token",CreateChallan.token));
nameValuePairs.add(new BasicNameValuePair("customer_code",CreateChallan.strcustomer_code));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse responsePOST = httpclient.execute(httppost);
resEntity = responsePOST.getEntity();
response=EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#SuppressLint("DefaultLocale")
#Override
protected void onPostExecute(String result) {
Log.d("Result", result);
pd.dismiss();
if(result!=null)
{
if(result.contentEquals("1") && result!=null)
{ com.connectdb(myDbHelper);
Toast.makeText(context, " Challan Sent ", Toast.LENGTH_LONG).show();
myDbHelper.ChallN_Updateb("", "2", ChallanNo,"");
Cursor curval1= myDbHelper.dbQery("Select * from Challan_R where Flag=1 limit 1");
if(curval1 != null && curval1.moveToFirst()) {
fetchData();
}
curval1.close();
com.disconnectdb();
}
else
Toast.makeText(context, "Error In Sending Challan", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "Data Not Fount", Toast.LENGTH_LONG).show();
}
}
}

Related

Could not get the value from Edit Text element

Fantastic morg. Below this code to get data from mysql database and displayed into the EditText element.There is no problem with getting data from db its working good using this asyn tesk new checkUserPermission().execute("");.
Problem is
I want to make some calculation from code and dispaly in another Edittext. so i need values thats why i get data from db.while OnCreate() to get the data from db(its working). whenever i call this calculatePL(); method i could not get value.
LOGCAT:
System.out: Empty Value
Why its empty or something. but above my edittext elements hold the
values.
...some declaration of variables and etc....
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.five_activity);
new checkUserPermission().execute(""); //call here
calculatePL();//call the method
}
class checkUserPermission extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(Five_Activity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Please wait..");
Dialog.show();
super.onPreExecute();
userid = (TextView)findViewById(R.id.userID);
uid = userid.getText().toString();
System.out.println(uid);
}
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>();
values.add(new BasicNameValuePair("userid", uid));
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.13:8090/stat_api/shiftClose.php");
httppost.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is2 = entity.getContent();
Log.i("TAG", "Connection Successful");
} catch (Exception e) {
Log.i("TAG", e.toString());
//Invalid Address
}
try {
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2, "iso-8859-1"), 8);
StringBuilder sb2 = new StringBuilder();
while ((line2 = reader2.readLine()) != null) {
sb2.append(line2 + "\n");
}
is2.close();
result2 = sb2.toString();
JSONObject json_data2 = new JSONObject(result2);
code2=(json_data2.getString("code"));
Allvalues = code2;
String[] splited = Allvalues.split("\\s+");
Totalkm=splited[0];
discountamt=splited[1];
receviedamt=splited[2];
totalamt=splited[3];
expen=splited[4];
//Log.d("Splited String ", "Splited String" + totalamt+expen);
runOnUiThread(new Runnable() {
#Override
public void run() {
totkm.setText(Totalkm);
discount.setText(discountamt);
recamt.setText(receviedamt);
totamt.setText(totalamt);
expenses.setText(expen);
}
});
Log.i("TAG", "Result Retrieved");
} catch (Exception e) {
Log.i("TAG", e.toString());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
// Close progress dialog
Dialog.dismiss();
}
}
public void calculatePL(){
try {
String a_value =totamt.getText().toString().trim();
System.out.println(a_value);
}catch(NumberFormatException numberEx)
{
System.out.println(numberEx);
}
}
Your checkUserPermission executes in background. And immediately you are calling calculatePL() so your main thread is not waiting for checkUserPermission execution to complete.
What you need to do is, make wait your main thread so that after full execution of checkUserPermission calculatePL() will get called. You can achieve it by adding ProgressDialog. Show the ProgressDialog in onPreExecute() and dismiss it in onPostExecute()
Hope it will do your job.
Override protected void onPostExecute in your asyncTask and call calculatePl() here. And you should set Edittext's text in onPostExecute too, because this method is main thread and you don't need to use runOnUIThread.
EDIT with example code:
class checkUserPermission extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(Five_Activity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Please wait..");
Dialog.show();
super.onPreExecute();
userid = (TextView)findViewById(R.id.userID);
uid = userid.getText().toString();
System.out.println(uid);
}
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>();
values.add(new BasicNameValuePair("userid", uid));
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.13:8090/stat_api/shiftClose.php");
httppost.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is2 = entity.getContent();
Log.i("TAG", "Connection Successful");
} catch (Exception e) {
Log.i("TAG", e.toString());
//Invalid Address
}
try {
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2, "iso-8859-1"), 8);
StringBuilder sb2 = new StringBuilder();
while ((line2 = reader2.readLine()) != null) {
sb2.append(line2 + "\n");
}
is2.close();
result2 = sb2.toString();
JSONObject json_data2 = new JSONObject(result2);
code2=(json_data2.getString("code"));
Allvalues = code2;
} catch (Exception e) {
Log.i("TAG", e.toString());
e.printStackTrace();
}
return Allvalues;
}
protected void onPostExecute(String result){
String[] splited = result.split("\\s+");
Totalkm=splited[0];
discountamt=splited[1];
receviedamt=splited[2];
totalamt=splited[3];
expen=splited[4];
totkm.setText(Totalkm);
discount.setText(discountamt);
recamt.setText(receviedamt);
totamt.setText(totalamt);
expenses.setText(expen);
// Close progress dialog
Dialog.dismiss();
calculatePL();
}
}
Make sure totamt is declared as a global. Try logging the value of totamt or an object of the same. Finally check where you have declared it.

How to cancel async task while uploading video using multipart in android

I'm working on android application in which I'm uploading videos to server using multipart upload and AsyncTask.
I want to cancel AsyncTask after clicking on cancel button of progress bar
here is my code.
uploadVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadVideoButton.setEnabled(false);
uploadtoserver = new UploadFileToServer();
uploadtoserver.execute(objVideoList.getImage_path());
}
private class UploadFileToServer extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(AddVideoActivity.this);
progressDialog.setMessage("Uploading Video...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(true);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (uploadtoserver != null && uploadtoserver.getStatus() != AsyncTask.Status.FINISHED)
uploadtoserver.cancel(true);
}
});
progressDialog.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// progressBar.setProgress(progress[0]);
// percentageTextView.setText(String.valueOf(progress[0]) + "%");
if(isCancelled())
{
return ;
}
else
{
progressDialog.setProgress(progress[0]);
if(progress[0] == 100)
{
progressDialog.setMessage("Validating video from server...");
//progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
}
}
#Override
protected String doInBackground(String... params) {
return uploadFile(params[0]);
}
#SuppressWarnings("deprecation")
private String uploadFile(String filePath) {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.FILE_UPLOAD_URL);
if(isCancelled())
{
publishProgress(CANCELLED);
return(null);
}
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
if(isCancelled())
{
publishProgress(CANCELLED);
return;
}
else
{
publishProgress( (int) ((num * 100) / totalSize));
//int value = (int) ((num * 100) / totalSize);
}
//publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("video_file", new FileBody(sourceFile));
String userId = new DevicePreferences().getString(
AddVideoActivity.this, Constants.PREF_USER_ID, "");
entity.addPart("user_id", new StringBody(userId));
entity.addPart("detail", new StringBody(descriptionEditText
.getText().toString()));
entity.addPart("title", new StringBody(titletext.getText()
.toString()));
entity.addPart("image_path", new StringBody(filePath));
totalSize = entity.getContentLength();
entity.addPart("video_size",
new StringBody(Long.toString(totalSize)));
httppost.setEntity(entity);
if(isCancelled())
{
publishProgress(CANCELLED);
return(null);
}
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onCancelled(String result) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
new AlertMessage(AddVideoActivity.this)
.showAToast("Cancelled by user");
uploadVideoButton.setEnabled(true);
super.onCancelled(result);
}
#Override
protected void onPostExecute(String result) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
//new AlertMessage(AddVideoActivity.this)
// .showAToast(result);
if(!isCancelled())
{
Object json;
try {
json = new JSONTokener(result).nextValue();
if (json instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) json;
if (jsonObject.has("status")) {
if (jsonObject.getString("status").equalsIgnoreCase(
"ok")) {
objVideoList
.setVideo_id(jsonObject.getString("id"));
showAlert("Uploaded Successfully.",
percentageTextView, progressBar, true);
} else {
showAlert("Some error occured", percentageTextView,
progressBar, false);
}
} else {
showAlert(result, percentageTextView, progressBar,
false);
}
} else {
showAlert(result, percentageTextView, progressBar, false);
}
} catch (JSONException e) {
showAlert(result, percentageTextView, progressBar, false);
} finally {
uploadVideoButton.setEnabled(true);
}
}
super.onPostExecute(result);
}
AsyncTasks are tricky to cancel. Better you use OKHTTP for example, so you cancel it this way
to cancel asynctask uyou can call uploadtoserver.cancel(true);

How to Asynctask within fragment?

I want to use a DefaultHttpClient/HttpGet asynctask to grab the JSON from the school's site. But I want to request it from within the Fragment.
How can I do that without failing?
This is what I already tried:
public class RequestData extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private Context context;
private String Error = null;
private ProgressDialog Dialog;
public RequestData(Context context) {
this.context = context;
}
protected void onPreExecute() {
Dialog = new ProgressDialog(context);
Dialog.setMessage("Downloading source..");
Dialog.show();
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
if (Error != null) {
Toast.makeText(context, Error, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Source: " + Content, Toast.LENGTH_LONG).show();
}
}
}
Which is called by this:
RequestData request = new RequestData(getSherlockActivity());
request.execute(getBaseURL() + "phpinfo.php");

Can't show Toast inside AsyncTask inside a DialogFragment

I'm using a DialogFragment to show a simple form, which then is posted to a remote server and a success/fail code is sent back.
However whenever I want to show a Toast when an error occurred I get an exception in which getActivity() returns null. Any idea why this is?
This is a summary of the code:
private class UploadNewGroupToServer extends AsyncTask<String, Void, Void>
{
ProgressDialog createGroupProgressDialog;
#Override
protected Void doInBackground(String... params)
{
getActivity().runOnUiThread(new Runnable()
{
public void run()
{
createGroupProgressDialog = new ProgressDialog(getActivity());
createGroupProgressDialog.setTitle("Creating group...");
createGroupProgressDialog.show();
}
});
String encodedImage = params[0];
String groupTitle = params[1];
String groupDesc = params[2];
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_API_CREATE_GROUP);
try
{
// Add data
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if(encodedImage != null)
{
nameValuePairs.add(new BasicNameValuePair("picture", encodedImage));
}
nameValuePairs.add(new BasicNameValuePair("title", groupTitle));
nameValuePairs.add(new BasicNameValuePair("desc", groupDesc));
nameValuePairs.add(new BasicNameValuePair("token", "MY_TOKEN_HERE!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Log.d("APP", "Going to execute ");
final String responseBody = httpclient.execute(httppost, responseHandler);
Log.d("APP", "Back from execute, responseBody is " + responseBody);
//More business logic here
// . . . . .
throw new Exception(); //simulate an error
} catch (final Exception e)
{
Log.d("APP", "Exception es " + e.getMessage());
createGroupProgressDialog.dismiss();
getActivity().runOnUiThread(new Runnable() //App dies here!
{
public void run()
{
Toast.makeText(getActivity(), "Error!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
Here's the logcat:
11-04 00:16:18.414: E/AndroidRuntime(7229): Caused by: java.lang.NullPointerException
11-04 00:16:18.414: E/AndroidRuntime(7229): at com.myapp.android.GroupCreateDialogFragment$UploadNewGroupToServer.doInBackground(GroupCreateDialogFragment.java:204)
11-04 00:16:18.414: E/AndroidRuntime(7229): at com.myapp.android.GroupCreateDialogFragment$UploadNewGroupToServer.doInBackground(GroupCreateDialogFragment.java:1)
11-04 00:16:18.414: E/AndroidRuntime(7229): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-04 00:16:18.414: E/AndroidRuntime(7229): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-04 00:16:18.414: E/AndroidRuntime(7229): ... 4 more
When you invoke asynctask use
new UploadNewGroupToServer(getActivity()).execute();.
Now in the constructor
Context mContext;
pulic void UploadNewGroupToServer(Context context)
{
mContext = context;
}
Also move your progressdialog initialization to the constructor
pulic void UploadNewGroupToServer(Context context)
{
createGroupProgressDialog = new ProgressDialog(context);
createGroupProgressDialog.setTitle("Creating group...");
}
In onPreExecute
public void onPreExecute()
{
super.onPreExecute();
createGroupProgressDialog.show();
}
Also instead of displaying toast in doInbackground return result and in onPostExecute dismiss dialog and show toast accordingly.
Could your create a handler in your async task? If handler created in UI thread(If use MainLooper) post method samely runOnUiThread.
private class UploadNewGroupToServer extends AsyncTask<String, Void, Void>
{
ProgressDialog createGroupProgressDialog;
Handler handler;
protected void onPreExecute(){
handler = new Handler();
}
#Override
protected Void doInBackground(String... params)
{
handler.post(new Runnable()
{
public void run()
{
createGroupProgressDialog = new ProgressDialog(getActivity());
createGroupProgressDialog.setTitle("Creating group...");
createGroupProgressDialog.show();
}
});
String encodedImage = params[0];
String groupTitle = params[1];
String groupDesc = params[2];
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_API_CREATE_GROUP);
try
{
// Add data
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if(encodedImage != null)
{
nameValuePairs.add(new BasicNameValuePair("picture", encodedImage));
}
nameValuePairs.add(new BasicNameValuePair("title", groupTitle));
nameValuePairs.add(new BasicNameValuePair("desc", groupDesc));
nameValuePairs.add(new BasicNameValuePair("token", "MY_TOKEN_HERE!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Log.d("APP", "Going to execute ");
final String responseBody = httpclient.execute(httppost, responseHandler);
Log.d("APP", "Back from execute, responseBody is " + responseBody);
//More business logic here
// . . . . .
throw new Exception(); //simulate an error
} catch (final Exception e)
{
Log.d("APP", "Exception es " + e.getMessage());
createGroupProgressDialog.dismiss();
handler.post(new Runnable() //App dies here!
{
public void run()
{
Toast.makeText(getActivity(), "Error!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}

ProcessDialog is not appearing properly?

This is my function that is in LoginActivity.java.So onclick of button i am calling this function.
public void postHttpRequest(String userId,String pass,TextView error){
RequestClient reqClient = new RequestClient(LoginActivity.this);
String AppResponse = null;
try {
url = "myurl";
Log.d("URL", url);
AppResponse = reqClient.execute().get();
String status = ValidateLoginStatus.checkLoginStatus(AppResponse);
Log.d("Status recived", status);
if(status.equals("200")){
saveInformation(userId,pass);
startingActivity(HOST_URL);
}else{
error.setText("Incorrect UserName or Password");
}
} catch (Exception e) {
Log.e("Exception Occured", "Exception is "+e.getMessage());
}
}
From this function i am calling a AsynkTask for Http Communication.So onclick of button when i am geeting the response then my processDialog in opening just for one sec.I want as i click the buttoon my processDialog should get open utill i got the response
public class RequestClient extends AsyncTask<String, Void, String>{
ProgressDialog pDialog;
Context context;
public RequestClient(Context c) {
context = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Authenticating user...");
pDialog.show();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
DefaultHttpClient httpClient=new DefaultHttpClient();
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(LoginActivity.url);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_ERROR", responseString);
httpClient.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(pDialog!=null)
pDialog.dismiss();
}
}
So please suggest me what changes i have to make so that processDialog should display properly in the center of the device
//add style in your progressbialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Authenticating user...");
if (pDialog != null && !pDialog.isShowing()) {
pDialog.show();
}
}
AsyncTask return value only after using get() method
Drawing from the above link
Calling the get() method of AsyncTask will block the main thread and wait for the result to be returned. This effectively makes using an AsyncTask become a synchronous operation in which case there's no point in using an AsyncTask.
The only reason I can think of to use the get() method would be from a thread other than the main (UI) thread although I can't think of many reasons to do that.
On Button click
RequestClient reqClient = new RequestClient(LoginActivity.this,new TheInterface() {
#Override
public void theMethod(String result) {
Log.i("Result =",result);
}
});
reqClient.execute(url); // no get(). pass url to doInBackground()
In your activity class
public interface TheInterface {
public void theMethod(String result);
}
}
AsyncTask
public class RequestClient extends AsyncTask<String, Void, String>{
ProgressDialog pDialog;
Context context;
TheInterface listener;
public RequestClient(Context c,TheInterface listen) {
context = c;
listener = listen;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Authenticating user...");
pDialog.show();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
HttpClient client;
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(aurl[0]); // url
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_ERROR", responseString);
client.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pDialog.dismiss();
if (listener != null)
{
listener.theMethod(result);
}
}
}
It seems that your button code is not correct, because it's async, but you are trying to use it as standart sync code.
Try to move this code into onPostExecute:
String status = ValidateLoginStatus.checkLoginStatus(response);
Log.d("Status recived", status);
if(status.equals("200")){
saveInformation(userId,pass);
startingActivity(HOST_URL);
}else{
error.setText("Incorrect UserName or Password");
}
and make this button click code:
public void postHttpRequest(String userId,String pass,TextView error){
RequestClient reqClient = new RequestClient(LoginActivity.this);
String AppResponse = null;
try {
url = "myurl";
Log.d("URL", url);
reqClient.execute();
} catch (Exception e) {
Log.e("Exception Occured", "Exception is "+e.getMessage());
}
}

Categories

Resources