2

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.

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

I got one more question. In the end my function turned into public Object[] get_content(String emailid). What does Object[] different from normal array?
Object[] notation mean that it is an array of Object. [] mean array. So, String[] mean an array of String and so on. Read here for more: docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html | Object is the parent of all object in Java.

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.