retrieving record from database using cursor in android - android

I have used following codes to retrieve record:
String getCredentialsFromAdmint(String name ,String pwd) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ADMIN, new String[] { KEY_ID,
KEY_A_USER_NAME, KEY_A_PWD }, KEY_A_USER_NAME + "=?" + " AND " + KEY_A_PWD + "=?",
new String[] { name , pwd }, null, null, null, null);
if (cursor != null){
cursor.moveToFirst();
return cursor.getString(1);
}
else{
return "norecord";
}
This code works if there is a record but if no record is found then application gets an error.
Is there any other ways to retrieve data from database?

Change your code to following
if ( cursor.moveToFirst()){
return cursor.getString(1);
} else{
return "norecord";
}

You don't check if cursor.moveToFirst() returns true;
It should looks like this:
if (cursor != null) {
if(cursor.moveToFirst()){
return cursor.getString(cursor.getColumnIndexOrThrow(KEY_A_USER_NAME));
} else{
//no record
}
} else {
//invalid uri
}

Try to use the following code instead
if (cursor != null){
cursor.moveToFirst();
if(cursor.isAfterLast() == false) {
return cursor.getString(1);
}
else
{
return "norecord";
}
}
else{
return "norecord";
}

Related

how to check if sqlite database is empty (android)?

I am making a media player which loads metadata of songs into a database.
Below is my function for checking whether the db is empty or not but it isn't working. Please tell me what's wrong with my code and suggest a correction or a better alternative.
private static boolean isDbEmpty(SQLiteDatabase songsDb) {
try {
Cursor c = songsDb.rawQuery("SELECT * FROM " + SongsTable.TABLE_NAME, null);
if (c.moveToFirst()) { // c.getCount() == 0 is also not working
Log.d(TAG, "isDbEmpty: not empty");
return false;
}
c.close();
} catch (SQLiteException e) {
Log.d(TAG, "isDbEmpty: doesn't exist");
return true;
}
return true;
}
Use the following query to achieve your goal. There are two tables created automatically - android_metadata and sqlite_sequence, so we apply a NOT condition in the query.
SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name != 'android_metadata' AND name != 'sqlite_sequence';
Try this.
private static boolean isDbEmpty(SQLiteDatabase songsDb) {
Cursor c = null;
try {
c = songsDb.rawQuery("SELECT * FROM " + SongsTable.TABLE_NAME, null);
if (c == null || c.getCount() == 0) {
return true;
} else if (c.moveToFirst()) {
Log.d(TAG, "isDbEmpty: not empty");
return false;
}
} catch (SQLiteException e) {
Log.d(TAG, "isDbEmpty: doesn't exist");
return true;
}finally {
if(c != null){
c.close();
}
}
return true;
}
This will only tell you if the TABLE is empty, not the DATABASE.
Regardless, you could use code like:
Cursor countCursor = songsDb.rawQuery("select count(*) from " + SongsTable.TABLE_NAME, null);
countCursor.moveToFirst();
int count = countCursor.getInt(0);
countCursor.close();
And then test count.
You can check like this :
Cursor c = songsDb.rawQuery("SELECT * FROM " + SongsTable.TABLE_NAME, null);
cursor.moveToFirst();
if (cursor != null && cursor.getCount() == 0) {
//for empty
return true;
}else{
// not empty
return false;
}

Android retrieve contact name always returns false

I am trying to check whether given name is in phone contact or not, but it always returns false, i cant figure out what mistake i have done
public boolean ContactNotFound(String no, String name) {
if (no != null) {
Uri lookupUri = Uri.withAppendedPath(
PhoneLookup.CONTENT_FILTER_URI, Uri.encode(name));
String[] mPhoneNumberProjection = { PhoneLookup._ID,
PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
Cursor cur = con.getContentResolver().query(lookupUri,
mPhoneNumberProjection, null, null, null);
LogUtil.d("Count -->" + cur.getCount());
if (cur.getCount() > 0) {
try {
if (cur.moveToFirst()) {
return true;
}
} finally {
if (cur != null)
cur.close();
}
return false;
} else {
return false;
}
} else {
return false;
}
}
Kindly help me to figure out the issue
I suggest you to save all your contact names in arraylist temporarily and then check name using arrayList.contains(name) method

want to get a row from cursor

I want to get a row and this row have 2 columns which named username and password my code is here:
String selection = PROFILE_COLUMN_USERNAME + " = '" + userName+ "' AND " +PROFILE_COLUMN_PASSWORD + " = '" + password + "'";
Cursor cursor = database.query(TABLE_NAME, new String[] {PROFILE_COLUMN_USERNAME, PROFILE_COLUMN_PASSWORD }, selection,null, null, null, null);
I got a sample data like username = erdem and password= c on my db but when i write this sample and write to get username like this:
String s =cursor.getString(cursor.getColumnIndex(PROFILE_COLUMN_USERNAME));
it doesn't work. Why?
Try something like below : Here "path_on_server" is the name of the column in the DB table whose value is being extracted. You can change it to your table's column name.
String query = "some query";
Cursor c = newDB.rawQuery(query, null);
if (c != null) {
if (c.moveToFirst()) {
do {
mPathOnServer = c.getString(c
.getColumnIndex("path_on_server"));
} while (c.moveToNext());
}
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not extract information from DB");
}
Use moveToFirst, read the documentation.
Try this way...
Cursor cursor = null;
try {
String queryString = "SELECT * FROM Table_Name";
cursor = myDatabase.rawQuery(queryString, null);
if (cursor != null && cursor.moveToFirst()) {
do {
String nextUser = new String(cursor.getString(cursor
.getColumnIndex("driver_fname")));
} while (cursor.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.deactivate();
cursor.close();
cursor = null;
}
if (myDatabase != null) {
myDatabase.close();
}
}

getting data from database table using cursor in android

I have one employee table which has column values
("store_loc_id","name","password","address_id","role_id",
"retailer_id").
I want to get the name and password from this table using cursor. how can i do??
Haven't check this code, but the idiom should be understandable.
Cursor cursor = db.query(...);
if(cursor !=null && cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
} while (cursor.moveToNext());
}
public Cursor getEmployee() {
try {
return db.query(employee, new String[] { "name", "password" },
null, null, null, null, null);
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
return null;
}
}
Cursor c = db.getEmployee();
if (c == null) {
// do nothing
} else {
if (c.getCount() > 0) {
if (c.moveToFirst()) {
do {
String Name = c.getString(0);
String Password = c.getString(1);
} while (c.moveToNext());
}
}
}

using the contacts manager in android

i have an app which shows the received messages as a Toast through a BroadcastReceiver. I am presently using the SmsMessage.getOriginatingAddress() method which gives me the number of the sender, how can modify it to get the corresponding name of the sender if stored in the contacts?
You will need to query the contacts for the rest of the data.
First query for the contacts id using the phone number.
Cursor cursor = context.getContentResolver().query(
Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, address),
new String[] { Contacts.Phones.PERSON_ID }, null, null, null);
if (cursor != null) {
try {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
Long id = Long.valueOf(cursor.getLong(0));
if (Log.DEBUG) Log.v("Found person: " + id);
return (String.valueOf(id));
}
} finally {
cursor.close();
}
}
Then query for the Contacts name with the id from the first query.
Cursor cursor = context.getContentResolver().query(
Uri.withAppendedPath(Contacts.People.CONTENT_URI, id),
new String[] { PeopleColumns.DISPLAY_NAME }, null, null, null);
if (cursor != null) {
try {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
String name = cursor.getString(0);
if (Log.DEBUG) Log.v("Contact Display Name: " + name);
return name;
}
} finally {
cursor.close();
}
}
You may be able to combine these two queries somehow.

Categories

Resources