MainActivity execute external asynctask class
Here my code
public class MainActivity extends AppCompatActivity implements View.OnClickListener
...
public void onFirstBtnClick()
{
AysncClass ac = new AyncClass();
ac.execute();
}
and external asynctask
public class AysncClass extends AsyncTask<String, String, Integer>
#Override
protected Integer doInBackground(String... strings) {
Method1(strings[0], Integer.parseInt(strings[1]));
return null;
}
public Method1(Strins s, int i)
{
onProgressUpdate("first start");
publishProgress();
// do more work
onProgressUpdate("second start");
publishProgress();
}
public void Method2()
{
onProgressUpdate("Method2 here");
publishProgress();
}
...
#Override
protected void onProgressUpdate(final String... values) {
super.onProgressUpdate(values);
// what can i do here?
}
}
I use runOnUiThread like this in onProgressUpdate
((MainActivity)context).runOnUiThread(new Runnable()
{
#Override
public void run()
{
((MainActivity)context).tvRead.append(values[0]);
}
});*
but It occur 'java.lang.ArrayIndexOutOfBoundsException: length=0; index=0' even though values[0] is not null.
Also I use interface
this.context.WriteText(values[0]);
It occur same error
And I do this...
((MainActivity)context).tvRead.append(values[0]);
It occur 'java.lang.RuntimeException: An error occured while executing doInBackground()' and 'CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.'
...How can I resolve?
Do not call onProgressUpdate(). Instead just call publishProgress("The String").
By calling publishProgress without a parameter you will have no values in onProgressUpdate. That's why you get an IndexOutOfBondException.
Don't call onProgressUpdate on your own.
Call publishProgress("My Message");
In onProgressUpdate, don't use runOnUIThread.
OnProgressUpdate runs on the Ui thread only.
Instead of this
onProgressUpdate("Method2 here");
publishProgress();
Do this
publishProgress("Method2 here");
On ProgressUpdate will be in UIThread, no need again specify in UI thread. From DoInbackGround you have to make call publishProgress method for invoking OnProgressUpdate.
Use an interface as communicator between your Activity and AsyncTask
Create Interface
interface MyInterface {
void callActivityUi(String progress); // use float maybe
}
Initialize AsyncTask like this:
AysncClass as = new AysncClass(new MyInterface() {
#Override
void callActivityUi (String progress) {
// you will receive data here
}
});
Create a constructor in your AysncClass
private MyInterface myInterface;
public AysncClass (MyInterface myInterface) {
this.myInterface = myInterface;
}
Call Activity in onProgressUpdate(String... values)
myInterface.callActivityUi(values[0]);
Based on your code, you can use an interface to post the progress to the activity. I modified your code like this:
AsyncTask class
public class AysncClass extends AsyncTask<String, String, Integer> {
public interface SomeListener {
public void onSomething(Object mObject);
}
private SomeListener sl;
public AysncClass(SomeListener sl) {
this.sl = sl;
}
#Override
protected Integer doInBackground(String... strings) {
Method1(strings[0], Integer.parseInt(strings[1]));
return null;
}
public Method1(Strins s, int i) {
onProgressUpdate("first start");
publishProgress();
// do more work
onProgressUpdate("second start");
publishProgress();
}
public void Method2() {
onProgressUpdate("Method2 here");
publishProgress();
}
...
#Override
protected void onProgressUpdate(final String... values) {
super.onProgressUpdate(values);
// what can i do here?
sl.onSomething(mObject);
}
}
MainActivity class
public class MainActivity extends AppCompatActivity implements View.OnClickListener,
AysncClass.SomeListener {
...
public void onFirstBtnClick() {
AysncClass ac = new AyncClass(this);
ac.execute();
}
#Override
public void onSomething(Object mObject) {
//Do your UI work here
}
}
Related
Here is my problem. I have created a asyncTask to link to my database and send and receive information using JSON.
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
returnValues = dataParsed.split("\\s+");
mainActivity.getValue(this is the function that calls anotherfunction in
asyncTask)
Log.v("ARRAY LENGTH", String.valueOf(returnValues.length));
}
public String[] returnmyString(){
//return mySaveData;
Log.v("ARRAY LENGTH 2", String.valueOf(returnValues.length));
return returnValues;
}
I create the asyncTask object within my activity based class and then call that object.execute. My problem is that my code will continue to run once calling the object.execute and one of the lines calls a function within the asyncTask class before it is done executing all the code.
process.activitySave(1); //<---Process is the object for the asyncTask class
process.ContextSave(this,ServerURLSource,myParameters);
process.execute()
changedData = process.returnmyString(); //<-- this is the line of code that gets implemented that returns a null value
I have tried creating a Mainactivity object in the asyncTask class and then calling a function then that retrieves the value but my app crashes when I do this. any help would be appreciated. I would like to put some sort of listener in the mainactivity class as it seems I cannot reference any of the functions from my mainactivity class in my asyncTask class.
This is the function within the asyncTask to return the value:
public String[] returnmyString(){
//return mySaveData;
Log.v("ARRAY LENGTH", String.valueOf(returnValues.length));
return returnValues;
}
Method 1 is the basic, anonymous inner class implementation. Because of the inner AsyncTask class is not static class, you can access to the CustomActivity's properties from that implementation.
In Method 2, AsyncClass implemented separately. If you gave your activity to this class, it can be call back your desired method after execution. This method, for our example is the #setChangedData method. CustomAsyncTask call backs the #setChangedData in the #onPostExecute.
public class CustomActivity extends AppCompatActivity {
String mChangedData;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Method 1 - change data into the anonymously implemented AsyncTask class
new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
CustomActivity.this.mChangedData = "foo"; // this changes mChangedData as "foo"
}
}.execute(1);
// Method 2 - change data into the custom AsyncTask class
new CustomAsyncTask(this).execute(2);
}
public void setChangedData(String changedData){
this.mChangedData = changedData;
}
static class CustomAsyncTask extends AsyncTask<Integer, Void, Void> {
CustomActivity mActivity;
public CustomAsyncTask(CustomActivity activity) {
this.mActivity = activity;
}
#Override
protected Void doInBackground(Integer... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mActivity.setChangedData("bar");
}
}
}
And, as method 3, if you want to separate you Activity and AsyncTask more loosely, this is the handler method:
public class CustomActivity extends AppCompatActivity {
private String mChangedData;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CustomAsyncTask task = new CustomAsyncTask();
task.setOnDataChangedListener(new CustomAsyncTask.OnDataChangedListener() {
#Override
public void onDataChanged(String data) {
mChangedData = data;
}
});
task.execute(1);
}
private static class CustomAsyncTask extends AsyncTask<Integer, Void, Void> {
private OnDataChangedListener onDataChangedListener;
#Override
protected Void doInBackground(Integer... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(onDataChangedListener != null) {
onDataChangedListener.onDataChanged("foo");
}
}
void setOnDataChangedListener(OnDataChangedListener onDataChangedListener) {
this.onDataChangedListener = onDataChangedListener;
}
interface OnDataChangedListener {
void onDataChanged(String data);
}
}
}
I have several different AsyncTasks that need to perform the same shared basic operation and show progress while doing so. Rather than copying a lot of code several times (with progress showing in each) is there a way to share the code by passing in the other class? The AsyncTasks are very different and you can't just pass in the Abstract, which has a protected publishProgress() method anyway. Looked at a bunch of examples and tried to a lot of different variations without success.
So here are the details...lets say we have two different tasks doing different stuff, but sharing the need to hit a server, download a number of files and then put them in a DB (and then do other stuff):
public class ExampleTaskFragment extends ListFragment {
private ProgressDialog mProgress;
private void hideProgress() {
mProgress.dismiss();
}
private void showProgress(String message) {
mProgress = ProgressDialog.show(getActivity(), null, message, true, false);
}
protected void updateProgressMessage(String message) {
mProgress.setMessage(message);
}
public class TaskA extends AsyncTask<Object, String, ArrayList<A>> {
public void progressUpdate(String... values) {
publishProgress(values);
}
#Override
protected void onCancelled() {
hideProgress();
}
#Override
protected void onPreExecute() {
showProgress("Stuff before shared...");
}
#Override
protected ArrayList<A> doInBackground(Object... params) {
// DoStuffPublish is the common stuff both tasks share
DoStuffPublish dostuff = new DoStuffPublish(this);
return doMoreStuffA();
}
#Override
protected void onPostExecute(ArrayList<A> result) {
updateProgressMessage("After shared stuff...");
hideProgress();
}
ArrayList<A> doMoreStuffA() {
return new ArrayList<A>();
}
}
public class TaskB extends AsyncTask<Object, String, ArrayList<B>> {
public void progressUpdate(String... values) {
publishProgress(values);
}
#Override
protected void onCancelled() {
hideProgress();
}
#Override
protected void onPreExecute() {
showProgress("Stuff before shared...");
}
#Override
protected ArrayList<B> doInBackground(Object... params) {
// DoStuffPublish is the common stuff both tasks share
DoStuffPublish dostuff = new DoStuffPublish(this);
return doMoreStuffB();
}
#Override
protected void onPostExecute(ArrayList<B> result) {
updateProgressMessage("After shared stuff...");
hideProgress();
}
ArrayList<B> doMoreStuffB() {
return new ArrayList<B>();
}
}
}
public class DoStuffPublish {
private AsyncTask task;
public DoStuffPublish(AsyncTask task) {
super();
this.task = task;
doSharedStuff();
}
protected void publishProgress(String message) {
if (task instanceof TaskA) {
((TaskA)task).progressUpdate(message);
}
else if (task instanceof TaskB) {
((TaskB)task).progressUpdate(message);
}
}
public void doSharedStuff() {
publishProgress("Doing Shared stuff...");
// Do lots of shared things here...
publishProgress("Done doing shared stuff...");
}
}
This code has been cobbled together - so don't get too hung up on the syntax. The concept it there...I want to have a shared class I can call in 2 or more tasks that can share that code and still publish updates. I have tried putting the ProgressDialog in the tasks and outside without success. When I have done so I get "Only the original thread that created a view hierarchy can touch it's views". And in the debugger you can see the two different threads - the original main UI thread and the thread created in the Form doInBackground(Object... params).
I fear this may not be possible...
robinj - had it correct, just needed to read his/her answer a little better. The trick was to code it like this:`public class ExampleTaskFragment extends ListFragment {
private ProgressDialog mProgress;
private void hideProgress() {
mProgress.dismiss();
}
private void showProgress(String message) {
mProgress = ProgressDialog.show(getActivity(), null, message, true, false);
}
protected void updateProgressMessage(String message) {
mProgress.setMessage(message);
}
public class TaskA extends AsyncTask<Object, String, ArrayList<A>> {
public void progressUpdate(String... values) {
publishProgress(values);
}
#Override
protected void onProgressUpdate(String... values) {
updateProgressMessage(values[0]);
}
#Override
protected void onCancelled() {
hideProgress();
}
#Override
protected void onPreExecute() {
showProgress("Stuff before shared...");
}
#Override
protected ArrayList<A> doInBackground(Object... params) {
// DoStuffPublish is the common stuff both tasks share
DoStuffPublish dostuff = new DoStuffPublish(this);
return doMoreStuffA();
}
#Override
protected void onPostExecute(ArrayList<A> result) {
updateProgressMessage("After shared stuff...");
hideProgress();
}
ArrayList<A> doMoreStuffA() {
return new ArrayList<A>();
}
}
public class TaskB extends AsyncTask<Object, String, ArrayList<B>> {
public void progressUpdate(String... values) {
publishProgress(values);
}
#Override
protected void onProgressUpdate(String... values) {
updateProgressMessage(values[0]);
}
#Override
protected void onCancelled() {
hideProgress();
}
#Override
protected void onPreExecute() {
showProgress("Stuff before shared...");
}
#Override
protected ArrayList<B> doInBackground(Object... params) {
// DoStuffPublish is the common stuff both tasks share
DoStuffPublish dostuff = new DoStuffPublish(this);
return doMoreStuffB();
}
#Override
protected void onPostExecute(ArrayList<B> result) {
updateProgressMessage("After shared stuff...");
hideProgress();
}
ArrayList<B> doMoreStuffB() {
return new ArrayList<B>();
}
}
}
public class DoStuffPublish {
private AsyncTask task;
public DoStuffPublish(AsyncTask task) {
super();
this.task = task;
doSharedStuff();
}
protected void publishProgress(String message) {
if (task instanceof TaskA) {
((TaskA)task).progressUpdate(message);
}
else if (task instanceof TaskB) {
((TaskB)task).progressUpdate(message);
}
}
public void doSharedStuff() {
publishProgress("Doing Shared stuff...");
// Do lots of shared things here...
publishProgress("Done doing shared stuff...");
}
}
`
Note the
#Override
protected void onProgressUpdate(String... values) {
updateProgressMessage(values[0]);
}
Previously I had been trying to directly set the mProgress value, but it was in the wrong thread? Anyway thanks to robinj for the help! If you put an answer in I will thumbs it up...
I have an AsyncTask class SearchForQuestions that is called from an Activity QuizMap. When looping through an array in SearchForQuestions I can't find the correct context for toast to appear within the AsynTask.
The standard Toast.makeText(getApplicationContext(), "This is Toast!!!", Toast.LENGTH_SHORT).show(); gives error getApplicationContext() undefined.
I have tried some of the solutions to this offerred by SO, most of them are listed here and concern getting UiThread and running on that.
I can't get this to work however. Here's example code snippets of what i have tried. I have put a method in QuizMap and try calling it from SearchForQuestions but SearchForQuestions isn't recognised. How can I get around this? )Still a newbie at java...)
// QuizMap activity
public class QuizMap extends FragmentActivity
implements OnMarkerClickListener {
private GoogleMap map;
private static final String TAG = "QuizMap"; // debugging
...
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quizmap);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
...
}
// make toast inside AsyncTask
public void showNotNearToast(final String toast) {
QuizMap.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(QuizMap.this, "This is Toast!!!", Toast.LENGTH_SHORT).show();
}});
}
.
// SearchForQuestions class
private class SearchForQuestions extends AsyncTask<String, Void, DataHandler> {
// checks for proximity to question locations
Location location =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
#Override
protected DataHandler doInBackground(String... pointsList) {
String result = pointsList[0];
...
}
#Override
protected void onPostExecute(DataHandler result) {
ArrayList<String> resultsArray = result.results;
Integer numPoints = resultsArray.size();
for (int i =0;i<numPoints;i++){
String[] pointDetails = resultsArray.get(i).split("::");
...
// we can make use of the Android distanceTo function to calculate the distances
float distance = location.distanceTo(fixedLoc);
if (i > DIST) { // this is UCL
showNotNearToast("My Message"); // showNotNearToast undefined
if (distance < DIST) {
...
}
};
I'm going t close this question. I haven't solved my problem but the number of answers provided that apparently work in other situations suggest there's something else going on. I'm going to re-structure the classes to get around having to call from within AsyncTask.
Just Toast it, why do you want to create a function for it? onPostExecute() is already on UI thread.
You are not able to access because inner Class can not call functions of Outer class unless you pass instance of the outer class.
Call your toast in onPostExecute
Create an interface for a callback.
public interface ToastCallback {
public void invoke(String text);
}
Your AsyncTask constructor
private ToastCallback toastCallback;
public SearchQuestions(ToastCallback callback) {
this.toastCallback = callback;
}
// in doInBackground() {
toastCallback.invoke("Toast from background");
}
In Your Activity,
private void showNotNearToast(String text) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
}
public class MyToastCallback implements ToastCallback {
#Override
public void invoke(String text) {
showNotNearToast(text);
}
}
// Asynctask call
new SearchQuestion(new MyTosatCallback()).execute(<Your params here>);
Try this from inside your AsyncTask:
myActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
}
});
Where you have your
showNotNearToast("My Message"); // showNotNearToast undefined
Replace myActivity with the name of your Activity.
(Ab)use the publishProgress method
private class ToastAsyncTask extends AsyncTask<Void, String, Void>{
#Override
protected Void doInBackground(Void... voids) {
SystemClock.sleep(1000);
publishProgress("Toast msg string");
SystemClock.sleep(1000);
return null;
}
#Override
protected void onProgressUpdate(String... values) {
Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show();
}
}
**UPDATE: ** since you are having problems with context for some reason, use this version. Tough the implementation above works for me.
private class ToastAsyncTask extends AsyncTask<Void, String, Void> {
private WeakReference<Context> contextRef;
public ToastAsyncTask(Context context) {
contextRef = new WeakReference<Context>(context);
}
#Override
protected Void doInBackground(Void... voids) {
SystemClock.sleep(1000);
publishProgress("Toast msg string");
SystemClock.sleep(1000);
return null;
}
#Override
protected void onProgressUpdate(String... values) {
if (contextRef.get() != null) {
Toast.makeText(contextRef.get(), values[0], Toast.LENGTH_SHORT).show();
} else {
// The context was destroyed.. check what you are doing
}
}
}
Use it like this
new ToastAsyncTask(MainActivity.this).execute();
Pass the activity into the AsyncTask. See below.
private class SearchForQuestions extends AsyncTask<String, Void, DataHandler> {
Activity activity;
public void SearchForQuestions(Activity activity){
this.activity = activity;
}
//... rest of the code
public class QuizMap extends FragmentActivity implements OnMarkerClickListener {
/*...*/
new SearchForQuestions(this).execute();
/*...*/
/*When calling the toast:*/
Toast.makeText(this.activity, "This is Toast!!!", Toast.LENGTH_SHORT).show();
I try a Toast Message interface. If app not connection internet, I want show a Toast Message and I'm wanting java interfaces.
This is MotherActivity.java. This file implement ToastMessagges.ToastMessaggeCallback
public class MotherActivity extends ActionBarActivity implements ToastMessagges.ToastMessaggeCallback {
ToastMessagges toastMessagges;
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mother);
toastMessagges = new ToastMessagges();
AppStarter();
}
private void AppStarter(){
boolean checkinternet = InternetControl.checkInternetConnection( getApplicationContext() );
if( checkinternet ) {
toastMessagges.show_toast_messagge();
}
else {
}
}
#Override
public void LongToastMessagge() {
Toast.makeText(getApplicationContext(), "Hello World", Toast.LENGTH_LONG).show();
}
}
This is my ToastMessagges.java file.
public class ToastMessagges {
ToastMessaggeCallback toastMessaggeCallback;
public void show_toast_messagge(){
toastMessaggeCallback.LongToastMessagge();
}
public static interface ToastMessaggeCallback {
public void LongToastMessagge();
}
}
When the start this app. I get NullPointerException error.
Caused by: java.lang.NullPointerException
at com.medyasef.bulenttirasnewapp.bulenttiras.functions.ToastMessagges.show_toast_messagge(ToastMessagges.java:22)
at com.medyasef.bulenttirasnewapp.bulenttiras.MotherActivity.AppStarter(MotherActivity.java:36)
at com.medyasef.bulenttirasnewapp.bulenttiras.MotherActivity.onCreate(MotherActivity.java:29)
ToastMessagges.java:22
toastMessaggeCallback.LongToastMessagge();
Sorry bad english.
Please help.
Thank you.
You haven't initialized you ToastMessaggeCallback toastMessaggeCallback.
To do this, write
ToastMessaggeCallback toastMessaggeCallback = new ToastMessaggeCallback(){
public void LongToastMessagge(){
// add some toasting code here
}
};
This will make an object implementing your interface (called "anonymous class"). Of course, your ToastMessaggeCallback should do something in the method LongToastMessagge, so add the desired code there.
I will recommend you to create a Util class instead of Interface. I'm here giving you an example of Util class.
public class Util {
public static void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
}
Then call the showToast() method from your activity as follows...
Util.showToast(YourActivity.this, "text");
Update:
Declare your Interface as a individual, not inside a class as below...
public interface ToastMessaggeCallback {
public void showLongToastMessagge(String text);
}
Then implement the Interface as follows...
public class MotherActivity extends ActionBarActivity implements ToastMessaggeCallback {
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mother);
AppStarter();
}
private void AppStarter(){
boolean checkinternet = InternetControl.checkInternetConnection( getApplicationContext() );
if( checkinternet ) {
showLongToastMessagge("Hello World");
}
else {
}
}
#Override
public void showLongToastMessagge(String text) {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
}
Your ToastMessagges class needs to provide a method to register the callback. Then, your Activity needs to call this method to register itself as the callback, right after you construct the ToastMessages object.
I don't understand why I'm getting this error. I'm using AsyncTask to run some processes in the background.
I have:
protected void onPreExecute()
{
connectionProgressDialog = new ProgressDialog(SetPreference.this);
connectionProgressDialog.setCancelable(true);
connectionProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
connectionProgressDialog.setMessage("Connecting to site...");
connectionProgressDialog.show();
downloadSpinnerProgressDialog = new ProgressDialog(SetPreference.this);
downloadSpinnerProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
downloadSpinnerProgressDialog.setMessage("Downloading wallpaper...");
}
When I get into doInBackground() depending on a condition I:
[...]
connectionProgressDialog.dismiss();
downloadSpinnerProgressDialog.show();
[...]
Whenever I try downloadSpinnerProgressDialog.show() I receive the error.
Any ideas guys?
The method show() must be called from the User-Interface (UI) thread, while doInBackground() runs on different thread which is the main reason why AsyncTask was designed.
You have to call show() either in onProgressUpdate() or in onPostExecute().
For example:
class ExampleTask extends AsyncTask<String, String, String> {
// Your onPreExecute method.
#Override
protected String doInBackground(String... params) {
// Your code.
if (condition_is_true) {
this.publishProgress("Show the dialog");
}
return "Result";
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
connectionProgressDialog.dismiss();
downloadSpinnerProgressDialog.show();
}
}
I had a similar issue but from reading this question I figured I could run on UI thread:
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
alertDialog.show();
}
});
Seems to do the trick for me.
I had a hard time making this work too, the solution for me was to use both hyui and konstantin answers,
class ExampleTask extends AsyncTask<String, String, String> {
// Your onPreExecute method.
#Override
protected String doInBackground(String... params) {
// Your code.
if (condition_is_true) {
this.publishProgress("Show the dialog");
}
return "Result";
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
alertDialog.show();
}
});
}
}
final Handler handler = new Handler() {
#Override
public void handleMessage(final Message msgs) {
//write your code hear which give error
}
}
new Thread(new Runnable() {
#Override
public void run() {
handler.sendEmptyMessage(1);
//this will call handleMessage function and hendal all error
}
}).start();