Read One Record from SQLite Android Helper
This blog is in
continuity with my previous two posts which was related to creation of a database helper class and insertion of new data entry into the table. After creating database in android and open the connection we
had to add entries into the database. But, as we are already done with the insertion of records into the table. So, now it's time to search for the added record.
So, here we will use PreferenceInfo POJO for assigning retrieved values to the object.
in order to retrieve
a stored record into database we must need to provide an identity
value which will search the record into table against that id.
public PreferenceInfo getUser(int id){
As I have already
mentioned in my previous two blogs; we must need to get a
readabledatabase object because here we only need to read a database.
SQLiteDatabase db=null;
// 1. get reference to readable DB
try{
db = this.getReadableDatabase();
}catch (Exception e){
Toast.makeText(currentContext, "database cannot be opened", Toast.LENGTH_LONG);
}
Now like the
database we must need to initialize the cursor. Cursor interface
provides random read-write access to the result set returned by a
database query.
So, now we must need to build query:
Cursor cursor =
db.query(REGISTER_TABLE, // a. table
COLUMNS, // b. column names
SECURITY_NUMBER +" = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
Now, we must need to
check for the cursor, if results will be returned then cursor will be
populated else it will remain null.
if (cursor != null)
after validating the
cursor, we must need to move the cursor to the first row. This method
will return false if the cursor is empty. Here, we are retrieving
only one record because we know that for each identity only one
record exist into the table.
cursor.moveToFirst();
Now we must need to
populate the data from table into the POJO and then return the object
into that method.
PreferenceInfo preferenceInfo = new PreferenceInfo();
Now we will get the
values from the zero-based index of the target column and will set
into the relevant property of POJO using the setters.
preferenceInfo.setSecurityNumber(Integer.parseInt(cursor.getString(0)));
preferenceInfo.setEmail(cursor.getString(1));
preferenceInfo.setPassword(cursor.getString(2));
preferenceInfo.setUserName(cursor.getString(3));
preferenceInfo.setMobileNumber(cursor.getString(4));
preferenceInfo.setKeyMessage(cursor.getString(5));
After complete
transformation of cursor to object, we will return the object back to
the method.
return
preferenceInfo;
Now, the updated
DatabaseHelper file and PreferenceInfo.java file
Comments
Post a Comment