3

I want tofind the index of the custom array list. This is my custom array list:

private ArrayList<UserData> ListItems = new ArrayList<>();

UserData list = new UserData("list", "5", R.drawable.email_black, false);

UserData list1 = new UserData("list1", "3",R.drawable.text_msg, false);

UserData list2 = new UserData("list2", "2",R.drawable.phone_call, false);

ListItems.add(list);
ListItems.add(list1);
ListItems.add(list2);

I am doing like below but not getting the index .

int m = ListItems.indexOf("list1");

UserData obj = ListItems.get(m);
String name = obj.getName();

I need list1 in name string.

6
  • You will have to pass the userData object in listItems.indexOf() not the string in order to get the index. Commented Jul 21, 2016 at 6:21
  • can you explain how....? Commented Jul 21, 2016 at 6:23
  • 1
    That is Custom object not custom list. You have to pass ListItems.indexOf(list1), here list1 is a UserData object(Custom Object in your case). Commented Jul 21, 2016 at 6:23
  • As mentioned by Glenn passing the userData object is the right way to go, also if it is possible you could get items based on index. Commented Jul 21, 2016 at 6:23
  • @samir Read Saritha's comment Commented Jul 21, 2016 at 6:24

3 Answers 3

3

Iterator your array list to get your required data. Do something like below:

    for (int i = 0; i < ListItems.size(); i++) {
        String userListName = ListItems.get(i).getListName();
        if(userListName.equals("list1")){
            //Do something here
        }else{
            //Nthng to do
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

1

The indexOf method is based on the argument and the item in the list being equal. Since they are not (one is a UserData instance and the other is a String), you can't use indexOf. Instead, you'll have to implement this logic yourself:

private UserData getUserDataByName(String name) {
    for (UserData item : listItems) {
        if (item.getName().equals(name)) {
            return item;
        }
    }
    // Not found, return null;
    return null;
}

2 Comments

where to store return item ; UserData item = getUserDataByName("list1"); String name = item.getName(); it's wotking or'not.....?
@samir yes, that should work. If you want to be extra cautious, you should check item != null before calling item.getName() though.
1

In such a scenario, You can use HashMap also. Use HashMap<String,UserData> where String would be "list", "list1" etc.

Ex -

map.put("list", list);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.