Monday, 30 April 2012

How to show the data saved in the database in a List View

There comes many aspects where we cant to show the database data in a List View. So here is the easiest way to get it out.

For this case we have to use SimpleCursor Adapter as :-

public class GetList extends Activity {

DBadapter db;
ListView lv;
@Override
public void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);
setContentView(R.layout.data_list);

db = new DBadapter(this);
getData();

}

public void getData(){


try {
db.open();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

lv = (ListView)findViewById(R.id.dbList);
List<String> items = new ArrayList<String>();
Cursor c = db.getAllData();
    c.moveToFirst(); 
    
    ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.row_for_db, c, new String[]{"_id", "userName", "Password"}, new int[]{R.id.ID,R.id.name,R.id.Password} );
    lv.setAdapter(adapter);
    
}  


where getAllData() is a function in DBAdapter class and it is as follows :-

public Cursor getAllData(){
 
return db.query(TABLE_NAME, new String[] {_id,userName,Password}, null, null, null, null, null);
}


This is how you can get the data from a database in a List View.

No comments:

Post a Comment