简体   繁体   中英

ArrayList<Object> to ArrayList<String>

I have made an ExpandableListView with ArrayList as groupItem and ArrayList as childItem:

public void setGroupData() {
    groupItem.add("TechNology");
    groupItem.add("Mobile");
    groupItem.add("Manufacturer");
    groupItem.add("Extras");

}

ArrayList<String> groupItem = new ArrayList<String>();
ArrayList<Object> childItem = new ArrayList<Object>();

public void setChildGroupData() {

    /**
     * Add Data For TecthNology
     */
    ArrayList<String> child = new ArrayList<String>();
    child.add("Java");
    child.add("Drupal");
    child.add(".Net Framework");
    child.add("PHP");
    childItem.add(child);

    /**
     * Add Data For Mobile
     */
    child = new ArrayList<String>();
    child.add("Android");
    child.add("Window Mobile");
    child.add("iPHone");
    child.add("Blackberry");
    childItem.add(child);
    /**
     * Add Data For Manufacture
     */
    child = new ArrayList<String>();
    child.add("HTC");
    child.add("Apple");
    child.add("Samsung");
    child.add("Nokia");
    childItem.add(child);
    /**
     * Add Data For Extras
     */
    child = new ArrayList<String>();
    child.add("Contact Us");
    child.add("About Us");
    child.add("Location");
    child.add("Root Cause");
    childItem.add(child);       

}

I want the if statement to trigger an action when a child is selected. However childItem is an object and if I put it like this, nothing happens when I press the "Java" child:

if(childItem.get(childPosition).toString().equals("Java")){

        iv.setImageResource(R.drawable.pic);    
}

When I tried with groupItem which is a string it worked, but not the way I wanted( it doesn't matter which item I press within group "TechNology" it will work)

if(groupItem.get(groupPosition).equals("TechNology")){

        iv.setImageResource(R.drawable.pic);
}

What am I doing wrong and how can I fix it?

ArrayList<Object> obj_array = new ArrayList<Object>();
//set this ArrayList ...
ArrayList<String> str_array = new ArrayList<String>();
for (int i = 0; i < obj_array.size(); i++)
{
   str_array.add((String)obj_array.get(i));
}

childItem is an array list of array lists, so the toString is calling the toString for an array list. More properly, you can declare childItem as an ArrayList<ArrayList<String>> object.

Your problem is childItem is an ArrayList of ArrayList of String objects ( List<List<String>> if you want), so your if conditions will always return false because you are comparing an ArrayList with a String object.

In order to fix it you should get the corresponding ArrayList<String> and check the String instances stored within.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM