vendredi 2 octobre 2015

How to display all contacts to layout without pressing any button

I am new to android and especially to sqlite so please bear with me.

I want to ask, how can I retrieve all the data from android DB and display them to android layout without pressing any button?

Here is my code from the database class:

 // Getting All Contacts
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    String selectQuery = "SELECT  * FROM " + TABLE_CS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setId(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setTime(Integer.parseInt(cursor.getString(2)));
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    return contactList;
}

but I am not sure how to get this list view to my MainActivity, what I have done is something like this:

listView = (ListView) findViewById(R.id.list_data);


    new Handler().post(new Runnable() {
        @Override
        public void run() {
            customAdapter = new CustomCursor(MainActivity.this, DB.getAllContacts());
            listView.setAdapter(customAdapter);
        }
    });

Which of course gives error because I am calling a non-static method from a static context. How should I call GetAllContacts from my MainActivity?

Aucun commentaire:

Enregistrer un commentaire