write Gson Object to Bundle - Android android.os

Android examples for android.os:Bundle

Description

write Gson Object to Bundle

Demo Code

import android.os.Bundle;
import java.util.ArrayList;

public class Main{

    /**//from  w w w .  jav  a 2s  . c  om
     * Writes Gson compatible object into the bundle.
     *
     * @param clazz  type of t
     * @param t      item_book we want to persist
     * @param bundle to persist into. If null passed new one will be created
     * @param <T>    type of t
     * @return bundle with appended data
     */
    public static <T> Bundle writeObject(Class<T> clazz, T t, Bundle bundle) {
        if (bundle == null) {
            bundle = new Bundle();
        }
        if (t != null) {
            bundle.putString(clazz.getSimpleName(), GsonUtils.toJson(t));
        }

        return bundle;
    }
    /**
     * Creates bundle and writes Gson compatible object into that bundle.
     *
     * @param t   item_book we want to persist
     * @param <T> type of t
     * @return bundle with appended data
     */
    public static <T> Bundle writeObject(Class<T> clazz, T t) {
        return writeObject(clazz, t, null);
    }

    /**
     * Puts string value to bundle if passed and creates it if {@code null} passed.
     *
     * @param bundle to put into
     * @param key    to to put under
     * @param value  to put
     * @return bundle with the newly put value
     */
    public static Bundle putString(Bundle bundle, String key, String value) {
        if (bundle == null) {
            bundle = new Bundle();
        }
        bundle.putString(key, value);
        return bundle;
    }

}

Related Tutorials