IssacZH.
IssacZH.

Reputation: 1477

Retrieve specific column of data and store it in string array

I got a sqlite database and i wanted to retrieve a specific column of data and store it into a string array. Inside the database there are two columns. There will be multiple row of data with the same username and I wanted to retrieve the user's "ContentPath" and store it into a string array. But I don't know how to retrieve that specific column data...

    public String[] get_contentByEmailID(String emailid){
    String[] returnMsg = null;
    helper = this.getReadableDatabase();

    Cursor c = helper.rawQuery("SELECT tableid, emailid, contentpath" +
            " from w_content where emailid='"+emailid"' ", null);



    int contentpathColumn = c.getColumnIndex("contentpath");


    if (c.moveToFirst()) {
        do {
            returnMsg = new String[2]; 

            String contentpath = c.getString(contentpathColumn);

            returnMsg[0] = emailid_sync;

            returnMsg[1] = contentpath;


        } while (c.moveToNext());
    }
    if (c != null && !c.isClosed()) {
        c.close();
    }
    if (helper!=null){
        helper.close();
    };
    return returnMsg;
}

When I called this function to retrieve the data. It comes up with emailid and contentpath.

String values[] = helper.get_contentByEmailID(SettingConstant.EMAIL);

Any comments will be appreciated.

Upvotes: 2

Views: 4504

Answers (1)

ariefbayu
ariefbayu

Reputation: 21979

The reason you got array filled with emailid and contentpath is, because you always reset the returnMsg on each row and fill it with such value. Since there will be varying row count, it is generally suggested that you use ArrayList, instead of building static length array.

To fix it, change:

String[] returnMsg = null;

to:

ArrayList<String> returnMsg = new ArrayList<String>();

And then, in your do{}, do something like this:

do {
    String contentpath = c.getString(contentpathColumn);
    returnMsg.add(contentpath);
} while (c.moveToNext());

Finally, change your return statement to:

return returnMsg.toArray();

Upvotes: 1

Related Questions