4

I want to display column names with column values in the Listview using cursor. My present code shows only the column values.

public void openAndQueryDatabase() {

    db = openOrCreateDatabase( "mydatabase.db", SQLiteDatabase.CREATE_IF_NECESSARY , null ); 

    Cursor cursor = db.rawQuery("select * from "+ table + " where name='"+ name + "'",  null);


    int count = cursor.getColumnCount();

    if (cursor!=null )
    { 

        if  (cursor.moveToFirst())
        {
            do 
            {
                 for (int i =0 ; i< count; i++)
                {
                String data = cursor.getString(i);
                details.add(data);
                }
            } 
            while (cursor.moveToNext()); 
        } 

         }
}
2
  • use cursor.getColumnName(columnIndex) Commented Apr 19, 2014 at 8:37
  • You don't really need to do a rawquery, you could just use the wrapper methods. Commented Apr 19, 2014 at 8:39

4 Answers 4

2

In this case you should use hashmap

for (int i =0 ; i< count; i++)
{
    String data = cursor.getString(i);
    String column_name = cursor.getColumnName(i);

    HashMap<String,String> map = new HashMap<String,String>();
    map.put("column_value",data);
    map.put("column_name",column_name);

    details.add(map); //change the type of details from ArrayList<String> to arrayList<HashMap<String,String>>
}
Sign up to request clarification or add additional context in comments.

2 Comments

you should edit your post instead of add another answer
this site allows to answer more than once. Right? therefore i did that.
2

Use getColumnName(int columnIndex) to get the name of the row for a given index.

1 Comment

one liner: DatabaseUtils.cursorRowToContentValues
1

Use this.

 for (int i =0 ; i< count; i++)
  {
      String data = cursor.getString(i);
      String column_name = cursor.getColumName(i);
      details.add(data);
  }

1 Comment

This will add only column values to the listview. How to display both of them together?
0

Simply retrieve String array with names like that:

cursor.getColumnNames()

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.