2

i am having the following code for display the contacts in my application. i am having the problem to display the contacts. my array(from) get only one value from database but in database many values are there. How to get the all values from database.

mydatabasecode:

public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

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

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setPhoneNumber(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
}

GetvalueFromDb code:

 List<Contact> contacts = db.getAllContacts();
    for (Contact cn : contacts) {
        from = new String[] { cn.getName()};
        Toast.makeText(getApplicationContext(), ""+Arrays.toString(from), Toast.LENGTH_LONG).show();

    }
note = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_edit,from);
        lv.setAdapter(note);

2 Answers 2

5

You are making from only a single string, not a string array to apply to the array adapter. Try the following:

List<Contact> contacts = db.getAllContacts();
ArrayList<String> from = new ArrayList<String>;
for (Contact cn : contacts) {
    from.add(cn.getName());
    Toast.makeText(getApplicationContext(), ""+Arrays.toString(from), Toast.LENGTH_LONG).show();

}
note = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_edit, from);
    lv.setAdapter(note);
Sign up to request clarification or add additional context in comments.

Comments

1

because your initializing from array in loop and last time when loop runs you gets that last single value

you can try

List<Contact> contacts = db.getAllContacts();
from = new String[contacts.size()];
int i=0;
for (Contact cn : contacts) {
from[i]=cn.getName();
i++;             
        Toast.makeText(getApplicationContext(), ""+Arrays.toString(from), Toast.LENGTH_LONG).show();

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.