Wednesday, August 27, 2014

Read Multiple Rows from Android SQLite Helper

This blog is in continuity with my previous three posts which were related to creation of a database helper class, insertion of new data entry intothe table and selection of a record from the database. After creating database in android and open the connection we had to add entries into the database. And after that we have seen how to select a single record from the database.

But now it's time to move to more advance level of retrieving records from the table. And now we must need to select multiple records from the table and populate it to the collection of POJO. (PreferenceInfo.java)

In order to retrieve a stored record into database we had to provide an identity value which will search the record into table against that id. But, here we are planning to search all the records from the database.

A List is a collection which maintains an ordering for its elements. Every element in the List has an index. Each element can thus be accessed by its index, with the first index being zero. Normally, Lists allow duplicate elements, as compared to Sets, where elements have to be unique.
public List<PreferenceInfo> getAllUsers(){
List<PreferenceInfo> preferenceInfos = new ArrayList<PreferenceInfo>();

This time query must not contain any kind of selection criteria and should remain wild.
String query = "select * from " + REGISTER_TABLE;

Now, we must need a connection in order to execute this query. This time we are planning to executing a raw query so will need a Writable Database object.
SQLiteDatabase db = this.getWritableDatabase();

Here, we must need to store the results into the Cursor so that we can retrieve every single row and assign it to the POJO. Once things will be done we will start adding it to the list after each row population.
Cursor cursor = db.rawQuery(query, null);

Iterating over each row, building POJO and adding it to list
PreferenceInfo prefInfo = null;

Move the cursor to the first row. This method will return false if the cursor is empty.
if(cursor.moveToFirst()){
do{

Refreshing object in each iteration and assigning new values from the cursor.
prefInfo = new PreferenceInfo();
prefInfo.setSecurityNumber(Integer.parseInt(cursor.getString(0)));
prefInfo.setEmail(cursor.getString(1));
prefInfo.setPassword(cursor.getString(2));
prefInfo.setUserName(cursor.getString(3));
prefInfo.setMobileNumber(cursor.getString(4));
prefInfo.setKeyMessage(cursor.getString(5));

Adding each object to the list
preferenceInfos.add(prefInfo);
}while(cursor.moveToNext());

Move the cursor to the first row. This method will return false if the cursor is empty. And after completion of iteration we will simply return the list to the method.


  return preferenceInfos;

If you find it helpful kindly click the donate button on the top of page. Also added an attachment of the files used in this blog which can bee seen by clicking on links below:

No comments:

Post a Comment