【问题标题】:What's wrong with my code while populating Listview from SQLite?从 SQLite 填充 Listview 时我的代码有什么问题?
【发布时间】:2011-03-11 05:41:42
【问题描述】:

按照我的代码将数据从数据库显示到列表视图。但它不会工作并使我的应用程序崩溃。请为我的这个问题提供完美的解决方案。

我的代码......

        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.deletestudent);
           // DisplayStudent();


        ArrayList<String > arrlst=new ArrayList<String>();
         ListView lst_stu=(ListView) findViewById(R.id.ListView01);

            db.open();
            Cursor cur=db.GetStudent();

            for (int i=0;i<cur.getCount();i++)
            {
                cur.moveToFirst();

                String stunm=cur.getString(1);
                arrlst.add(1, stunm);
                lst_stu.setAdapter((ListAdapter) arrlst);

                 db.close();
            }

    }

【问题讨论】:

  • 为什么要在 for 循环中设置适配器并关闭数据库?
  • 谢谢,现在我将更改我的代码。

标签: android sqlite android-listview


【解决方案1】:
        for (int i=0;i<cur.getCount();i++)
        {
            cur.moveToFirst();

            String stunm=cur.getString(1);
            arrlst.add(1, stunm);
            lst_stu.setAdapter((ListAdapter) arrlst);

             db.close();
        }

问题是您在第一次迭代中关闭了光标。

为我的这个问题提供完美的解决方案。

你看起来像我的老板,除了他每小时支付 20 美元......

无论如何,您的代码中有很多不好的地方,主要是因为您不了解游标的工作原理:

  • 为什么每次迭代都调用moveToFirst?这对你有意义吗?
  • 为什么要在for里面关闭光标?
  • 为什么每次迭代都设置适配器?
  • 为什么要使用数组适配器而不是 CursorAdapter

【讨论】:

  • 对不起亲爱的。但是人们在犯错时会学到一些东西。
  • 现在我的问题得到了解决,并且由于您的指导,它会起作用。再次感谢。
  • 哦,是的...这是一种试错方法。没关系,但您可以尝试另一种更好的方法来学习:阅读。如果有一天你学会了阅读,你不仅会学到一些东西,还会节省很多时间。
【解决方案2】:

请尝试以下代码

try
    {
        Cursor cursor = null;

        db.OpenDatabase();
        cursor = db.GetStudent();

        // Here if condition check wheather the cursor returns record or not.
        // If cursor has some records then it will return non zero number .

        if (cursor.getCount() != 0) 
        {
            // Here if condition check wheather the cursor move to first record or not
            // If it moves to first record then it will return true.
            if (cursor.moveToFirst()) 
            {
                do 
                {
                    arrlst.add(cursor.getInt(cursor.getColumnIndex("your_field_in_database")).trim());

                }while (cursor.moveToNext());
            }
        }

        cursor.close();
        db.closeDatabase();
        lst_stu.setAdapter((ListAdapter) arrlst);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

【讨论】:

  • 亲爱的,它不会给出任何错误,但它不会在列表视图中显示数据。
  • 我正在输出我的那个问题。
  • 我在使用 Eclipse 配置 phonegap 时遇到了另一个问题。如果有任何解决方案,请发送给我..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-28
相关资源
最近更新 更多