livefront / bridge

An Android library for avoiding TransactionTooLargeException during state saving and restoration

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

can i use this library to transfer data between activities?

or-dvir opened this issue · comments

is this library only for saving/restoring state or can i use it to transfer data between activities?
please provide an example if possible

@or-dvir So technically that's not what this library is for but that is a really great question. I haven't really thought about it too much in the past but I bet you could probably a hack a solution into place.

Here's something I sketched out real quick. (I haven't actually tested it so I can't guarantee it works but I think you'll get the idea.) First, create a class that's going to leverage the save / restore calls from Bridge:

    public class BridgeTransport {

        @State Bundle mData;

        private BridgeTransport(@Nullable Bundle data) {
            mData = data;
        }

        public static void putData(
                @NonNull Bundle data,
                @NonNull Intent activityIntent) {
            Bundle currentExtras = activityIntent.getExtras();
            Bundle extras = currentExtras != null ? currentExtras : new Bundle();
            Bridge.saveInstanceState(new BridgeTransport(data), extras);
            activityIntent.putExtras(extras);
        }

        public static Bundle getData(@NonNull Intent activityIntent) {
            BridgeTransport transport = new BridgeTransport(null);
            Bridge.restoreInstanceState(transport, activityIntent.getExtras());
            return transport.mData;
        }

    }

Here I'm assuming your SavedStateHandler is going to be something like Icepick. Saving your data to push it to another Activity would then look something like this:

        Intent intent = new Intent(this, SomeActivity.class);
        Bundle yourData = new Bundle();
        // ...put data in the Bundle
        BridgeTransport.putData(yourData, intent);
        startActivity(intent);

And then to retrieve it in the next Activity:

        Bundle data = BridgeTransport.getData(getIntent());
        // ...get data from your Bundle

Hopefully that helps (and works...)

An important thing to note, though : this might have some problems with trying to grab the data from the Intent a second time (such as after a rotation or state restoration) since Bridge is going to automatically clear data that's been retrieved already. So you might need to save the data you pull out into the new Activity's saved state. So this solution might get a little awkward. See how it goes, though. If this feature is something enough people are interested in I could look at including it in the future.