Abdul.Moqueet
Abdul.Moqueet

Reputation: 1067

list.contains() is not working in android

list.contains is not working. Here is my list which gets data from database.

////////List/////////////////
public List<Comment> getAllComments() {
        List<Comment> comments = new ArrayList<Comment>();

        Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
                allColumns, null, null, null, null, null);

        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            Comment comment = cursorToComment(cursor);
            comments.add(comment);
            cursor.moveToNext();
        }
        // make sure to close the cursor
        cursor.close();
        return comments;
    }
/////////////////////////////////////////////





    datasource = new CommentsDataSource(this);
        datasource.open();
        final List list;
        list = datasource.getAllComments();

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
if(list.contains("Hello")){
                    Toast.makeText(getApplicationContext(), "List Contains data", Toast.LENGTH_SHORT).show();
                } ///////Here it always return false///////
else{
 Toast.makeText(getApplicationContext(), "Data not found", Toast.LENGTH_SHORT).show();
}
            }
        });
}
////////////////////////////////////////////////////

My list contais Hello but i don't know why its not working. & sorry if it is already asked. The thing is i want some example code, regarding my codes Thanks in advance.

Upvotes: 2

Views: 6794

Answers (2)

Ajay Sainy
Ajay Sainy

Reputation: 379

You can do something like this :

boolean contains = false;
        for (Comment c : list) {
            if (c.text.equals("H")) 
                contains = true;
        }

Upvotes: 1

Jose Angel Maneiro
Jose Angel Maneiro

Reputation: 1316

I think that you have to override equals() method inside Comment class. Something like

 @Override
 public boolean equals(Object obj) {
     if (this.message.equals(((Comment)obj).getMessage()) {
         return true;
     }

     return false;
 }

In this sample, message would be the property of your class that you would like to compare, and you could do it as follows

if(list.contains(new Comment("Hello")){
   ...

Regards!

Upvotes: 8

Related Questions