Convert String to Array (android)

徘徊边缘 提交于 2019-12-21 03:01:21

问题


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.



来源:https://stackoverflow.com/questions/1360513/convert-string-to-array-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!