简体   繁体   中英

Android SQL only returns one column

I got a SQL database containing the following layout:

SQL表

The table is called messages with around 5 columns.

I created an Cursor which should get all values from both columns using this:

public List<String> getContacts(SQLiteDatabase db) {
    List<String> List = new ArrayList<String>();
    // Select All Query
    String selectQuery = "SELECT `from`,`to` FROM messages";
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            List.add(cursor.getString(1));
        } while (cursor.moveToNext());
    }
    return List;
}

And here I add the values to a ListView:

DatabaseHelper dbHelper = new DatabaseHelper(
            this.getApplicationContext());

    newDB = dbHelper.getWritableDatabase();

    List<String> all = dbHelper.getContacts(newDB);
    if (all.size() > 0) // check if list contains items.
    {

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, all));

    } else {
        Toast.makeText(ConversationsList.this, "No items to display", 1000)
                .show();
    }

And yes values gets added, but only the me which is very weird. What am I doing wrong?

EDIT: Solved it by changing this:

if (cursor.moveToFirst()) {
            do {
                List.add(cursor.getString(0));
                List.add(cursor.getString(1));
            } while (cursor.moveToNext());
        }

To:

if (cursor.moveToFirst()) {
            do {
                List.add(cursor.getString(0));
                List.add(cursor.getString(1));
            } while (cursor.moveToNext());
        }

Your List<String> List and

do {
    List.add(cursor.getString(1));
    } while (cursor.moveToNext());  

are causing the problem.

If you cannot alter the List type,

do {
     List.add(
            cursor.getString(1) +","
            cursor.getString(1) +","
            ...
            +cursor.getString(n));
    } while (cursor.moveToNext());

will fetch comma delimited values of each record into the String. You can split the string and use the values individually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM