Search code examples
androidmultithreadingandroid-activity

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?


Solution

  • 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.