ProcessDialog is not appearing properly? - android

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

Related

Multiple progress bar on image

I have multiple images and i am uploading on php server using asynctask my problem is i want to show circular progress bar on every image individually like whatsapp but don't know how to do. here is my code
/**
* Uploading the file to server
* */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected String doInBackground(Void... params)
{
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(serviceurl+"conversations.php");
try {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
/* example for setting a HttpMultipartMode */
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File sourceFile = new File(imgDecodableString);
// Progress listener - updates task's progress
MyHttpEntity.ProgressListener progressListener =
new MyHttpEntity.ProgressListener() {
#Override
public void transferred(float progress) {
publishProgress((int) progress);
}
};
// Adding file data to http body
entity.addPart("file", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addTextBody("from_user",(prefid.getString("userid", null)),ContentType.TEXT_PLAIN);
entity.addTextBody("to_user",touser_id,ContentType.TEXT_PLAIN);
entity.addTextBody("message_type", msg_type,ContentType.TEXT_PLAIN);
httppost.setEntity(new MyHttpEntity(entity.build(),
progressListener));
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
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 onPostExecute(String result) {
super.onPostExecute(result);
}
}
I am calling above code in my main activity and i am using this to upload images and video.
please help me how i can set progress bar on multiple images same as in whatsapp
Thanks
You could pass the View to the AsyncTask, by create new constructor then show/hide it, notice that you have to runOnUIThread for the view.
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
ImageView iv_loading;
public UploadFileToServer(ImageView iv_loading){
this.iv_loading = iv_loading;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
runOnUiThread(new Runnable() {
#Override
public void run() {
iv_loading.setVisibility(View.VISIBLE);
}
}
);
}
...
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv_loading.setVisibility(View.GONE);
}
}
);
}
}

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

Dismiss Progress Dialog and handle exception in AsyncTask

I am having a trouble dismiss Progress Dialog if any exception occurs at doInBackground in my AsyncTask as it never reaches the onPostExecute and never dismiss the Progress Dialog which makes ANR.
Below is the code for AsyncTask
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPostExecute() {
// TODO Auto-generated method stub
super.onPostExecute();
dialogue.dismiss();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPreExecute(Void result) {
// TODO Auto-generated method stub
super.onPreExecute(result);
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}
My question is if any exception occurs at doInBackground how will I handle it and how onPostExecute will be called to dismiss the dialogue? I can not dismiss it on doInBackground. How to sync this up?
Try this..
Return something like string from doInBackground. If Exception came catch that assign string value error otherwise return success
private class checkAS extends AsyncTask<Void, Void, String>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected String doInBackground(Void... params) {
//Long Network Task
String result;
try{
result = "success"
}
catch(Exception e){
result = "error";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("error"))
dialogue.dismiss();
else
// do something
}
}
You are creating dialog dialog in onPostExecute method it should be in onPreExecute method.
try this.
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialogue.dismiss();
}
}
#Override
protected String doInBackground(String... params)
{
System.out.println("check user profile");
try
{
}
catch (Exception e)
{
e.printStackTrace();
publishProgress((e.getMessage()));
}
return result;
}
#Override
protected void onProgressUpdate(String... values)
{
// TODO Auto-generated method stub
super.onProgressUpdate(values);
Toast.makeText(activity, values[0], Toast.LENGTH_LONG);
if(dialog != null && dialog.isShowing())
dialog.dismiss();
}
#SuppressLint("InlinedApi")
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(dialog != null && dialog.isShowing())
{
dialog.dismiss();
}
}
You may want to dismiss dialog in finally block of try catch construct.
i.e.
try {
...
} catch {
...
finally{
//dismiss dialog here.
}
first check whether the dialog is showing or not using this code you can check
if(dialog.isShowing())
dialog.dismiss();
And use Exception handling to avoid unknown Exceptions
private class checkAS extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "checkAS";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 12000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 12000;
private int taskType = POST_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public checkAS(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
#SuppressWarnings("deprecation")
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost= new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
}
}
catch (Exception e) {
// display("Remote DataBase can not be connected.\nPlease check network connection.");
Log.e(TAG, e.getLocalizedMessage(), e);
return null;
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{
//display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
//do your stuff
}
catch (JSONException e1) {
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}
Try this:
private class checkAS extends AsyncTask<Void, Void, Boolean> {
ProgressDialog dialogue;
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialogue.dismiss();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(15000);
} catch (Exception e) {}
return true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialogue = new ProgressDialog(Main.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}

force Stop httpClient httpget?

aim not able at all to Stop both httpClient AND httpget
when i click on progress dialog cancel button the Request and AsyncTask shall Stop and abort but its not , the request still running until its finished
this is my AsyncTask Test code
public class getAlbuminfo extends AsyncTask<String,String, String> {
ProgressDialog progressDialog;
JSONObject data = null;
boolean prependMore = false;
//Http
HttpClient httpClient;
HttpGet httpget;
/**********
* Begien
*/
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
if ( onlypagenat == false )
{
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.setMessage(context.getResources().getString(R.string.opening_album));
progressDialog.setButton(context.getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
cancel(true);
finish();
}});
progressDialog.show();
}
prependMore = appendMore;
appendMore = false;
}
/**************
* IF Canceled
*/
#Override
protected void onCancelled() {
Log.i("Http Response:", "Aborted");
if ( httpget != null )
{
httpClient.getConnectionManager().shutdown();
httpget.abort();
}
}
/****************
* Make Request
*/
#Override
protected String doInBackground(String... params) {
String response = null;
String url = Api.foruminfo.forum_api_url+"/album.php?albumid="+albumid+"&page="+page+"&onlypagenat="+(onlypagenat?1:0);
httpClient = new DefaultHttpClient();
httpget = new HttpGet(url);
//Add Values User Headers and Cookies
httpget.addHeader("Cookie", Api.forumCookies());
httpget.setHeader("Accept-Charset", "utf-8");
// Making HTTP Request
try {
HttpResponse serverResponse = httpClient.execute(httpget);
Log.i("Http HttpResponse:", serverResponse.toString());
//Set Response
response = EntityUtils.toString(serverResponse.getEntity());
} catch (ClientProtocolException e) {e.printStackTrace();
} catch (IOException e) { e.printStackTrace();}
return response;
}
/**********************
* Done
*/
#Override
protected void onPostExecute(String response) {
Log.i("Http HttpResponse:", response);
if ( onlypagenat == false )
{
progressDialog.dismiss();
}
}
}
Any advice Please how to Full stop Get or Post http request in android !!
The AsyncTask.cancel() method has nothing to do with the cancel of a http request. cancel(true) only prevents that onPostExecute() will be invoked after doInBackground finished the job. Instead onCancelled() will be called.
If you wanna cancel a http request use HttpClient.getConnectionManager().shutdown();
public void onClick(DialogInterface dialog, int which) {
cancel(true);
httpClient.getConnectionManager().shutdown();
finish();
}});

when process dialog is being displayed, doInBackground() is not being executed

I'm trying to display process dialog, it is being showed as expected, but when it is being showed, doInBackground() is not being executed, when I press on screen of emulator, then doInBackground() starts executing again.
This is my AsyncTask class:
public class FetchEmployeeAsyncTask extends AsyncTask<String, Void, ArrayList<Employee> > {
private CaptureActivity activity;
//private ProgressDialog progressDialog;
public FetchEmployeeAsyncTask(CaptureActivity nextActivity) {
this.activity = nextActivity;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*progressDialog= new ProgressDialog(activity);
progressDialog.setCancelable(true);
progressDialog.setTitle("Fetching Employees!!");
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();*/
}
#Override
protected ArrayList<Employee> doInBackground(String... url) {
// TODO Auto-generated methoVoidd stub
ArrayList<Employee> employees = null;
for(String employeeUrl : url){
employees = fetch(employeeUrl);
}
return employees;
}
private ArrayList<Employee> fetch(String url) {
// TODO Auto-generated method stub
ArrayList<Employee> employees = null;
String response = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
employees = EmployeeXMLParser.employeeParser(response);
System.out.println("Size in fetch "+employees.size());
//System.out.println("Employee Name :: " + employees.get(0).getFirstName() + " " + employees.get(0).getLastName());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("Error parsing the response :: " + response);
e.printStackTrace();
}*/
return employees;
}
#Override
public void onPostExecute(ArrayList<Employee> employees){
super.onPostExecute(employees);
System.out.println("in post execxute "+employees.size());
//progressDialog.dismiss();
activity.showEmployees(employees);
}
}
I'm calling AsyncTask in this activity class:
public class CaptureActivity extends Activity {
private String url = "http://192.168.2.223:8680/capture/clientRequest.do?r=employeeList&cid=0";
FetchEmployeeAsyncTask employeeAsyncTask;
private ArrayList<Employee> employees = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
employeeAsyncTask = new FetchEmployeeAsyncTask(this);
employeeAsyncTask.execute(new String[] {url});
System.out.println("Status "+employeeAsyncTask.getStatus());
setContentView(R.layout.activity_capture);
}
What are you trying to do here? are you trying to get some values from the database if so check the assignment of the url if you are passing the value correctly.
Also please try explaining your problem in detail and paste some more code.
Try this:
protected void onPreExecute() {
progressDialog = ProgressDialog.show(currentActivity.this, "",
"Message Here", true);
}
protected void onPostExecute(String str) {
dialog.dismiss();
}

Categories

Resources