Android - 将sqlite数据库中的值加载到arraylist

时间:2011-03-30 05:51:43

标签: android sqlite arraylist

我是android新手。我有一个使用SQLite DB的应用程序。 我需要将值从数据库推送到类型为object的arraylist。 我使用的代码在这里给出。

 private ArrayList<objectname> objectList  = new ArrayList<objectname>();
 //function used to get values from database
   public ArrayList<objectname> getResults() {

    MyDb db = new MyDb(this); //my database helper file
    db.open();
    Cursor c = db.getAllValues(); //function to retrieve all values from a table- written in MyDb.java file
    if (c.moveToFirst())
    {
        do {         
            String date = c.getString(c.getColumnIndex("date"));

            try
            {
                ob = new objectname();
                ob.setDate(c.getString(c.getColumnIndex("date")));// setDate function is written in Class file
                objectList.add(ob);
            }
            catch (Exception e) {
             Log.e(MY_DEBUG_TAG, "Error " + e.toString());
            }

         } while (c.moveToNext());
    }
       db.close();
       return objectList;
}

这不能正常工作。没有显示任何错误,但我没有得到arraylist objectList

的值

请帮帮我..谢谢提前..

3 个答案:

答案 0 :(得分:7)

试试这个:

private ArrayList<objectname> objectList  = getResults();

private ArrayList<objectname> getResults() {

    MyDb db = new MyDb(this); //my database helper file
    db.open(); 

    ArrayList<objectname> resultList = new ArrayList<objectname>();


    Cursor c = db.getAllValues(); //function to retrieve all values from a table- written in MyDb.java file
    while (c.moveToNext())
    {
        String date = c.getString(c.getColumnIndex("date"));

        try
        {
            ob = new objectname();
            ob.setDate(date);// setDate function is written in Class file
            resultList.add(ob);
        }
        catch (Exception e) {
            Log.e(MY_DEBUG_TAG, "Error " + e.toString());
        }

    }

    c.close();

    db.close();
    return resultList;
}

答案 1 :(得分:2)

我在使用游标从数据库中检索值并在屏幕上显示时遇到了类似的问题。以下解决方案对我有用..

            Cursor cur = db.getAllValues();
            int index = c.getColumnIndex("date");
    cur.moveToFirst();

    while (cur.isAfterLast() == false) {
        System.out.println(cur.getString(index)); // For debug purposes
        String date = cur.getString(index);
        try {
            ob = new objectname();
            ob.setDate(date);
            resultList.add(ob);
        } catch (Exception e) {
            Log.e(MY_DEBUG_TAG, "Error " + e.toString());
        }
        cur.moveToNext();
    }
    cur.close();

答案 2 :(得分:1)

您的查询可能是空白而moveToFirst返回false。

如何在c.getCount()声明之前记录if的值?