Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RunOnUIThread from CustomCursorAdapter

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?

like image 404
Aritra Roy Avatar asked Jul 28 '14 03:07

Aritra Roy


3 Answers

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
    }
});
like image 159
Ashvin solanki Avatar answered Oct 16 '22 03:10

Ashvin solanki


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.

like image 24
Saeid Yazdani Avatar answered Oct 16 '22 02:10

Saeid Yazdani


  ((AppCompatActivity) context).runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {

                                            //context.refreshInbox();
                                        }
                                    });
like image 5
jagadishlakkurcom jagadishlakk Avatar answered Oct 16 '22 04:10

jagadishlakkurcom jagadishlakk