Eric
Eric

Reputation: 1557

Android trouble getting all rows data

I am having trouble to get all rows data from sql.

DatabaseHandler.java

public HashMap<String, String> getChannelDetails(){
    HashMap<String,String> channels = new HashMap<String,String>();
    String selectQuery = "SELECT  * FROM " + TABLE_CHANNEL;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            channels.put("title", cursor.getString(1));
            channels.put("url", cursor.getString(2));
            channels.put("create_at", cursor.getString(3));
        } while (cursor.moveToNext());
        Log.d("SELECT", channels.toString());
        Log.d("Count", Integer.toString(cursor.getCount()));
    }

    cursor.close();
    db.close();
    // return channels
    return channels;
}

Showresult.java

for(int i = 0; i < 13; i++){
         HashMap<String, String> allchannel = db.getChannelDetails(); 
         String id = allchannel.get("id");
         String title = allchannel.get("title");
         String url = allchannel.get("url");
         String date = allchannel.get("created_at");
         titles[i] = title;
         Toast.makeText(context,titles[i]+" "+url+" "+ date, Toast.LENGTH_SHORT).show();
         }

The cursor.getCount() have 13, however the output show only last row data repeatedly.

Upvotes: 0

Views: 321

Answers (1)

jeet
jeet

Reputation: 29199

change your method to following:

public ArrayList<HashMap<String, String>> getChannelDetails(){
ArrayList<HashMap<String, String>> list=new ArrayList<HashMap<String, String>>();
    String selectQuery = "SELECT  * FROM " + TABLE_CHANNEL;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            HashMap<String,String> channels = new HashMap<String,String>();

            channels.put("title", cursor.getString(1));
            channels.put("url", cursor.getString(2));
            channels.put("create_at", cursor.getString(3));
            list.add(channels);
        } while (cursor.moveToNext());
        Log.d("Count", Integer.toString(cursor.getCount()));
    }

    cursor.close();
    db.close();
    // return channels
    return list;
}

now use this list to iterate through the results.

Upvotes: 2

Related Questions