Reputation: 11141
I have a problem related to storing data dynamically in two Dimensional String Array
, String[][]
.
I am dynamically storing data in the String[i][j]
array. Here the first index's value is fixed i.e. i=3
, but second index's value is different for all rows.
for example, I am getting values like this,
String arrElements[][] = {
{"1"},
{"abc", "xyz", "lkm", "pwd", "srt", "qwert"},
{"1234", "3456"}
};
I am getting values something like this. i.e there is only 1 value in the first row, any number of values in the second row and in the third row.
If I go like this,
int i = 0, j = 0;
String arrElements[][] = {};
arrElements= new String[3][25];
//What size should I define here.
arrElements[0][0] = "Sahil";
if (a == 0) { //Its just a logical representation of what I might be doing.
// Store the value in second row
arrElements[1][i] = a;
i++;
}
if (a == 1) {
// Store the value in third row
arrElements[2][j] = a;
j++;
}
Now, I am setting these values in the expandable list View
. If the number of values in any of the rows exceeds the size specified, it gives ArrayOutOfBoundException
. and if the size is less than 25, it shows empty rows.
Now, I dont want to give hard coded size limit for the array indexes. Is there any better way to deal with it.
Upvotes: 0
Views: 1432
Reputation: 9190
You can use whatever data structures you like.
In the ExpandableListAdapter
that you pass to the view, just be sure you return correct values from getGroupCount
and getChildrenCount
. In getGroup
and getChild
, return the appropriate data from whatever backing structure you use (database cursor, list, list of lists, etc.).
One useful structure for this type of list is a Map<GroupData, List<ChildData>>
. This might be as simple as a HashMap<String, ArrayList<String>>
if the item text is the only data you have.
Upvotes: 1
Reputation: 7388
As a first remark: Are you sure a String[][]
is the right data structure for what you want to achieve? There is a whole bunch of Collection
classes that might be more suitable (ArrayList
to name the most obvious).
If you really want to proceed with String[][]
you can't define the length of the sub-arrays upfront but have to declare it per row:
String[][] foo = new String[4][];
foo[0] = new String[1];
foo[1] = new String[2];
// ....
But as I said you might be much happier with a nested ArrayList
which resizes dynamically:
ArrayList<ArrayList<String>> foo = new ArrayList<ArrayList<String>>();
// Do the following for each row
foo.add(new ArrayList<String>>());
// Do the following to append data in row i
foo.get(i).add("new string");
// Do the following to retrieve column j in row i
foo.get(i).get(j);
Depending on what you actually want to store, other data structures might be much more suited.
Upvotes: 1