Android AsyncTask runs multiple times - java

In my app ,there is an one button which get input from database.When I press it more than one in a short time it crashes.
How can i avoid this error with using asynctask?
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showinf();
}
});
}
private String[] columns={"name","surname"};
private void showinf(){
SQLiteDatabase db=v1.getReadableDatabase();
Cursor c=db.query("infos",columns,null,null, null,null,null);
Random mn2=new Random();
int count=c.getCount();
String mn=String.valueOf(count);
int i1=mn2.nextInt(count+1);
c.move(i1);
t1.setText(c.getString(c.getColumnIndex("name")));
t2.setText(c.getString(c.getColumnIndex("surname")));
}
thanks...

You can create a boolean flag (let's say bDiscardButtonAction), and set it to true in onPreExecute() and set it to false in onPostExecute(), something like:
public class FooTask extends AsyncTask<Foo, Foo, Foo>
{
private static boolean bDiscardButtonAction = false;
private boolean isDiscareded = false;
#Override
public void onPreExecute()
{
if(bDiscardButtonAction)
{
isDiscareded = true;
return;
}
bDiscardButtonAction = true;
}
#Override
public Foo doInBackground(Foo... params)
{
if(isDiscareded) return;
// ...
}
#Override
public void onPostExecute(Void result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
#Override
public void onCancelled(Foo result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
}

disable the show button in onPreExecute() and enable it back onPostExecute().
public class getAsyncDataTask extends AsyncTask<Void, Void, Void>
{
#Override
public void onPreExecute()
{
show.setAlpha(0.5);
show.setEnable(false);
}
#Override
public void doInBackground(Void... params)
{
//retrieve the data from db;
}
#Override
public void onPostExecute()
{
show.setAlpha(1.0);
show.setEnable(true);
}
}

I hope this code will help u out.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
new AsynchTaskManualLocation().execute();
});
public class AsynchTaskGetData extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... url) {
//showinf(); this method contains operation of getting data from //database OR ur logic to getdata
return showinf();
}
#Override
protected void onPostExecute(String result) {
//here u get result in resul var and process the result here
}
}
}

Related

set void to AsyncTask and execute it after doInBackground finishes

I'm trying to use AsyncTask to make HTTP GET requests in Android Studio. This AsyncTask class is used across many activities of the app. I want to assign a void function to the AsyncTask which will execute after the doInBackground has fetched the HTTP GET request. The HTTP returned response should be inserted into the void's parameter. I have researched a lot of times but cannot find a simple working solution. Need Help. Thanks.
Main.java containing the AsyncTask class:
package com.example.NAME;
import android.os.AsyncTask;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static class GetData extends AsyncTask<String, Void, Boolean> {
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
Boolean _return = false;
try {
String data = params[0];
// DO THE HTTP GET REQUEST AND EVALUATE THE BOOLEAN RETURN VALUE
_return = ???;
} catch (Exception e) {
e.printStackTrace();
}
return _return;
}
#Override
protected void onPostExecute(Boolean _return) {
super.onPostExecute(_return);
}
}
}
Activity1.java using the AsyncTask class:
package com.example.NAME;
import android.app.Activity;
import android.os.Bundle;
public class Activity1 extends Activity {
private final Main main = new Main();
#Override
protected synchronized void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity1);
}
public synchronized void GET_Request(View v) {
Main.GetData t = new Main.GetData();
t.execute("STRING");
/*
How to attach the `after_GET_Request` void that should be executed
after the HTTP GET Request happens and should receive the returned
Boolean value.
*/
}
public synchronized void after_GET_Request(Boolean b) {
// Use the Boolean data received from AsyncTask.
}
}
Add a result callback to your AsyncTask and process the outcome:
public static class GetData extends AsyncTask<String, Void, Boolean> {
private ResultCallback mCallback;
public GetData(ResultCallback callback) {
mCallback = callback;
}
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
Boolean _return = false;
try {
String data = params[0];
// DO THE HTTP GET REQUEST AND EVALUATE THE BOOLEAN RETURN VALUE
_return = ???;
} catch (Exception e) {
e.printStackTrace();
}
return _return;
}
#Override
protected void onPostExecute(Boolean _return) {
super.onPostExecute(_return);
mCallback.onResultReady(_return);
}
public interface ResultCallback {
void onResultReady(Boolean result);
}
}
And then in your activity call your function:
Main.GetData t = new Main.GetData(new ResultCallback() {
#Override
public void onResultReady(Boolean result) {
after_GET_Request(result);
}
});
t.execute("STRING");

Running two classes at the same time in android studio

The way that I have my current application set up is that when you press the button then the app displays a counter on the bottom that goes up to ten then stops and then it displays a counter on the top that goes from 10 to 0. However, what I need to do is make these counters happen at the same time. I tried using threads but I think that I must not have been doing it right. Any help would be appreciated.
edit: I want to run mytask and mytask1 at the same time, they currently run after each other
edit2: I was asked for the code for publish progress
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
Code:
public class MainActivity extends AppCompatActivity {
Button btn;
TextView txt;
Integer count =1;
Integer count1 =10;
TextView txt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//p
//p
btn = (Button) findViewById(R.id.button);
btn.setText("Start");
txt = (TextView) findViewById(R.id.textView);
txt1 = (TextView) findViewById(R.id.textView2);
View.OnClickListener listener = new View.OnClickListener(){
public void onClick(View view){
count =1;
//p
//p
switch (view.getId()){
case R.id.button:
new MyTask().execute(10);
new MyTask1().execute(0);
break;
}
}
};
btn.setOnClickListener(listener);
}
class MyTask extends AsyncTask<Integer, Integer, String> {
#Override
protected String doInBackground(Integer... params) {
for (; count <= params[0]; count++) {
try {
Thread.sleep(1000);
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task Completed.";
}
#Override
protected void onPostExecute(String result) {
txt.setText(result);
btn.setText("Restart");
}
#Override
protected void onPreExecute() {
txt.setText("Task Starting...");
}
#Override
protected void onProgressUpdate(Integer... values) {
txt.setText("BackGround Task Running..."+ values[0]);
}
}
class MyTask1 extends AsyncTask<Integer, Integer, String> {
#Override
protected String doInBackground(Integer... params) {
for (; count1 >= params[0]; count1--) {
try {
Thread.sleep(1000);
publishProgress(count1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task Completed.";
}
#Override
protected void onPostExecute(String result) {
txt1.setText(result);
btn.setText("Restart");
}
#Override
protected void onPreExecute() {
txt1.setText("Task Starting...");
}
#Override
protected void onProgressUpdate(Integer... values) {
txt1.setText("Countdown "+ values[0]);
}
}
}
AsyncTasks are executed on a single thread according to documentation, so that might be the issue.

strange java.lang.NullPointerException at onPostExecute

Who can help me with this strange error?
I marked the line when I get the error.
Thanks
/************************************************
* setItemsAsReadTask
************************************************/
private class SetItemsAsReadTask extends AsyncTask<ArrayList<FeedItem>, Void, Void> {
#Override
protected void onPreExecute() {
//AGGIORNO LISTVIEW SUBSCRIPTIONS
}
#Override
protected Void doInBackground(ArrayList<FeedItem> ... articoli) {
if(this.isCancelled()==false){
if(articoli.length!=0){
ArrayList<FeedItem> segnaComeLetti = articoli[0];
reader.setMultipleNewsAsRead(segnaComeLetti);
}
}
return null;
}
#Override
protected void onPostExecute(Void v) {
//TODO TRUE O FALSE
if(this.isCancelled()==false){
Log.d(TAG, "chiedo aggiornamento updateUI");
mCallbacks.onSubscriptionsUpdated();
}<---- that's the line of the error
}
}
**UPDATE
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (Callbacks)activity;
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
Your mCallbacks variable is probably null. Use defensive programming and check for null before calling the method. Also, instead of checking if a boolean value is false, just use the not ! logical operator.
#Override
protected void onPostExecute(Void v) {
if (!this.isCancelled()){
Log.d(TAG, "chiedo aggiornamento updateUI");
if (mCallbacks != null) {
mCallbacks.onSubscriptionsUpdated();
}
}
}

Android Interface class from another class show null pointer exception

public class MainActivity extends Activity Implements ICallInterface {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onTaskCompleted(Boolean result) {
if (result) {
Log.d(TAG, "1111111111111 11111111111 True condition ");
} else {
Log.d(TAG, "22222222222222222222 False condition ");
}
}
public interface ICallInterface {
void onTaskCompleted(Boolean result);
}
public class AsycData extends AsyncTask<String, Void, Void> {
ICallInterface mCallInterface;
// AsyncTask Data
// AsyncTask onPost
#Override
protected void onPostExecute(Void result) {
// call interface, set true value & call first activity.
mCallInterface.onTaskCompleted(true);
}
}
Getting null pointer exception at time of call.
I know something went wrong with my AsycData declaration but couldn't find ans.
Any who could help me .
I have modified your code, now it working and in log printing true value. Now what you want to do you can do with code. if it's work for you then please give up votes.
public class MainActivity extends Activity implements ICallInterface {
SecondClass second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// second.execute();
second = new SecondClass(this);
second.execute();
}
/*
*
* #Override public void onTaskCompleted(Boolean result) { // TODO
* Auto-generated method stub if (result) {
* Log.d("tag","1111111111111 11111111111 True condition ");
* System.out.println(result); // System.out.println(str);
* Toast.makeText(getApplicationContext(), " "+result,
* Toast.LENGTH_LONG).show();
*
*
* } else { Log.d("tag","22222222222222222222 False condition "); }
*
* }
*/
#Override
public void onTaskCompleted(String result) {
// TODO Auto-generated method stub
System.out.println(result);
// System.out.println(str);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
}
}
public class SecondClass extends AsyncTask<String, String, String> {
ICallInterface mCallInterface;
public SecondClass(ICallInterface mcaCallInterface) {
// TODO Auto-generated constructor stub
this.mCallInterface = mcaCallInterface;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String str = "Hello";
return str;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
mCallInterface.onTaskCompleted(result);
super.onPostExecute(result);
}
}
public interface ICallInterface {
void onTaskCompleted(String result);
}
I have modified your code, now it woking and in log printing true value. Now what you want to do you can do with code. if it's work for you then please give up votes.
public class MainActivity extends Activity implements ICallInterface {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsycData(MainActivity.this).execute();
}
#Override
public void onTaskCompleted(Boolean result) {
if (result) {
Log.d("TAG", "1111111111111 11111111111 True condition ");
} else {
Log.d("TAG", "22222222222222222222 False condition ");
}
}
}
interface ICallInterface {
void onTaskCompleted(Boolean result);
}
class AsycData extends AsyncTask<String, Void, Void> {
Activity activity;
public AsycData(MainActivity activity) {
this.activity = activity;
}
#Override
protected void onPostExecute(Void result) {
((ICallInterface) activity).onTaskCompleted(true);
}
#Override
protected Void doInBackground(String... arg0) {
return null;
}
}
mCallInterface is not initiated. Initialize it before using

I can't initialize component in asynctask background function

How would I call this function in asynctask?
void somefunc()
{
tr1 = (TableRow) new TableRow(this);
//error
txt1=new TextView(this);
txt9.setText(strinarr[0]);
tr1.addView(txt1);
tl.addView(tr1,new TableLayout.LayoutParams(layoutParams));
}
class SaveAdDetail extends AsyncTask<Void, String, Void>
{
#Override
public void onPreExecute()
{
super.onPreExecute();
Progdialog = ProgressDialog.show(demotable.this, "", "Please Wait...", true);
Progdialog.show();
}
#Override
public Void doInBackground(Void... unused)
{
try
{somefunc();}
catch (Exception e)
{strdata="Error";}
return null;
}
#Override
public void onPostExecute(Void unused)
{
Progdialog.dismiss();
if(strdata.equals("Error"))
{Toast(strdata);}
else
{
Toast("asdasdasd");
}
}
}
You have a choice : use handlers or call directly. In both cases you should pass a reference to the constructor of AsyncTask. onPostExecute() is called on the UI thread, so you can call the method directly on the reference of your activity.
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.TASK_FINISHED:
somefunc();
break;
}
}
};
SaveAdDetail task = new SaveAdDetail(handler);
task.execute();
// in your SaveAdDetail:
#Override
public void onPostExecute(Void unused) {
Progdialog.dismiss();
handler.obtainMessage(Constants.TASK_FINISHED).sendToTarget();
}
I would use a Handler. Here is an example: http://developer.android.com/resources/articles/timed-ui-updates.html

Categories