Reputation: 262
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
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
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
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
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
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