2009-09-01 378 views
1

我从Cursor获取String数据,但我不知道如何将其转换为Array。我怎样才能做到这一点?将字符串转换为数组(android)

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

回答

4

你可以只包mTitleRaw到一个单一的元素阵列像这样:

mString = new String[] { mTitleRaw }; 

更新: 你可能需要的是所有行添加到一个数组,你可以这样做一个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()]); 
+1

你确定这是好的吗?你的第一个元素被跳过了,不应该是:for(c.moveToFirst();!c.isAfterLast(); c.moveToNext()) – Pentium10 2010-03-04 21:53:19

1

正如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(); 
    } 

正如我所说的,这段代码将包含游标中的第一个元素。