1
List<Event> eventList = new ArrayList();
String selectQuery = "SELECT  * FROM " + TABLE_EVENTS+" WHERE " +  KEY_TYPE+" = \""+type_+"\"";
db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
            do {

                // event.setID(Integer.parseInt(cursor.getString(0)));
                event.setName(cursor.getString(1));

                event.setDescription(cursor.getString(7));
                event.setLink(cursor.getString(4));
                event.setLocation(cursor.getString(2));
                event.setType(cursor.getString(3));
                event.setStartDate(cursor.getString(5));
                event.setEndDate(cursor.getString(6));

                // Adding contact to list
                eventList.add(event);
               event.writeSc(event);

            } while (cursor.moveToNext());
        }
 db.close();
        return eventList;
    }

Here when i use new Arraylist at beginning, it doesnot work. The values become always same when i print. But when i do

List<Event> eventList = new ArrayList<>();

it works.

1 Answers1

-1

The issue is not the initialization of the List. Your problem is adding the same instance again and again to the List, since you don't create a new Event instance for each element you add to the List.

        do {
            event = new Event; // here's what you are missing
            event.setName(cursor.getString(1));
            ...

As for the List initialization,

List<Event> eventList = new ArrayList<>();

is more correct, since it uses the generic type instead of the raw ArrayList type.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • i am sorry you got thumb down because of me. I wish i could upvote. But i cant understand the thing, it workend when i add that definition you wrote. But lets think my code, each time i define different name location and i send same event object maybe has different names, how they are same? i cant understand. –  Dec 20 '15 at 15:32
  • @dog Don't worry about the downvote. I don't. As for the `event` object - if you add the same `event` object to the List, each time you modify the name (or any other properties), all the elements in the List are updated, since all the elements refer to the same object. – Eran Dec 20 '15 at 15:35
  • oh what an interesting thing. thank you caring and answering. good bye –  Dec 20 '15 at 16:08