giozh
giozh

Reputation: 10068

Pass ArrayList of integer array via bundle

I'm looking for a way to pass, via bundle, an

ArrayList<Integer[]> 

object to a Fragment (after activity is already created, so i can't use intent). By looking to android api, no method seems to do what i'm looking for. How can i do?

Upvotes: 2

Views: 5091

Answers (4)

nvinayshetty
nvinayshetty

Reputation: 3237

you can pass the Array List of integers by using the method putIntegerArrayList

Here is the code snippet

 ArrayList<Integer> values=new ArrayList<>();
            values.add(1);
            values.add(60);
            values.add(75);
            values.add(120);
 Bundle extras = new Bundle();
 extras.putIntegerArrayList(EXTRA_KEY,values); 

Upvotes: 0

Crimson
Crimson

Reputation: 311

int[] intarray = new int[] {4,5,6,7,8};

Bundle bundle = new Bundle();
bundle.putIntArray("integerarray", intarray);

Or an ArrayList with int arrays?

For that i think you should use Parcable. Or you could try to send the individual intArrays via the bundle and put them together in the receiving Activity. Like this:

int[] intarray1 = new int[] {4,5,6,7,8};
int[] intarray2 = new int[] {4,5,6,7,8};
int[] intarray3 = new int[] {4,5,6,7,8};

Bundle bundle = new Bundle();
bundle.putIntArray("INT_ARRAY1", intarray1);
bundle.putIntArray("INT_ARRAY2", intarray2);
bundle.putIntArray("INT_ARRAY3", intarray3);

Intent intent = new Intent(this,NewActivity.class)
intent.putExtras(bundle);
startActivity(intent)

Then in NewActivity.java you should create an array and get the bundle and fill the array with the received arrays.

Upvotes: 0

vlllc
vlllc

Reputation: 41

Sending activity:

final Intent intent = new Intent(this, SecondActivity.class);
Bundle extraBundle = new Bundle();

extraBundle.putIntegerArrayList("arraylist", [put array list here]);

intent.putExtras(extraBundle);
intent.setComponent(new ComponentName("com.myapp", "com.myapp.SecondActivity"));

startActivity(intent);

Receiving activity's onCreate():

final Intent intent = getIntent();
final Bundle extraBundle = intent.getExtras();

ArrayList<Integer> myIntegerArrayList = extraBundle.getIntegerArrayList("arraylist");

You can change "arraylist" to what you want in the setter and getter method calls, they just need to be the same.

Upvotes: 2

Thein
Thein

Reputation: 3968

I used Gson, convert to JSONArray and send via Bundle. But it may affects performance.

In First Activity

Intent activity = new Intent(MyActivity.this,NextActivity.class);
activity.putExtra("myArrayList", new Gson().toJson(myArrayList);
startActivity(activity);

In other activity..

Sting myArrayList;
Bundle extras = getIntent().getExtras();
if (extras != null) {
   myArrayList= extras.getString("myArrayList");

   Type listOfInteger = new TypeToken<List<Integer>>(){}.getType();
   String s = new Gson().toJson(myArrayList, listOfInteger);
   List<Integer> myList = new Gson().fromJson(s, listOfInteger); 
}

Upvotes: 0

Related Questions