ramzixp
ramzixp

Reputation: 17920

Array, HashMap, Strings - how to send it via Bundle?

I know how to send simple array via Bundle but know I need to send something like this:

 ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();

How to send and retrive it via Bundle?

Upvotes: 2

Views: 592

Answers (6)

Sushant
Sushant

Reputation: 254

Gson gson = new Gson();
Type type = new TypeToken<ArrayList<HashMap<String, String>>>() {}.getType();
ArrayList<HashMap<String, String>> arrayList = gson.fromJson(data, type);

For retrieving data in reciever class

Upvotes: 0

M A
M A

Reputation: 72854

ArrayLists and HashMaps are serializable objects. So just use Bundle#putSerializable(bundleKey, serializable).

If you want a more OOP approach, you can encapsulate the data to be sent into an object (say of type SongData) that implements Parcelable. See this post for an example. Also see the reference documentation for Parcelable:

public class MyParcelable implements Parcelable {
  private int mData;

  public int describeContents() {
      return 0;
  }

  public void writeToParcel(Parcel out, int flags) {
      out.writeInt(mData);
  }

  public static final Parcelable.Creator<MyParcelable> CREATOR
         = new Parcelable.Creator<MyParcelable>() {
      public MyParcelable createFromParcel(Parcel in) {
          return new MyParcelable(in);
      }

      public MyParcelable[] newArray(int size) {
          return new MyParcelable[size];
      }
  };

  private MyParcelable(Parcel in) {
     mData = in.readInt();
  }
}

Upvotes: 2

Sushant
Sushant

Reputation: 254

ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
Gson gson = new Gson();
String str_json = gson.toJson(songsListData);
Bundle bundle=new Bundle();
bundle.putString("data",str_json);

Use Gson for converting arraylist data into string

Upvotes: 0

Hayk Petrosyan
Hayk Petrosyan

Reputation: 373

Use something like the following in the sender

ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
intent.putExtra("song_list", songsListData);

and than in the receiver class

ArrayList<String> myList = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("song_list");  

Upvotes: 1

ddb
ddb

Reputation: 2435

In the sender class

bundle.putSerializable("something", songsListData);

and in the receiver class

ArrayList<HashMap<String, String>> songsListData = (ArrayList<HashMap<String, String>>)bundle.getSerializable("something");
;

Upvotes: 1

duffymo
duffymo

Reputation: 308813

This is bad encapsulation, poor object oriented thinking.

It sounds like you need a Song abstraction so you can return a List of Song instances:

List<Song> songList = new ArrayList<Song>();

I would avoid Java serialization; serialize them as JSON using Jackson.

Upvotes: 2

Related Questions