Convert String to Array (android)

2019-03-22 07:00发布

问题:

I get a String data from Cursor, but I don't know how to convert it to Array. How can I do that?

String[] mString;
for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()) {
   mTitleRaw = cursor.getString(cursor.getColumnIndex(SBooksDbAdapter.KEY_TITLE_RAW));
}
mString = mTitleRaw ????

回答1:

You could just wrap mTitleRaw into a single element array like so:

mString = new String[] { mTitleRaw };

Update: What you probably want is to add all the rows to a single array, which you can do with an ArrayList, and mutate back to a String[] array like so:

ArrayList strings = new ArrayList();
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
   String mTitleRaw = cursor.getString(cursor.getColumnIndex(SBooksDbAdapter.KEY_TITLE_RAW));
   strings.add(mTitleRaw);
}
Sting[] mString = (String[]) strings.toArray(new String[strings.size()]);


回答2:

As Pentium10 pointed out marshall_law's code has a bug in it. It skips the first element in the cursor. Here is a better solution:

    ArrayList al = new ArrayList();
    cursor.moveToFirst();
    while(!cursor.isAfterLast()) {
        Log.d("", "" + cursor.getString(cursor.getColumnIndex(ProfileDbAdapter.KEY_PROFILE_NAME)));
        String mTitleRaw = cursor.getString(cursor.getColumnIndex(ProfileDbAdapter.KEY_ID));
        al.add(mTitleRaw);
        cursor.moveToNext();
    }

As I said, this code will include the first element in the cursor.