将字符串转换为数组 (android)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1360513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert String to Array (android)
提问by Dennie
I get a String data from Cursor, but I don't know how to convert it to Array. How can I do that?
我从 Cursor 得到一个字符串数据,但我不知道如何将它转换为数组。我怎样才能做到这一点?
String[] mString;
for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()) {
mTitleRaw = cursor.getString(cursor.getColumnIndex(SBooksDbAdapter.KEY_TITLE_RAW));
}
mString = mTitleRaw ????
回答by marshall_law
You could just wrap mTitleRaw into a single element array like so:
您可以将 mTitleRaw 包装成一个单一元素数组,如下所示:
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 执行此操作,然后变异回 String[] 数组,如下所示:
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()]);
回答by GGCO
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:
正如 Pentium10 指出 marshall_law 的代码有一个错误。它跳过光标中的第一个元素。这是一个更好的解决方案:
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.
正如我所说,这段代码将包含光标中的第一个元素。