SAM Bhadani
SAM Bhadani

Reputation: 831

What's wrong with my code while populating Listview from SQLite?

Following s my Code to display data to listview from database. But it will not work and crash my application.please Give perfect solution for my this problem.

My Code......

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

    }

Upvotes: 0

Views: 371

Answers (2)

Chirag
Chirag

Reputation: 56925

Please Try Below Code

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

Upvotes: 1

Cristian
Cristian

Reputation: 200090

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

The problem is that you are closing the cursor in the first iteration.

Give perfect solution for my this problem.

You look like my boss, excepts that he pays 20 dollars per hour....

Whatever, there are a lot of things which are bad in your code, mostly because you don't understand how a cursor works:

  • Why do you call moveToFirst on each iteration? Does it make sens for you?
  • Why do you close the cursor inside the for?
  • Why do you set the adapter on each iteration?
  • Why do you use an array adapter instead of CursorAdapter?

Upvotes: 2

Related Questions