how cancel AsyncTask when send data - java

its my codes for send data to server i want cancel Asynctask when click back button i try a lot of way but i could not cancel Asynctask how do that??
public class sendcomment extends AsyncTask{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pr = ProgressDialog.show(sendques.this, null, null, true);
pr.setContentView(R.layout.progressdialog);
pr.getWindow().setBackgroundDrawable(newColorDrawable(android.graphics.Color.TRANSPARENT));
pr.setCancelable(true);
pr.show();
pr.setOnCancelListener(new ProgressDialog.OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
pr.cancel();
new sendcomment().cancel(true);
}
});
}
#Override
protected Object doInBackground(Object... arg0) {
// TODO Auto-generated method stub
try{
String data=URLEncoder.encode("name","utf8")+"="+URLEncoder.encode(ename.getText().toString()+"","utf8");
data+="&"+URLEncoder.encode("email","utf8")+"="+URLEncoder.encode(eemail.getText().toString()+"","utf8");
data+="&"+URLEncoder.encode("phone","utf8")+"="+URLEncoder.encode(ephone.getText().toString()+"","utf8");
data+="&"+URLEncoder.encode("question","utf8")+"="+URLEncoder.encode(equestion.getText().toString()+"","utf8");
data+="&"+URLEncoder.encode("serial","utf8")+"="+URLEncoder.encode(phoneserialnumber+"","utf8");
data+="&"+URLEncoder.encode("model","utf8")+"="+URLEncoder.encode(devicemodel+"","utf8");
data+="&"+URLEncoder.encode("androidv","utf8")+"="+URLEncoder.encode(androidOS+"","utf8");
URL link=new URL(Main.url+"getquestion.php");
URLConnection connect=link.openConnection();
//send data
connect.setDoOutput(true);
OutputStreamWriter wr=new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine()) != null){
sb.append(line);
}
res=sb.toString();
}catch(Exception e){
res=e.toString();
}
return "";
}
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(res.equals("ok")){
Builder alert = new AlertDialog.Builder(sendques.this);
alert.setTitle("your code: "+pnom+"");
alert.setMessage("your comment recieved!");
alert.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Finish activity
finish();
}
});;
alert.show();
pr.cancel();
}
}
}`
its all of my code for send data and data send by press button
Thank you

Cancelling an AsyncTask can be a pain -
Instead of new sendcomment().cancel(true); try sendcomment.this.cancel(true);
And to test it, know that if AsyncTask is successfully cancelled, onPostExecute() won't run but onCancelled() will run instead, so put something in onCancelled() so you can tell if it's called, and if it is that means the AsyncTask is cancelled.

new sendcomment().cancel(true);
You try to cancel new task.
mySendCommentTask = new sendcomment();
mySendCommentTask.cancel(true);
P.S Don't use AsyncTask.

Try this
// Initialize and execute
sendcomment mySendCommentTask = new sendcomment();
mySendCommentTask.execute();
// and when you need to cancel
mySendCommentTask.cancel(true);

Related

Async Task not getting canceled

I am trying to download file using AsyncTask and also wanted to implement cancel button in progress dialog to cancel the download.
i think the problem is in "doInBackground" method. here is my asynctask:
public class Download_result extends AsyncTask<String,Integer,Void>{
ProgressDialog progressDialog;
Context context;
String pdfFile;
Download_result(Context context, String pdfFile){
this.context=context;
this.pdfFile=pdfFile;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Downloading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(200);
progressDialog.setCancelable(false);
progressDialog.setProgress(0);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Download_result.this.cancel(true); //cancel asynctask here
dialog.dismiss();
}
});
progressDialog.show();
}
#Override
protected Void doInBackground(String... params) {
//given below
}
#Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
progressDialog.cancel();
}
}
"doInBackground" method:
#Override
protected Void doInBackground(String... params) {
String url_1=params[0];
int file_length=0;
try {
URL url = new URL(url_1);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_length=urlConnection.getContentLength();
filesize=file_length;
File sdCard = Environment.getExternalStorageDirectory();
File new_folder = new File (sdCard.getAbsolutePath() + "/xxx");
File input_file = new File(new_folder,pdfFile);
InputStream inputStream = new BufferedInputStream(url.openStream(),8192);
byte[] data=new byte[1024];
int total=0,count=0;
OutputStream outputStream = new FileOutputStream(input_file);
while ((count=inputStream.read(data))!=-1){
total+=count;
outputStream.write(data,0,count);
int progress= (total*200)/file_length;
downloadedsize=total;
publishProgress(progress);
if(isCancelled()){
break; or return null; // same result
}
}
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
try this:
boolean downloadstatus = true;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Downloading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(200);
progressDialog.setCancelable(false);
progressDialog.setProgress(0);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
download.cancel(true);
downloadstatus=false; //add boolean check
dialog.dismiss();
}
});
progressDialog.show();
}
Now in your doInbackGround()
while ((count=inputStream.read(data))!=-1){
if(!your_AsyncTask.isCancelled() || downloadstatus !=false){
total+=count;
outputStream.write(data,0,count);
int progress= (total*200)/file_length;
downloadedsize=total;
publishProgress(progress);
}else{
break;
}
}
This is a reply to my own post(may be in future someone need this):
Actualy my asynctask get cancel, but i didn't know because i thought that when we cancel the asynctask the file should not be there. But actualy when we cancel async task the file is stored but with the smaller size.
eg. Suppose the file is 1mb and i have cancel asynctask while progress dialog shows 50% then only 500kb file is stored, and i thought this is the actual file. sorry for my mistake.
So the logic is when someone press cancel you need to delete the half downloaded file too.
and sorry for my English, it's terrible i know.

How to set progressbar while fetching data from server on click? [duplicate]

This question already has answers here:
Updating progress dialog in Activity from AsyncTask
(2 answers)
How to use AsyncTask to show a ProgressDialog while doing background work in Android? [duplicate]
(2 answers)
Closed 8 years ago.
I want to add progressbar while new activity is not opened.
on next activity I am also fetching data so I want to add a progress bar on next activity also.
Here is my code.
login=(Button)dialog.findViewById(R.id.buttonLogin);
login.setOnClickListener(new OnClickListener() {
#SuppressLint("DefaultLocale")
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(LoginUsername.getText()==null||LoginUsername.getText().toString().equals(""))
{
LoginUsername.setHint("Enter Username");
LoginUsername.setHintTextColor(Color.RED);
}
else if(LoginPassword.getText()==null||LoginPassword.getText().toString().equals("")||LoginPassword.getText().toString().length()<6)
{
LoginPassword.setText("");
LoginPassword.setHint("Enter Password");
LoginPassword.setHintTextColor(Color.RED);
}
else
{
String username=LoginUsername.getText().toString();
String password=LoginPassword.getText().toString();
username1=username.toLowerCase();
// fetch the Password form database for respective user name
//String loginentries=database.getSingleEntry(username1);
//type=database.getType(username1);
try{
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://www.universal-cinemas.com/android/login.php");
JSONObject jobj=new JSONObject();
jobj.put("username",username1);
jobj.put("password", password);
post.setEntity(new StringEntity(jobj.toString()));
Log.i("Info", "Sending request");
HttpResponse res=client.execute(post);
Log.i("Info", "Executed");
InputStream inp=res.getEntity().getContent();
BufferedReader bf = new BufferedReader(new InputStreamReader(inp));
StringBuilder sb= new StringBuilder();
sb.append(bf.readLine()+"\n");
String tmp="0";
while((tmp=bf.readLine())!=null)
{
sb.append(tmp+"\n");
}
String result= sb.toString();
JSONArray jarray=new JSONArray(result);
for(int i=0;i<jarray.length();i++)
{
a=1;
JSONObject job=jarray.getJSONObject(i);
type=job.getString("type");
currency=job.getString("currency");
}
}
catch(Exception e)
{
e.printStackTrace();
}
if(a==1)
{
i=new Intent(getApplicationContext(),User_MainOptions_List.class);
startActivity(i);
finish();
Toast.makeText(getApplicationContext(), "Welcome "+username, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Username and Password is not correct", Toast.LENGTH_SHORT).show();
}
}
}
});
dialog.show();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); // retrieves the windows attributes
lp.dimAmount=0.7f;// sets the dimming amount to zero
dialog.getWindow().setAttributes(lp); // sets the updated windows attributes
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND); // adds the flag to blur bg
}
});
class MyLodingAsycTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
runOnUiThread(new Runnable() {
public void run() {
progressDialog = new ProgressDialog(CameraActivity.this);
progressDialog.setMessage("Loding...");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
#Override
protected Void doInBackground(Void... params) {
//call HTTP service
return null;
}
}
try this
private class MyAsync extends AsyncTask {
ProgressDialog PD;
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = new ProgressDialog(MainActivity.this);
PD.setTitle("Please Wait..");
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
#Override
protected Void doInBackground(Void... params) {
//do what u want
return result;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
PD.dismiss();
}
}
}

Android login not working

Hi Please Can someone help me look at this code? Don't know what am doing wrong,But the try block doesn't run. instead it goes to the catch block.
public void onClick(View arg0) {
//Toast.makeText(getBaseContext(), "connecting",Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
httpclient = new DefaultHttpClient();
htpost = new HttpPost("http://10.0.2.2/fanaticmobile/log_in.php");
uname= username.getText().toString();
pass= password.getText().toString();
try {
namearray = new ArrayList<NameValuePair>();
namearray.add(new BasicNameValuePair("username", uname));
namearray.add(new BasicNameValuePair("password", pass));
htpost.setEntity(new UrlEncodedFormEntity(namearray));
response= httpclient.execute(htpost);
if(response.getStatusLine().getStatusCode()==200){
entity= response.getEntity();
if(entity != null){
InputStream stream = entity.getContent();
JSONObject jresponse = new JSONObject(ConvertInput(stream));
String logged= jresponse.getString("logged");
login_err.setText(""+logged);
if(logged.equals("true")){
Toast.makeText(getBaseContext(), "Successfull",Toast.LENGTH_SHORT).show();
//String retname= jresponse.getString("name");
//String retmail= jresponse.getString("email");
}else if(logged.equals("false")){
String message=jresponse.getString("message");
Toast.makeText(getBaseContext(), message,Toast.LENGTH_SHORT).show();
}
}
}else{
}
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Poor Connection",Toast.LENGTH_SHORT).show();
}
}//
This is the function to read the json object
private static String ConvertInput(InputStream is){
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line ="";
try {
while((line = reader.readLine())!= null){
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
return sb.toString();
}// end of convert function
Please am new to this and i followed a tutorial to this point,but mine is not working. Have set permission(internet) in the manifest file
I have a suggestion Try to Use AsyncHttpclient for getting responses from server no need of this long codes.
http://loopj.com/android-async-http/
AsyncHttpClient asyncHttpClient=new AsyncHttpClient();
RequestParams params=new RequestParams();
params.put("username", uname);
params.put("password", pass);
asyncHttpClient.post("http://10.0.2.2/fanaticmobile/log_in.php", params,new AsyncHttpResponseHandler(){
#Override
public void onFailure(Throwable arg0, String arg1) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
}
#Override
public void onSuccess(String arg0) {
// TODO Auto-generated method stub
super.onSuccess(arg0);
}
});
Just include the jar file in your project it will be simple to use.
Like already been stated in the comments, you're running a network operation in your main thread (the UI thread). This is not only discouraged (lengthy operations should never use the Main Thread), but also forbidden in the case of networking.
response= httpclient.execute(htpost)
^ this fails.
Read how to move that code to an AsyncTask and do it the right way in the official google reference. Googling AsyncTask will help too.
A Pseudo Code version would be:
public class YourTask extends AsyncTask<Void, Void, Void>{
YourListener mListener;
public YourTask(final YourListener listener) {
mListener = listener;
}
#Override
protected Void doInBackground(final Void... params) {
// do your lengthy operation here
return null;
}
#Override
protected void onPostExecute(Void result) {
mListener.onVeryLongTaskDone();
}
public interface YourListener {
public void onVeryLongTaskDone();
}
}
Then make your activity implement that "YourListener" interface and the method onVeryLongTaskDone() will be called.
How do you start the task?
in your onClick method:
(new YourTask(YourActivityName.this)).execute();

Can't cancel doInBackground process in AsyncTask even using cancel method

I have declared instance of FileUploadTask which extends AsyncTask in onCreate() method
FileUploadTask uploadTask= null;
and executes the background method by following code
public class UploadFiles implements OnClickListener{
....
if(SOTCNetStat.chkConnectionStatus(UploadResult.this)){
uploadTask=new FileUploadTask();
uploadTask.execute("");
}
else
{
Toast.makeText(UploadResult.this, getResources().getString(R.string.Text_CheckNetworkConnections) , Toast.LENGTH_LONG).show();
}
....
}
Having a cancel button to cancel the background process
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d(TAG,"cancel button clicked.....");
//FileUploadTask uploadTask= new FileUploadTask();
if(uploadTask!=null)
{
Log.d(TAG,"click event null checking....");
uploadTask.cancel(true);
}
}
}
In FileUploadTask class declared a boolean to check the running status
public class FileUploadTask extends AsyncTask<String, Integer, String> {
....
boolean isRunning=true;
The doInBackground method
#Override
protected String doInBackground(String... arg0) {
for(int i=0; i<fp.size(); i++){
index = i+1;
if(isCancelled() && !isRunning)
{
Log.d(TAG,"Cancel 1 Condition Checked ["+i+"]");
Log.d(TAG,"doInBackground canceled");
break;
}
else
{
Log.d(TAG,"Cancel 1 Canceled ["+i+"]");
}
file1 = new File(fp.get(i));
String urlString = Constants.UPLOAD_URL;
try {
Log.e("doInBackground", "urlString: " + urlString);
Log.e("doInBackground", "domainPref: " + domainName);
urlString = urlString.replace("domain", URLEncoder.encode(domainName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
ProgressMultipart reqEntity = new ProgressMultipart(new ProgressListener() {
#Override
public void transferred(long num) {
//publishProgress((int) ((num / (float) file1.length() ) * 100));
publishProgress((int) ((num / (float) totalSize ) * 100));
}
});
reqEntity.addPart("userfile", bin1);
if(getIntent().hasExtra("show_id"))
{
//String showId = getIntent().getStringExtra("show_id");
reqEntity.addPart("mobileshow", new StringBody("1"));
reqEntity.addPart("show_ids", new StringBody(getIntent().getStringExtra("show_id")));
}
reqEntity.addPart("Filename", new StringBody(file1.getName()));
reqEntity.addPart("user_id", new StringBody("2"));
reqEntity.addPart("privateasset", new StringBody("true"));
reqEntity.addPart("uploadtype", new StringBody("Normal"));
reqEntity.addPart("version_num", new StringBody("1"));
totalSize = reqEntity.getContentLength();
post.setEntity(reqEntity);
System.err.println("post :"+post.toString());
//to be check the cancel operation
if(isCancelled() && !isRunning)
{
Log.d(TAG,"Cancel 2 Condition Checked ["+i+"]");
Log.d(TAG,"File Uploading Cancelled in doInBackground method");
break;
}
else
{
Log.d(TAG,"Cancel 2 Canceled ["+i+"]");
}
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
response_str = EntityUtils.toString(resEntity);
}
....
return response_str;
}
and overloaded onCancelled methods
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
Log.d(TAG,"onCancelled() method called");
super.onCancelled();
}
#Override
protected void onCancelled(String result) {
// TODO Auto-generated method stub
Log.d(TAG,"onCancelled(String) method called");
isRunning=false;
this.cancel(true);
}
I tried a lot and explored . Even using cancel method I can't able to stop the uploading process in background. Please any one give solutions to the problem
Some links i referred
http://www.technotalkative.com/cancel-asynctask-in-android/
http://developer.android.com/reference/android/os/AsyncTask.html
You seem to be missing how AsyncTask works. The onCancelled() method will only be called after doInBackground() is finished, similar to the onPostExecute() method. It is not called immediately after uploadTask.cancel(true) is called as you think it will be. The way you are using it, you have no need for onCancelled() methods or an isRunning variable (currently in your code isRunning is never changed to false and thus your isCancelled() check never works). Remove both the onCancelled() methods and the isRunning variable and your AsyncTask will work.
check this, after canceling the asynctask write this condition.
if(asynctask.iscancel()){
break;
}
it may help for u. :)
http://developer.android.com/reference/android/os/AsyncTask.html

refresh content of Activity or add refresh button

As I can refresh the content of an activity?, for example, I have a menu and a button send me an application content that displays information online, but to go back and return again, the information is not updated.
This is my Activity.
public class Bovalpo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bovalpo);
Button buttonExit = (Button)this.findViewById(R.id.cerrar);
buttonExit.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
System.exit(0);
}
}
);
TextView myListView = (TextView) findViewById(R.id.tv);
try {
myListView.setText(getPage());
if(getPage().contains("Abierto")){
myListView.setTextColor(Color.parseColor("#008000"));
}else{
myListView.setTextColor(Color.parseColor("#FF0000"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getPage() throws MalformedURLException, IOException {
HttpURLConnection con = (HttpURLConnection) new URL("http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=1").openConnection();
con.connect();
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
return inputStreamToString(con.getInputStream());
} else {
return null;
}
}
private String inputStreamToString(InputStream in) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append("Mercado: " + line + "\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
public void lanzar(View view){
Intent i = new Intent(this, xml7009.class);
startActivity(i);
}
public void lanzar3(View view){
Intent i = new Intent(this, tabla7009.class);
startActivity(i);
}
public void lanzar4(View view){
Intent i = new Intent(this, xml6503.class);
startActivity(i);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
}
put your code here
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// make your work to data bind
}
The code that fetches your data and sets list view color should be put in onResume() instead of onCreate if you want it to run each time your Activity is shown.
Simply you can put your update code in the onResume() method of the activity. OnResume() method will be called when ever you return from the other activity.
But onResume() method is often called when your activity is resume for example. If you open and dismiss the dialog then your activity will be Resume. SO if you are calling some network call in onResume then it will consume the process and Network speed.
The alternate solution is use startActivityForResult() method to receive the result from the next activity and bases of the activity result you can call your web API or any work. You can get the result of the next activity in onActivityResult() method.
But before using the startActivityForResult method ensure that the next activity will set the result by calling setResult() method.
If you want to update your data every time you came to activity, you need to set your updated values in onResume
like below
#Override
protected void onResume() {
super.onResume();
try {
myListView.setText(getPage());
if(getPage().contains("Abierto")){
myListView.setTextColor(Color.parseColor("#008000"));
}else{
myListView.setTextColor(Color.parseColor("#FF0000"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Categories