我想从我的数据库中获取详细信息,并将它们放入List中。 - 在循环内部,我可以看到List获取详细信息(列表大小增加,列表中的值为true)。 - 循环结束后,我检查列表并找到它的大小是我想要的,但字段值是null! List变量是在函数外定义的(即它的类字段)。 看到: 循环开始 获得游标价值 将值放入列表中 检查列表值:值是否正常。 循环结束。
这是代码:
List<Bundle> friends = new ArrayList<Bundle>();
public List<Bundle> getAllFriends()
{
SQLiteDatabase db = this.getWritableDatabase();
String Check="Select * From Friends";
Cursor c = null;
String name ="";
String ID ="";
String OnlineStt ="";
String photoUrl ="";
String friendSince ="";
Bundle det=new Bundle();
if(db!=null)
c=db.rawQuery(Check,null);
if(c!=null)
if(c.isBeforeFirst()&&c.getCount()>0) // if there is result/s
{
c.moveToFirst();
do
{
name = c.getString(0);
ID = c.getString(1);
OnlineStt = c.getString(2);
photoUrl = c.getString(3);
friendSince = c.getString(4);
det.putString("name",name);// fill the bundle
det.putString("ID",ID);
det.putString("OnlineStt",OnlineStt);
det.putString("photoUrl",photoUrl);
det.putString("friendSince",friendSince);
friends.add(det);// put the Bundle in the list
Log.d("AddFriend---","name in the list: "+friends.get(friends.size()-1).getString("name")); // get true value
Log.d("AddFriend---","List size="+friends.size()); // size increased // another log.d showed me the current value
det.clear(); // clear the Bundle
} while(c.moveToNext());
if(friends.size()<1)
{ Log.d("FUN","no Friends found!") ;
return null;}
} else return null;
for (int x=0;x<friends.size()-1;x++)
Log.d("AddFriend---","name of friend in list: "+friends.get(x).getString("name")); // I get null
Log.d("AddFriend---"," list Size after the loop end "+friends.size()); // I get the true size
return friends;
.... 记录结果:
AddFriend---﹕ name of friend in list: John
D/AddFriend---﹕ List size=1
D/AddFriend---﹕ name of friend in list: Fadi
---- after the loop:
D/AddFriend---﹕ List size=2
D/AddFriend---﹕ name of friend in list: null
D/AddFriend---﹕ list Size after the loop end 2
答案 0 :(得分:0)
你不应该打电话
det.clear();
但您应该在每次迭代时创建一个新实例(Bundle det = new Bundle()
)