Reputation: 831
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
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
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:
moveToFirst
on each iteration? Does it make sens for you?CursorAdapter
?Upvotes: 2