I'm trying to pass an array of Address objects to another Activity through an Intent object.
As the Address class implements the Parcelable interface I try to do the following. I got a List Address object from a Geocoder object, which I convert into a array of Address objects. Then I put this array into the Intent and call the activity.
final Address[] addresses = addresseList.toArray(new Address[addresseList.size()]);
final Intent intent = new Intent(this, SelectAddress.class);
intent.putExtra(SelectAddress.INTENT_EXTRA_ADDRESSES, startAddresses);
startActivityForResult(intent, REQUEST_CODE_ACTIVITY_SELECT_ADDRESSES);
On the other activity I try to retrieve the Address[] from the Intent with the following piece of code. But the call of the last line ends with a ClassCastException Landroid.os.Parcelable.
Bundle bundle = getIntent().getExtras();
Address[] addresses = (Address[]) bundle.getParcelableArray(INTENT_EXTRA_ADDRESSES);
What am I doing wrong? How do I have to retrieve the Address[].
The problem is the casting. try:
Bundle bundle = getIntent().getExtras();
Parcelable[] parcels = bundle.getParcelableArray(INTENT_EXTRA_ADDRESSES);
Address[] addresses = new Address[parcels.length];
for (Parcelable par : parcels){
addresses.add((Address) par);
}
or on java1.6:
Parcelable[] x = bundle.getParcelableArray(KEY);
addresses = Arrays.copyOf(x, x.length, Address[].class);
The #LiorZ answer is completely true. I just merged his answer and this other in this handy function.
#SuppressWarnings("unchecked")
private static <T extends Parcelable> T[] castParcelableArray(Class<T> clazz, Parcelable[] parcelableArray) {
final int length = parcelableArray.length;
final T[] array = (T[]) Array.newInstance(clazz, length);
for (int i = 0; i < length; i++) {
array[i] = (T) parcelableArray[i];
}
return array;
}
Related
I need to pass a 2D array as an intent onto another activity.
This code works for sending the 2D array, the problem is retrieving it in the next activity.
i++;
Intent tryAgain = getIntent();
tryAgain.putExtra("index", i);
tryAgain.putExtra("from", "next");
int [][] previousValues = getSelectedIndices();
Toast.makeText(AnotherActivity.this, "Bang " + previousValues[3][3], Toast.LENGTH_SHORT).show();
Bundle mBundle = new Bundle();
mBundle.putSerializable("array", previousValues);
tryAgain.putExtras(mBundle);
AnotherActivity.this.finish();
startActivity(tryAgain);
I have already tried this code below to retrieve the 2D array, it does NOT work.
else if(getIntent().getStringExtra("from").equals("next")){
i=index;
int [][] arrayReceived=null;
Object[] objectArray = (Object[]) getIntent().getExtras().getSerializable("array");
if(objectArray!=null){
arrayReceived = new int[objectArray.length][];
for(int i=0;i<objectArray.length;i++){
arrayReceived[i]=(int[]) objectArray[i];
}
}
You can do something for receiving array like this as an example:
Bundle b = getIntent().getExtras();
int[][] list_array = (int[][])b.getSerializable("array");
I have a list of json array response with multiple userinformation. Created a bundle and successfully passed it to next activity. Created another bundle with user selected date and time.But no luck to second bundle to the same activity because i can be able to pass only one bundle to same activity.
My actual problem is how to pass second bundle in putExtras to same activity
Json Response
{
"userinfo": [
{
"address": "Tambaram",
"name": "Vishranthi"
},
{
"address": "Medavakkam",
"name": "Sophia"
},
]
}
Bundle creation code:
JSONArray infoarray = obj.getJSONArray("Info");
Bundle h = new Bundle();
for (int i = 0; i < infoarray.length(); i++) {
Bundle b = new Bundle();
JSONObject infoobject = infoarray.getJSONObject(i);
String name = infoobject.getString("name");
String address = infoobject.getString("address");
b.putString("name", name);
b.putString("address", address);
h.putBundle(Integer.toString(i), b);
System.out.println(b);
}
Intent i = new Intent(context, Secondpage.class);
Bundle d=new Bundle();
d.putString("date", text1);
d.putString("time", text2);
i.putExtras(h);
System.out.println(h);
context.startActivity(i);
if you want to put two bundles into your intent you have to use
Intent putExtra (String name,
Bundle value)
something like this:
Intent i = new Intent(context, Secondpage.class);
i.putExtra("bundleH", h);
i.putExtra("bundleD", d);
ref
instead of create another Bundle to the date and time use the same one
You cannot, so the easiest solution would be to pass the json youre parsing into the second activity and the values you want on the second bundle as primitives, then on the second activity parse json into primitive data and retrieve date & time.
You don't need to deserialize a JSONObject or JSONArray, just put it in Bundle as String.
Bundle bundle = new Bundle();
bundle.putString("MyBundle", infoarray.toString());
So at next Activity, get the JSONArray
JSONArray newJArray = new JSONArray(bundle.getString("MyBundle",""));
A little tip: Avoid declare variables inside loops to avoid memory leaks.
I think you should change the approach a bit:
do this in your first activity your you have the json array
Intent i = new Intent(context, Secondpage.class);
i.putExtra("userinfo", infoarray.toString());
and in your second activity do the rest code
if (getIntent().getExtras() != null && getIntent().getExtras().containsKey("userinfo")) {
try {
JSONArray infoarray = new JSONArray(getIntent().getExtras().getString("userinfo"));
for (int i = 0; i < infoarray.length(); i++) {
]
JSONObject infoobject = infoarray.getJSONObject(i);
String name = infoobject.getString("name");
String address = infoobject.getString("address");
//your code parse user list
}
} catch (JSONException e)
}
I got a byte arraylist(List<byte[]> barray= new ArrayList<byte[]>();).And i need to pass it to another activity.How i can do it with intent.putextra method or something else ?
Something like this to populate the intent:
Intent intent = new Intent(...);
intent.putExtra("barray_size", barray.size());
for (int i = 0; i < barray.size(); i++) {
intent.putExtra("barray"+i, barray.get(i));
}
Then to get them out in the other activity:
Intent intent = getIntent();
ArrayList<byte[]> barray = new ArrayList<>();
int size = intent.getIntExtra("barray_size", 0);
for (int i = 0; i < size; i++) {
barray.add(intent.getByteArrayExtra("barray"+i));
}
May you can use a JSON serializer to accomplish this task. So you can convert from any (List in your case) to string and this is easy to serialize.
In my app, i need to send a Two dimensional Array and two more integer values form on Activity to Another with the help of Intent method.
This is done as ..
Intent i = new Intent(getApplicationContext(), ViewActivity.class);
Bundle postbundle = new Bundle();
String[][] X={{"abc"},{"def"}};
postbundle.putSerializable("data", X);
i.putExtra("A", postbundle);
i.putExtra("albumid", position);
i.putExtra("Bigcard",bigcard);
here am using .putSerializable method to place an array into bundle.
So to access these data in the receiver Activity am using
Bundle bundle = getIntent().getBundleExtra("A");
String[][] ABC=(String[][]) bundle.getSerializable("data");
Log.e("Array is",""+ABC);
but I got java.lang.NullPointerException error message..
Whith out use of " Static " declaration how can i get these values from bundle here (in the receiver Activity..)
Let me out pls from this ..
step-1:Write a seperate bean class and save into another file
public class MyBean implements Serializable{
String[][] data = null;
public void set2DArray(String[][] data){
this.data = data;
}
public String[][] get2DArray(){
return data;
}
}
step-2:In the calling activity
Intent intent = new Intent(this, Second.class);
String data[][] = new String[][] {{"1","kumar"},{"2","sona"},{"3","kora"},{"1","pavan"},{"2","kumar"},{"3","kora333"}};
MyBean bean = new MyBean();
bean.set2DArray(data);
Bundle b = new Bundle();
b.putSerializable("mybean", bean);
intent.putExtra("obj", b);
startActivity(intent);
step-3:In the caller activity
Bundle b = getIntent().getBundleExtra("obj");
MyBean dData = (MyBean) b.getSerializable("mybean");
String[][] str =dData.get2DArray();
Not a real answer, but a try:
what happens if You try:
Intent intent = getIntent();
int a = intent.getIntExtra("albumid"); //if Your value is an int, otherwise use String
//getStringExtra or whatever Your value is
I want to pass a 2-D String Array to another activity.
My S2-D String Array (String[][]) is 'selected_list'.
code is :
Bundle list_bundle=new Bundle();
list_bundle.putStringArray("lists",selected_list);
Intent list_Intent = new Intent(v.getContext(), view_selected_items.class);
startActivityForResult(list_Intent, 2);
But putStringArray("lists",selected_list) is showing a error like we can pass only 1-Dimensional Array (String[]).
Thanks
You can use putSerializable. Arrays are serializable, provided their elements are.
To store:
list_bundle.putSerializable("lists", selected_list);
To access:
String[][] selected_list = (String[][]) bundle.getSerializable("lists");
This finally works well for me : Thanks to Matthew and Mehdiway
To start a new activity (sending String[][] and String):
String[][] arrayToSend=new String[3][30];
String stringToSend="Hello";
Intent i = new Intent(this, NewActivity.class);
i.putExtra("key_string",stringToSend);
Bundle mBundle = new Bundle();
mBundle.putSerializable("key_array_array", arrayToSend);
i.putExtras(mBundle);
startActivity(i);
To access in NewActivity.onCreate:
String sReceived=getIntent().getExtras().getString("key_string");
String[][] arrayReceived=null;
Object[] objectArray = (Object[]) getIntent().getExtras().getSerializable("key_array_array");
if(objectArray!=null){
arrayReceived = new String[objectArray.length][];
for(int i=0;i<objectArray.length;i++){
arrayReceived[i]=(String[]) objectArray[i];
}
}
As Matthew said, you can put the string array in the bundle like this
Bundle list_bundle=new Bundle();
list_bundle.putStringArray("lists",selected_list);
This works very well, but when you try to get the array via (String[][]) bundle.getSerializable("lists"); it gives a
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.util.String
So what you have to do is this :
Object[] objectArray = (Object[]) getIntent().getExtras().getSerializable("lists");
int horizontalLength = 0;
if (objectArray.length > 0)
horizontalLength = ((Object[]) objectArray[0]).length; // See explanation to understand the cast
String[][] my_list = new String[objectArray.length][horizontalLength];
int i = 0;
for(Object row : objectArray)
{
my_list[i][0] = ((String[])row)[0];
my_list[i++][1] = ((String[])row)[1];
}
Explanation :
When you get the array as I Serializable object it doesn't behave the same way a simple String array does, instead it considers every row as a separate array, so what you have to do is to read the Serializable object as a one dimensional array, and then cast every row of it to a String[] array. Et voila !