将sqlite中的数据以列表形式放入hashmap中

时间:2012-08-20 09:38:52

标签: android sqlite list hashmap

public class ABC extends ListActivity {
static final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.abc_list);

    SimpleAdapter adapter = new SimpleAdapter(
            this,
            list,
            R.layout.abc_list_row,
            new String[] {"AAA","BBB","CCC"},
            new int[] {R.id.aa,R.id.bb, R.id.cc,}
            );

    add();
    setListAdapter(adapter);  
}

   private void add() {        

    DatabaseA databaseHelper = new DatabaseA(this);
    SQLiteDatabase db = databaseHelper.getReadableDatabase();

    Cursor c= db.rawQuery("select * from data", null);
    HashMap<String,String> temp = new HashMap<String,String>();  

    while(c.moveToNext()){
        Log.d("Debug", c.getString(2));
        temp.put("AAA", c.getString(1));
        temp.put("BBB", c.getString(2));
        temp.put("CCC", c.getString(3));
        list.add(temp);
    } 

    c.close();
    db.close();

    for (Map.Entry<String, String> entry : temp.entrySet()) {
        String xx= entry.getKey();
        String yy = entry.getValue();
        Log.d("data", xx+" : "+yy);
    }
}

我的Logcat:

 D/Debug(657): New york
 D/Debug(657): New moon
 D/data(657): AAA : Aug 20, 2012 3:57:02 PM
 D/data(657): BBB : New moon
 D/data(657): CCC : Title

我的问题是它总是遗漏了此列表中sqlite的第一个数据。此外,每当我按下按钮查看此列表时,它会将这些数据添加到此列表中,尽管它们已经存在。我只想以列表形式在sqlite中查看这些数据。任何解决这个问题的方法。感谢。

2 个答案:

答案 0 :(得分:1)

您需要在Map循环

中创建while
while(c.moveToNext()){
    Map<String,String> temp = new HashMap<String,String>();  
    Log.d("Debug", c.getString(2));
    temp.put("AAA", c.getString(1));
    temp.put("BBB", c.getString(2));
    temp.put("CCC", c.getString(3));
    list.add(temp);
} 

答案 1 :(得分:0)

像这样添加游标moveToFirst():

Cursor c= db.rawQuery("select * from data", null);
HashMap<String,String> temp = new HashMap<String,String>();  
c.moveToFirst();
while(c.moveToNext()){
    Log.d("Debug", c.getString(2));
    temp.put("AAA", c.getString(1));
    temp.put("BBB", c.getString(2));
    temp.put("CCC", c.getString(3));
    list.add(temp);
} 

请点击按钮后发布源代码!