executing runOnUiThread on a separate class
You need to have the Activity's
reference (lets name it activity
) and pass it to your AsyncTask
class. Then you can call runOnUiThread
like this:
activity.runOnUiThread
The runOnUiThread is a method defined in Activity
class.
Just add a contsructor to your AsyncTask. Your AsyncTask will look like this:
public class AdamTask extends AsyncTask<String, Void, String> {
private Activity activity; //activity is defined as a global variable in your AsyncTask
public AdamTask(Activity activity) {
this.activity = activity;
}
public void showToast(final String toast)
{
activity.runOnUiThread(new Runnable() {
public void run()
{
Toast.makeText(activity, toast, Toast.LENGTH_SHORT).show();
}
});
}
...
}
Then to call the AsyncTask
you need something like this:
AdamTask adamTask = new AdamTask(Eve.this);
adamTask.excecute(yourParams);
UPDATE As Sam mentioned in the comments, AsyncTasks
may result in context
leaking when configuration changes occur (one example is when screen rotates and the Activity
is recreated). A way to deal with this is the headless fragment
technique.
Another way, more efficient, is using an event bus. See here for more information (link provided by Sam in the comments).
Android how to runOnUiThread in other class?
Here's a solution if you don't want to pass the context:
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
// code goes here
}
});
Run on UI thread from another class
You can use this snippet
textView.post(new Runnable() {
@Override
public void run() {
textView.setText("Text");
}
});
Want to use Context instead of Activity for RunOnUIThread
You don't need context too.
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// Your code here
}
});
Related Topics
How to Open a Fragment on Button Click from a Fragment in Android
How to Save Image in Shared Preference in Android | Shared Preference Issue in Android with Image
How to Send Data Message Using Firebase Console
Android Drag and Drop Images on the Screen
Change Keyboard Input Language
Java.Lang.Noclassdeffounderror: Android.Support.V7.Appcompat.R$Styleable
Image Size (Drawable-Hdpi/Ldpi/Mdpi/Xhdpi)
Android Preferences: How to Load the Default Values When the User Hasn't Used the Preferences-Screen
How to Add External Fonts to Android Application
How to Change Toolbar Navigation and Overflow Menu Icons (Appcompat V7)
Android Webview - Intercept Clicks
Naming My Application in Android
How to Open My Existing Eclipse Projects in Android Studio
Android Custom View Group Delegate Addview