Ghorbanzadeh
Ghorbanzadeh

Reputation: 262

Android - Remove an item from arraylist by its ID

I have an arraylist in my adapter ( RecyclerView ) .

I have to delete an item from array list by its ID :

public static ArrayList<News> newsList = new ArrayList<News>();

I filled array list like below :

News n = new News();
n.id = data.getString("from_user_id");
n.comments = data.getString("message");
n.title = data.getString("name");
n.time = time;
newsList.add(n);

I want to remove an item from this list by its id ( n.id ) value .

How can i do this ?

Upvotes: 3

Views: 7284

Answers (5)

M.Bilal Murtaza
M.Bilal Murtaza

Reputation: 1973

This is simple guys no need to check index etc suppose ItemList is list of n element and you want to remove itme base on id so u can use these code; Replace your condition id insted of your id;

for(Object item : ItemList)
  if(item.id == your id)
     ItemList.remove(item);

Upvotes: 0

Manohar
Manohar

Reputation: 23404

Try something like this

public deleteItemById(int Id){
      for(int i=0;i<newsList.size();i++){
         if(newsList.getItem(i).getid()==Id){
            newsList.remove(i);
          }
     } 
}

Upvotes: 2

user6303614
user6303614

Reputation:

Try this, surly this will help you

for(int i = 0 ; i < "YOURLIST.size();" ; i++){
    if("IDTOREMOVE".equalsIgnoreCase(REALID){
        YOURLIST.remove(i);
    }
}

Upvotes: 1

Abhishek Jaiswal
Abhishek Jaiswal

Reputation: 628

You can do like this

for(int i = 0 ; i < newsList.size() ; i++){
        if("yourId".equalsIgnoreCase(newsList.get(i).id)){
            newsList.remove(i);
        }
    }

Upvotes: 8

Akshay Bhat &#39;AB&#39;
Akshay Bhat &#39;AB&#39;

Reputation: 2700

Loop through list and check if id matches and remove. Like :

public static ArrayList<News> newsList = new ArrayList<News>();
News newsToRemove;
for(News news : newsList) {
    if(news.getId() == yourId) {
        newsToRemove = news;
        break;
    }
}
if(newsToRemove != null) {
    newsList.remove(newsToRemove);
}

Upvotes: 3

Related Questions