Search code examples
javaandroidandroid-activityandroid-recyclerviewandroid-async-http

Update a recyclerView in another activity from async thread of other activity


I have two activity A and B.

In activity A I have a AsyncHttpClient fetching some data from a website. Once the data is received, I refresh the RecyclerView in activity A. But while the data is being fetched if someone switches to activity B, i want the RecyclerView of activity B to be refreshed on completion of data fetch.

Currently I am able to update in the same activity A, but can't do that in B.

Here is what I have done -

public void loadFromWeb(){
            RequestParams params = new RequestParams();
            AsyncHttpClient client = new AsyncHttpClient();
            params.put("id", id);

            client.post("http://example.com/process.php", params, new JsonHttpResponseHandler() {
                @Override
                public void onStart() {

                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    try {
                        //process the response

                        adapterInActivityA.notifyDataSetChanged();
                        //This works for Activity A

                        //How to implement the function updateInActivityB()?  
                        updateInActivityB();

                    } catch (Exception e) {
                        //catch exception
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    // Process failure
                }

            });
}

The problem is how to implement function updateInActivityB()


Solution (As suggested by Alok)

Following are the details of what I did for others who want to do the same -

This uses greenrobot's EventBus library

Compile the library by adding it to the app's build.gradle file

Compile the library

compile 'de.greenrobot:eventbus:2.4.0'

Create your event class, this will store the data which you are communicating.

//In FirstActivity

public class myEvent {
    private final String data;

    //Constructor
    public myEvent(String data){
        this.data = data;
    }

    public String getData(){
        return data;
    }
}

Whenever you want to send an update the data has been downloaded (i.e. in updateInSecondActivity() function)

post the update -

//In FirstActivity

public void updateInSecondActivity(){
    EventBus.getDefault().post(new myEvent("Updated Data");
}

Now, In the SecondActivity, you have to listen for this event. First Register in the SecondActivity to subscribe to the events -

Register for the events

//In SecondActivity

EventBus.getDefault().register(this);

You can register in onCreate(), onStart(), onResume(). Also don't forget to unregister in onPause(), onDestroy(), onStop() -

Unregister the event listener

//In SecondActivity

EventBus.getDefault().unregister(this);

Once the registration and unregistration is in place, you have to listen if the update has been posted by FirstActivity or not. You can do this by creating an onEvent() function which listens for posting of myEvent class -

Listen to the event

//In SecondActivity

public void onEvent(myEvent mE){
    String updatedData = me.getData();
    // Process/update using the updateData
}

Solution

    1. You can try to make a broadcast receiver that can receive a broadcast Message fired by your asynchronous thread.

    Or

    2.you can use event bus to limitless communication.

    Or

    3.you can register an observer for content received .

    Logic is pretty simple You try to fetch the data if data fetched before user switch to next activity than everything is fine.

    In second case when user switches earlier, than in this case you can check for content while resuming next activity. If content not received yet than you can implement any of above 3 method observer ultimately when content received your observer will be notified.