Integer[] not working in Intent#putExtra(...) - android

I want to put an int[] into an Android Intent. For various reasons I am getting a LinkedList<Integer>, so I tried (roughly) this:
LinkedList<Integer> myList = getIntegerList();
Intent intent = new Intent (context, class);
intent.putExtra("com.me.INTARRAY", myList.toArray());
This didn't work because toArray() was giving me an Object[]. I thought I could fix it by doing
intent.putExtra("com.me.INTARRAY", (Integer[]) myList.toArray(new Integer[myList.size()]) )
which does indeed produce an Integer[]; however, getting it out of the Intent STILL doesn't work.
Ultimately this isn't too hard to work around with a for loop so I ask more for curiosity than any other reason, but ... how do you get an Integer[] into an Intent extra as though it were an int[]?

I have not tested this thoroughly, but I believe it should work. You can try it.
Integer[] integerArray = {/*something */ };
intent.putExtra("com.me.INTARRAY", integerArray);
And then (not working)
Integer[] newArray = (Integer[]) getIntent().getSerializableExtra("com.me.INTARRAY");
EDIT:
Ahh.. After a little research and testing it seems the above is not possible. It is not possible because the compiler would have to iterate through every element to verify the cast. A solution(and I have testet it this time) would be to do this instead:
Object[] s = (Object[]) getIntent().getSerializableExtra("com.me.INTARRAY");
Integer[] newArray = Arrays.copyOf(s, s.length, Integer[].class);
I found the explanation here: Deserializing Arrays on Android

You can change the array to int[] and pass it as extras using putExtra(java.lang.String, int[]). On the other side you will need to get that extra using getIntArrayExtra.
Here is the code that works fine, caller first and receiver follows:
LinkedList<Integer> myList = getIntegerList();;
int iArray[] = new int[myList.size()];
for (Integer i : myList)
iArray[myList.indexOf(i)] = i;
Intent intent = new Intent();// create your actual intent
intent.putExtra("com.your.package.name.int", iArray);
startActivity(intent);
and the other side:
int array[] = getIntent().getExtras().getIntArray("com.your.package.name.int");
Another alternate, (which is better i guess) is to convert the LinkedList to Integer ArrayList. This works as follows, sender first receiver followed.
intent.putIntegerArrayListExtra("com.your.package.name.array", new ArrayList<Integer>(myList));
and on the other side:
ArrayList<Integer> array = getIntent().getExtras().getIntegerArrayList("com.your.package.name.array");
Hope this helps :)

Related

ArrayList contains null after being passed to next activity

I use an ArrayList to store some data and then pass it to the next activity where it is actually required through the .putStringArrayList() method. I use the same process in a couple of places in a my project where it works absolutely fine. However, in this particular case, when I extract it in the receiving activity, it contains null. To be sure, I even displayed the list before sending it, and it did displayed the strings I require. Here is my code for sending the Arraylist:
for(int i=0; i<AssignmentTitles.size(); i++)
{
System.out.println(AssignmentTitles.get(i));
}
Intent localIntent;
localIntent = new Intent(CourseFolder.this, Assignments.class);
Bundle b=new Bundle();
b.putStringArrayList("titles",AnnouncementTitles);
b.putStringArrayList("links",AnnouncementLinks);
localIntent.putExtras(b);
startActivity(localIntent);
Here is the receiving activity code:
AssignmentTitles = getIntent().getStringArrayListExtra("titles");
AssignmentLinks = getIntent().getStringArrayListExtra("links");
System.out.println("size: " + AssignmentLinks.size() + "TITLES:");
for(int i=0; i<AssignmentTitles.size(); i++)
{
System.out.println(AssignmentTitles.get(i));
}
setListAdapter( new ArrayAdapter<String(Assignments.this,
android.R.layout.simple_list_item_1,
AssignmentTitles));
The problem is that I use the exact same code in another part of my project and it works perfectly, what could be the problem?
Try this way
AssignmentTitles = getIntent().getExtras().getStringArrayList("titles");
AssignmentTitles = getIntent().getExtras().getStringArrayList("links");
Use Intent.getExtras() to get the Bundle first, then extract your array lists.

how to get an int value according to its name

I would like to ask how can I get the value of predefined value to its name
The following is my code
public class Calculation_Activity extends Activity{
int a=1;
int b=2;
int c=50;
int result;
String array1[]=new String[]{"a","b","c"};
}
I would like to ask how can I get the value of the string by using array1[i]?
for instance, I would like to use array1[3]to call the value of c[ie.50]
May you give me some advice on this matter?
You might solve your issue by using a Map and its standard implementation HashMap:
Map<String, Integer> values = new HashMap<String, Integer>();
values.put("a",1);
values.put("b",2);
values.put("c",50);
String array1[] = new String[] {"a","b","c"};
int result = values.get(array1[2]); //result = 50
// or
int result = values.get("c"); //result = 50
You can use a HashMap (http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html), is a dictionary like data structure where you can store key-pair values
What you're trying to achieve would be better suited to a dynamic/scripting language. Have you considered using a Map instead of multiple varaibles?
In Java, this is not a common approach, such as it would be in scripting languages. You could try to use a Map (ie HashMap), which would enable you to achieve what you want, sort of.
In fact I think it is possible to do exactly what you want using reflection in Java, but I would not go there!

Java Android passing data Array double

I have a question about intent in android application
i have an array in class1
double [][] tableCityPair = new double[100][100];
---here code to fill array---
in the end of class i want to send tableCityPair to another class, class2.
how i should declare for array in class2 ?
is this right?
Intent it = getIntent();
double tabelJarakAntarKota= it.getDoubleExtra("tableCityPair",3);
The Bundle class has methods for passing and retrieving an array of doubles:
void putDoubleArray(String, double[])
double [] getDoubleArray(String)
However, these work for one-dimensional arrays. You are attempting to pass a 2D array. I do not know of a direct way to do this. One way to achieve this would be to put N arrays of doubles in a loop.
for(int i=0;i<tableCityPair.length;i++){
bundle.put("tableCity"+i, tableCityPair[i]);
}
And at the receiving end, you do:
double [] aPair = it.getExtras().getDoubleArray("tableCity"+i);
I'm not sure about the performance implications of this though; since you would be adding 100 extras as part of the bundle.
There could be a better way (perhaps make your pair a List<List<Double>> and then implement Parcelable) but I haven't tried any of it so I wouldn't suggest it.
double [][] tableCityPair = new double[100][100];
and then...
make intent it=....
then
put: `it.putExtra("size",tableCityPair.length)`
then:
for(i=0;i<tableCitypair.length;i++)
{
it.putExtra("table"+i,tableVityPair[i][]);
}
THEN in CLASS B
double [][] tableCityPairinB = new double[100][100];
for(i=0;i<getIntent().getExtras("size");i++)
{
double[i][]=getIntent().getExtras("table"+i);
}

Sending LinkedHashMap to intent

I want send LinkedHashMap to another Intent. But I don't known what method for extras is allowable.
Bundle extras = getIntent().getExtras();
LinkedHashMap<Integer, String[]> listItems = extras.get(LIST_TXT);
You cannot reliably send a LinkedHashMap as an Intent extra. When you call putExtra() with a LinkedHashMap, Android sees that the object implements the Map interface, so it serializes the name/value pairs into the extras Bundle in the Intent. When you want to extract it on the other side, what you get is a HashMap, not a LinkedHashMap. Unfortunately, this HashMap that you get has lost the ordering that was the reason you wanted to use a LinkedHashMap in the first place.
The only reliable way to do this is to convert the LinkedHashMap to an ordered array, put the array into the Intent, extract the array from the Intent on the receiving end, and then recreate the LinkedHashMap.
See my answer to this question for more gory details.
The best way is to convert it to ArrayList of the same type examble :
LinkedHashSet<Long> uniqueIds = new LinkedHashSet();
ArrayList<Long> ids = new ArrayList(uniqueIds);
Intent intent = new Intent(getContext(), UserStoryActivity.class);
intent.putParcelableArrayListExtra(FLAG_USERS_STORY_LIST_IDS, (ArrayList) ids);
startActivity(intent);
Thanks #David Wasser for pointing out this issue.
I have another approach is to use Gson to parse your whatever map to json string, then put into the intent. Less drama!
Code send:
gson.toJson(data)
Code get back:
Kotlin:
gson.fromJson<LinkedHashMap<Int, Int>>(
it.getStringExtra(ARG_DATA),
object : TypeToken<LinkedHashMap<Int, Int>>() {}.type
)
Java:
gson.fromJson(
it.getStringExtra(ARG_DATA),
new TypeToken<ArrayList<Mountain>>(){}.getType()
);

android parcelable string array

I have
ArrayList<String> ids = ArrayList<String>();
What would be the cleanest way to make it Parceleable? Apparently String itself is not parcelable, so Parcel.writeList(ids) is not working.
I was thinking to either parcelize ArrayList<Uri> or put array contents into a Bundle.
Convert your list to String[] and use Parcel.writeStringArray. Example here
This isnt parcelizing, but to put it in a bundle:
ArrayList<String> ids = new ArrayList<String>();
savedInstanceState.putStringArrayList("key",ids);

Categories

Resources