Convert String Objects in ArrayList to Array of Arrays
I have a menu structure that outputs a list of favourite configuration items.
In the Android SDK in the Views examples there is a view example that I would like to use called ExpandableList1.java.
In order to use the view I have to pass a String[] groups
structure and a String[][] children
structure.
I have no problem converting a list of strings from the menu objects to an array using groups.toArray
. The problem that I have is with converting the favourites items to an array of arrays. The favourite items are array lists contained in the menu object.
The relevant parts of the code is pasted here. First we call MyExpandableListAdapter with an array of strings:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> favouriteMenuList = Main.menuList.getFavouriteMenusFullPath();
mAdapter = new MyExpandableListAdapter(favouriteMenuList);
setListAdapter(mAdapter);
registerForContextMenu(getExpandableListView());
}
Next MyExpandableListAdapter and it's constructor is show where the array conversion happens:
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
// Sample data set. children[i] contains the children (String[]) for groups[i].
// private String[] groups = { "People Names", "Dog Names", "Cat Names", "Fish Names" };
private String [] groups;
private String[][] children = {
{ "Arnold", "Barry", "Chuck", "David" },
{ "Ace", "Bandit", "Cha-Cha", "Deuce" },
{ "Fluffy", "Snuggles" },
{ "Goldy", "Bubbles" }
};
public MyExpandableListAdapter(ArrayList<String> groups) {
this.groups = groups.toArray(new String[groups.size()]);
}
As you can see in the above code snippet there is no problem converting to St开发者_如何学Goring[] groups
. My idea is to iterate over the menu objects, extract the list of favourites, and then?? How would I build a dynamic array in Java since array sizes are so fixed.
Here is the outer loop I have in mind:
public ArrayList<FavouritesObject> getFavouriteItems() {
ArrayList<FavouritesObject> favouritesList = new ArrayList<FavouritesObject>();
for (MenuObject m : allMenusList) {
if (m.isFavourite) {
favouritesList.add(m.getFavouriteItems());
}
}
return favouritesList;
}
Use an ArrayList (res
) to dynamically add items and convert it to an Array (mString
).
ArrayList<String> res = new ArrayList<String>();
res.add("Item");
String[] mString = (String[]) res.toArray(new String[res.size()]);
Assuming for example that you have a List<Menu>
and each Menu
can return a List<String>
of favourites, I believe you want this:
String[][] children = new String[menus.size()][];
for (int i = 0; i < menus.size(); i++) {
List<String> favourites = menus.get(i).getFavourites();
children[i] = favourites.toArray(new String[favourites.size()]);
}
精彩评论