How to cancel async task while uploading video using multipart in android - 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);

Related

How to get correct entity content length to show progress in progress dialog?

I want to upload multiple image files using Android MultiPart Entity via AsyncTask in an activity. When I attempt to upload single image file then the progress dialog shows correct progress and as soon as 100% progress is reached the dialog dismisses and does the further tasks. But, when I am attempting to upload multiple image files it shows the 100% progress and the progress dialog is stuck till other image files are being uploaded to server. I add the multiple image files to entity using a for loop. But when I try to get the content length it seems that I am getting wrong value.
#SuppressWarnings("deprecation")
private class UploadAttachments extends AsyncTask<Void, Integer, String> {
ProgressDialog pDialog;
long totalSize = 0;
int statusCode;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegistrationActivity.this);
pDialog.setMessage(getString(R.string.label_upload_attachments));
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setMax(mFilePaths.size());
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
pDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Network.URL_UPLOAD);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
for (int i = 0; i < mFilePaths.size(); i++) {
entity.addPart("image" + i, new FileBody(new File(mFilePaths.get(i))));
mPrefix += 1;
entity.addPart("prefix" + i, new StringBody(String.valueOf(mPrefix)));
}
totalSize = entity.getContentLength();
entity.addPart("count", new StringBody(String.valueOf(mFilePaths.size())));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = getString(R.string.label_upload_successful);
} else {
responseString = getString(R.string.error_network_error);
}
} catch (IOException e) {
responseString = getString(R.string.error_network_error);
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if (mToast != null) mToast.cancel();
mToast = makeText(getApplicationContext(), result, Toast.LENGTH_SHORT);
mToast.show();
mPreferences.clearRegDetails();
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
}
}
Please have a look. Please help me on this! Thanks.

How to send large video file to server in android

Hi i am trying to upload large video files to server using Volley library but when i request big video files to server it's taking too large time and video not uploading there is server side limitation 4MB
how can i resolve this problem please help me some one
my code:
RequestQueue queue = Volley.newRequestQueue(context.getApplicationContext());
final String url = Constants.SERVER_URL + serverUrl;
MultipartAPI multipartAPI = new MultipartAPI(url, params, authenticationHeaders,fileType,fileMap, reqType,
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyErrorvolleyError) {
// progressDialog.dismiss();
if (volleyError != null) {
}
}
}, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("------->" + response);
}
});
int socketTimeout = 450000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
multipartAPI.setRetryPolicy(policy);
queue.add(multipartAPI);
Define Progress bar displaying uploading progress
private ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
Uploading the file to server
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("PHP FILE_UPLOAD_URL Here");
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(" Your File Path");
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// 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 onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}
Method to show alert dialog
private void showAlert(String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle("Response from Servers")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
Start uploading call
new UploadFileToServer().execute();

How to use Handler in AsynkTask in android

I am fetching data from server using AsynkTask which works fine but I want to use handler in AsynkTask to reduce load from main Thread.How can I use Handler in AsynkTask. Kindly help me to solve this problem.
Here is my code.
public class CLoginScreen extends Fragment {
public static String s_szLoginUrl = "http://192.168.0.999:8080/rest/json/metallica/getLoginInJSON";
public static String s_szresult = " ";
public static String s_szMobileNumber, s_szPassword;
public static String s_szResponseMobile, s_szResponsePassword;
public View m_Main;
public EditText m_InputMobile, m_InputPassword;
public AppCompatButton m_LoginBtn, m_ChangePass, m_RegisterBtn;
public CJsonsResponse m_oJsonsResponse;
public boolean isFirstLogin;
public JSONObject m_oResponseobject;
public LinearLayout m_MainLayout;
public CLoginSessionManagement m_oLoginSession;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.login_screen, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
m_oLoginSession = new CLoginSessionManagement(getActivity());
init();
return m_Main;
}
public void init() {
m_MainLayout = (LinearLayout) m_Main.findViewById(R.id.mainLayout);
m_InputMobile = (EditText) m_Main.findViewById(R.id.input_mobile);
m_InputPassword = (EditText) m_Main.findViewById(R.id.input_password);
m_LoginBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Login);
m_ChangePass = (AppCompatButton) m_Main.findViewById(R.id.btn_ChangePass);
m_ChangePass.setBackgroundColor(Color.TRANSPARENT);
m_ChangePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CChangePasswordScreen()).commit();
}
});
m_RegisterBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Register);
m_RegisterBtn.setBackgroundColor(Color.TRANSPARENT);
m_RegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CRegistrationScreen()).commit();
}
});
m_LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginAttempt().execute();
}
});
}
private class LoginAttempt extends AsyncTask<String, Void, String> {
public Dialog m_Dialog;
public ProgressBar m_ProgressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
m_Dialog = new Dialog(getActivity());
m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
m_Dialog.setContentView(R.layout.progress_bar);
showProgress("Please wait while Logging...");// showing progress ..........
}
#Override
protected String doInBackground(String... params) {
getLoginDetails();// getting login details from editText...........
InputStream inputStream = null;
m_oJsonsResponse = new CJsonsResponse();
isFirstLogin = true;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(s_szLoginUrl);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", s_szMobileNumber);
jsonObject.put("pin", s_szPassword);
jsonObject.put("firstloginflag", m_oLoginSession.isLogin());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
// httpPost.setHeader("Accept", "application/json"); ///not required
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
// 9. receive response as inputStream
inputStream = entity.getContent();
System.out.print("InputStream...." + inputStream.toString());
System.out.print("Response...." + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.print("statusLine......" + statusLine.toString());
////Log.d("resp_body", resp_body.toString());
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
// 10. convert inputstream to string
if (inputStream != null) {
s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
//String resp_body =
EntityUtils.toString(httpResponse.getEntity());
}
} else
s_szresult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
System.out.println("s_szResult....." + s_szresult);
System.out.println("password......" + s_szPassword);
// 11. return s_szResult
return s_szresult;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
hideProgress();// hide progressbar after getting response from server......
try {
m_oResponseobject = new JSONObject(response);// getting response from server
new Thread() {// making child thread...
public void run() {
Looper.prepare();
try {
getResponse();// getting response from server
Looper.loop();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getResponse() throws JSONException {
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
m_oLoginSession.setLoginData(s_szResponseMobile, s_szResponsePassword);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CDealMainListing()).commit();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
showToast("Please Enter Valid Mobile Number");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
showToast("Please Enter Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {
showToast("Invalid Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {
showToast("You are blocked as You finished you all attempt");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
showToast("Connection Lost ! Please Try Again");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
showToast("User not found ! Kindly Regiter before Login");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("OTP not verify")) {
showToast("Otp not Verify ! Kindly Generate Otp on Sign Up");
}
}
public void showToast(String message) {// method foe showing taost message
Toast toast = Toast.makeText(getActivity(), "" + message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
public void getLoginDetails() {
s_szMobileNumber = m_InputMobile.getText().toString();
s_szPassword = m_InputPassword.getText().toString();
}
public void showProgress(String message) {
m_ProgressBar = (ProgressBar) m_Dialog.findViewById(R.id.progress_bar);
TextView progressText = (TextView) m_Dialog.findViewById(R.id.progress_text);
progressText.setText("" + message);
progressText.setVisibility(View.VISIBLE);
m_ProgressBar.setVisibility(View.VISIBLE);
m_ProgressBar.setIndeterminate(true);
m_Dialog.setCancelable(false);
m_Dialog.setCanceledOnTouchOutside(false);
m_Dialog.show();
}
public void hideProgress() {
m_Dialog.dismiss();
}
}
}
As per android docs here
An asynchronous task is defined by a computation that runs on a
background thread and whose result is published on the UI thread.
And loading data from URL with Handler is not a good thing. Instead use Executor or ThreadPoolExecutor to do heavy background tasks.
You Can Use
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
getResponse();
}
});
you can do like this:
class MyAsyncTask extends AsyncTask<Object,Object,Object>{
Private Context c;
private Handler handler;
private final static int YOUR_WORK_ID = 0x11;
public MyAsyncTask(Context c,Handler handler){
this.c = c;
this.handler = handler;
}
protected Object doInBackground(Object... params){
//do your work
...
Message m = handler.obtainMessage();
m.what = YOUR_WORK_ID;
...
handler.sendMessage().sendToTarget();
}
}
And in your fragment ,you can init a handler as params to MyAsyncTask,and deal with you work in handleMessage();

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

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