Unable to cancel async task execution - java

Am getting exception when the user continuously clicking the button on which am calling the async task.
So is there any way to cancel the execution of first async task execution on second time pressing the button.
I hope u understand the problem.
The codes am using is given below.
On button click am using the following code
GetData obj= new GetData();
String urls="http://pathramonline.com/?cat=46";
obj.execute(urls);
My async task
public class GetData extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
BufferedReader reader =null;
String data =null;
try{
HttpClient client = new DefaultHttpClient();
URI uri=new URI(params[0]);
HttpGet get =new HttpGet(uri);
HttpResponse response= client.execute(get);
InputStream stream=response.getEntity().getContent();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer =new StringBuffer("");
String line="";
String newLine= System.getProperty("line.separator");
while((line=reader.readLine())!=null){
buffer.append(line+newLine);
}
reader.close();
data = buffer.toString();
return data;
}
catch(URISyntaxException e){
e.printStackTrace();
}
catch(ClientProtocolException f){
f.printStackTrace();
}
catch(IOException g){
g.printStackTrace();
}
catch(Exception e)
{
//
}
finally{
if(reader!=null){
try{
reader.close();
}
catch(Exception e){
}
}
}
return null;
}
#Override
protected void onCancelled() {
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//TextView t3=(TextView)findViewById(R.id.textView3);
if(result==null)
{
Intent home = new Intent(MainActivity.this,NoConnection.class);
MainActivity.this.startActivity(home);
MainActivity.this.finish();
}
//Some actions
}
}

I would suggest another method instead of cancelling the asynctask.
In your onPreExecute() method disable the button click
button.setEnabled(false);
And in onPostExecute() method enable back the button
button.setEnabled(true);
If you explicitly want to know that button is disabled then while the asynctask is being executed you can change the background color of the button to another color or background, so that the user will know that some function is being carried out and he needs to wait..
Another approach is
new AsyncTask<Void, Void, Void>() {
String result = "";
ProgressDialog progressDialog = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading , Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "your link comes here"
JSONObject jsonObject = jpass.getJSONFromUrl(url);
try {
//do your work here
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void a) {
// TODO Auto-generated method stub
progressDialog.dismiss();
if (result.equals("success")) {
//on success do some work here
}
else
{
//on failure do some work here
}
super.onPostExecute(a);
}
}.execute();

Instead of cancelling the AsyncTask just set your button's click listener to null and then again set it inside onPostExecute of your AsyncTask. It would be even better if you display a ProgressBar when your doInBackground() code is executing.

Related

How can i use two web service methods in the same activity?

I have two methods which are from soap webservice. I am calling them in asyntask that is a superclass of info.java page and tring to get the results in onPost method of asyntask. The calling code of info.java/onCreate is below.
try{
PropertyInfo propertyInfo1 = new PropertyInfo();
properties.clear();
propertyInfo1 = new PropertyInfo();
propertyInfo1.setName("Module_id");
propertyInfo1.setType(String.class);
propertyInfo1.setValue(Utils.selectedModule_id);
properties.add(propertyInfo1);
new Info.AsyncTaskService().execute(new ServiceParams("GetInfo", properties), new ServiceParams("GetInfo_Photo", properties));
} catch (Exception e) {
Toast.makeText(Info.this, "Please check your internet connection.", Toast.LENGTH_LONG);
}
Both of the service methods takes the same properties thats why i gave them same properties. My problem is i can't take the results because i know that it needs to call these two methods in different threads with an order but i don't know how to do it. Could you help me please? The codes of asynctask class is also below thank you.
public class AsyncTaskService extends AsyncTask<ServiceParams, Void, Void> {
String resp = "";
String resp2 = "";
ProgressDialog progressDialog;
#Override
protected Void doInBackground(ServiceParams... params) {
resp = WebService.invoke(params[0].properties, params[0].methodName);
resp2 = WebService.invoke(params[1].properties, params[1].methodName);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.w("WEBSERVICE RESPONSE===", resp);
Log.w("WEBSERVICE RESPONSE===", resp2);
try {
JSONArray ja = new JSONArray(resp);
Utils.subMenuArrayList.clear();
Info_Item info_item=new Info_Item(ja.getJSONObject(0));
((TextView)findViewById(R.id.txtInfo)).setText(info_item.getInfo());
((TextView)findViewById(R.id.txtModule)).setText(Utils.selectedMenuName);
} catch (JSONException e) {
e.printStackTrace();
}
if (progressDialog != null)
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(Info.this);
if (progressDialog != null) {
progressDialog.setCancelable(false);
progressDialog.setMessage("İşlem yapılıyor ...");
progressDialog.show();
}
}
protected void onProgressUpdate(Integer... progress) {
if (progressDialog != null)
progressDialog.setProgress(progress[0]);
}
}
I have found how to do it! Wanted to share with you too.
First of all describe you async tasks as below. I have two methods which i want to use in one activity at the same time(paralel) so i described two async task classes.
public class FirstAsyncTask extends AsyncTask<ServiceParams, Void, Void> {
String resp = "";
ProgressDialog progressDialog;
#Override
protected Void doInBackground(ServiceParams... params) {
resp = WebService.invoke(params[0].properties, params[0].methodName);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.w("WEBSERVICE RESPONSE===", resp);
try {
JSONArray ja = new JSONArray(resp);
Utils.subMenuArrayList.clear();
Info_Item info_item=new Info_Item(ja.getJSONObject(0));
((TextView)findViewById(R.id.txtInfo)).setText(info_item.getInfo());
((TextView)findViewById(R.id.txtModule)).setText(Utils.selectedMenuName);
} catch (JSONException e) {
e.printStackTrace();
}
if (progressDialog != null)
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(Info.this);
if (progressDialog != null) {
progressDialog.setCancelable(false);
progressDialog.setMessage("İşlem yapılıyor ...");
progressDialog.show();
}
}
protected void onProgressUpdate(Integer... progress) {
if (progressDialog != null)
progressDialog.setProgress(progress[0]);
}
}
Then you should call the tasks like this with executeOnExecuter in your activity's onCreate method. I used a property array here to hold the parameters i am going to send to web service method and describe a serviceparameter with properties and method name and send them in executeOnExecuter() method. I used same properties for my both web service methods but you can describe an other property array like this "private ArrayList properties = new ArrayList<>();" and add informations you need for parameters you will send to web service method.
try{
PropertyInfo propertyInfo1 = new PropertyInfo();
properties.clear();
propertyInfo1 = new PropertyInfo();
propertyInfo1.setName("Module_id");
propertyInfo1.setType(String.class);
propertyInfo1.setValue(Utils.selectedModule_id);
properties.add(propertyInfo1);
ServiceParams serviceparams=new ServiceParams("GetInfo", properties);
ServiceParams serviceparams2=new ServiceParams("GetInfo_Photo", properties);
FirstAsyncTask asyncTask = new FirstAsyncTask(); // First
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serviceparams);
SecondAsyncTask asyncTask2 = new SecondAsyncTask(); // Second
asyncTask2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serviceparams2);
} catch (Exception e) {
Toast.makeText(Info.this, "Please check your internet connection.", Toast.LENGTH_LONG);
}

onPostExecute is not called

So I am having issues with my AsyncTask. I need postExecute to display an alert dialog if a certain error throwable is caught in doInBackground. The problem is that postExecute is never called. I have tried adding #Override but Android Studio says that it isn't overriding a method in its super class. I have also tried changing the return type. I looked around this site and couldn't find an answer. Thanks in advance.
AsyncTask Class
public class AsyncTaskActivity extends AsyncTask<Void, Void, Void> {
String exception;
#Override
protected void onPreExecute() {
}
protected void onPostExecute() {
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
#Override
protected Void doInBackground(Void... params) {
try {
Log.i("AsyncTask", "Loading...");
// Make a URL to the web page. This takes the string representation of the URL
// and changes it into a URL object
URL url = new URL("http://api.wunderground.com/api/0c0fcc3bf62ab910/conditions/q/IN/Fort_Wayne.json");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
// read each line and write to text file
while ((line = br.readLine()) != null) {
Log.i("AsyncTask", line);
TextEditor.file = new File(MainActivity.path, "siteInfo.txt");
TextEditor.writeString(line);
}
TextEditor.saveAndClose();
} catch (Exception e) {
e.printStackTrace();
exception = e.toString();
}
Log.i("AsyncTask", "DONE");
return null;
}
}
showDialog method
public static void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.context);
builder.setView(R.layout.dialog_layout);
builder.setPositiveButton(
R.string.dialog_close,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(1);
}
});
builder.show();
}
look like you're missing something
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
First please refer this documentation. you have missed parameters on onPostExecute().
https://developer.android.com/reference/android/os/AsyncTask.html
What you would have to do is,
#Override
protected void onPostExecute(Params) {
// your logics
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
Please note that you need to initialize exception, otherwise it may cause a NullPointerException

ProgressDialog not dismissed in AsyncTask

i have an issue with an AsyncTask. I have an Activity with three CheckBox that if checked launch the async task when the user press the button. My async is this
private class MyTask extends AsyncTask<Void, Void, Void> {
String valore
public MyTask(String valore) {
this.valore = valore;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage(getString(R.string.message));
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Exec some operations
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(risultato != null) {
textView.append(risultato);
}
if(errori != null) {
textView.append(errori);
}
progressDialog.dismiss();
}
}
And the button
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(checkBox.isChecked()) {
new MyTask("string").execute();
}
if(checkBox2.isChecked()) {
new MyTask("string2").execute();
}
if(checkBox3.isChecked()) {
new MyTask("string3").execute();
}
}
});
The problem is that if two or three checkbox are checked the ProgressDialog is not dismissed and remain on the screen. Why? How can i dismiss it also when two or more checkbox are checked?
try {
if ((pDialog != null) && pDialog.isShowing()) {
pDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
pDialog = null;
}
Try dismissing the dialog like this It might solve your problem
There are problem in this code
public void onClick(View v) {
// TODO Auto-generated method stub
if(checkBox.isChecked()) {
new MyTask("string").execute();
}
if(checkBox2.isChecked()) {
new MyTask("string2").execute();
}
if(checkBox3.isChecked()) {
new MyTask("string3").execute();
}
}
this is besically a logical error if we dry run this code it will
execute as many time as number of checked checkbox increases .
Suppose you do the checkbox1 to checked it will execute the async 1 time
while when you click checkbox2 it will execute checkbox1 async as well as checkbox2 async
and it be so on so change the condition on the button onclicklistner
Hi Since you are creating a new progressDialog every time therefore it is not getting dismissed. Create only one and keep variable at common place . For example
#Override
protected void onPreExecute() {
super.onPreExecute();
if(progressDialog!=null){
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage(getString(R.string.message));
progressDialog.setIndeterminate(true);
progressDialog.show();
}
}
What are you doing in "doInBackground" method please write that code as well.
And what is "risultato" and "errori" refer to.

Android - asynctask don't show image when a use get(time)

I try to do app which show elements. Each element should start showing when the before element was hidden. Each element is showing 2 seconds. I try a lot of way:
Android/java - How to do that loop wait to do action
And now I try with Asynctask. I find a way:
public class MainActivity extends Activity
{
ImageView image1,image2;
int id = 0;
AsyncTask.Status status;
TextView txt;
String status1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LongOperation task = new LongOperation();
status = task.getStatus();
status1 = String.valueOf(status);
txt = (TextView) findViewById(R.id.txt);
image1 = (ImageView)findViewById(R.id.image1);
image2 = (ImageView)findViewById(R.id.image2);
do{
new LongOperation().execute("");
id=id+1;
txt.setText(status1);
try
{
try
{
task.get(2500, TimeUnit.MILLISECONDS);
} catch (TimeoutException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}while(id<3);
}
private class LongOperation extends AsyncTask<String, Void, String>
{
#Override
protected void onPreExecute()
{
image1.setVisibility(View.VISIBLE);
image2.setVisibility(View.VISIBLE);
txt.setText(status1);
}
#Override
protected String doInBackground(String... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.interrupted();
}
return null;
}
#Override
protected void onPostExecute(String result) {
txt.setText("Executed");
image1.setVisibility(View.GONE);
image2.setVisibility(View.GONE);
}
#Override
protected void onProgressUpdate(Void... values) {}
}
(This is a example). App run and end after 7.5 sec (everything ok) but images aren't shown when I start. What should I do?
I think you are creating a deadlock situation with your threads. The main UI thread is blocking at the line task.get(), which in turn is preventing the AsyncTask from running properly; its onPreExecute method is posted onto the UI Thread, and the doInBackground doesn't run until onPreExecute completes.

android.os.NetworkOnMainThreadException into AsyncTask

I have the following class:
class CargaImgsParaAmpliar extends AsyncTask<Void, Void, Bitmap> {
final ProgressDialog progressDialog = new ProgressDialog(imagen.this);
protected void onPreExecute() {
progressDialog.setTitle("");
progressDialog.setMessage("Cargando Imagen...");
progressDialog.show();
}
protected Bitmap doInBackground(Void... params) {
Bitmap mIcon1 = null;
URL url_value;
try {
url_value = new URL(StrUrl);
mIcon1 = BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mIcon1;
}
protected void onPostExecute(Bitmap imagen) {
m_imageView.setImageBitmap(urlImageToBitmap(StrUrl));
progressDialog.dismiss();
}
}
I am doing internet discharge processes within AsyncTask and it still gives me the exception android.os.NetworkOnMainThreadException.
How can I fix this isse?
It seems to me that urlImageToBitmap accesses the network but is executed from onPostExecute (which is run on the UI task).
And you don't seem to be doing anything with imagen parameter in onPostExecute. So the image retrieved in doInBackground is basically lost.

Categories

Resources