What I Have
I have a Custom Cursor Adapter from where I run a Thread to do some heave tasks.
What I Want
I want to update he UI upon completion of the thread, like showing a Toast.
My Problem
As I am inside the Custom Cursor Adapter, I am unable to get the Activity to use the runOnUiThread
method like getActivity().runOnUiThread()
. The Custom Cursor Adapter class is just a Java class and not an Activity or Fragment.
How can I get the Activity
reference and execute the runOnUiThread
method from my CustomCursorAdapter
?
I know this is late, but I hope this approach helps other people.
This solution works if I have Adapter (RecyclerView Adapter,Viewpager Adapter... etc)
, and in this adapter I'm working with AsyncTask
and want to change some data by using that AsyncTask
:
((Activity)contextObject).runOnUiThread(new Runnable() {
@Override
public void run() {
//change View Data
}
});
You need to somehow pass a reference of your activity to your adapter. then through some casting or use of interfaces you can call on ((YourActivity)context).runOnUiThread()
as for accessing the fragment manager, you need to do the same casting.
((YourActivity)context).getFragmentManager()
But be aware! this is not a good design pattern. if the context
is no an activity, you will soon have to deal with lots of NPE exceptions and stuff. For example, ApplicationContext
does not have getFragmentManager
but when you do the casting above, your IDE will not notify you, you will find that out when you actually try it on emulator or device.
Using interfaces are a bit safer, at least you know that your activity has which interface implemented.
((AppCompatActivity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
//context.refreshInbox();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With