getting data from database table using cursor in android - 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());
}
}
}

Related

Android lollipop error: Null pointer exception while trying to read phone contcats

I have got the following error while trying to read phone contact in Nexus 5(updated to lollipop) only.
java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.database.Cursor.moveToNext()' on a null object reference
at mycomp.android.ui.fragments.DirectoriesFragment.readContacts(SourceFile:595)
at mycomp.android.ui.fragments.DirectoriesFragment.processOneDirectory(SourceFile:744)
at mycomp.android.ui.fragments.DirectoriesFragment.onLoadFinished(SourceFile:722)
at mycomp.android.utils.RESTLoaderFragment.onLoadFinished(SourceFile:1)
at android.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:483)
at android.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:451)
at android.content.Loader.deliverResult(Loader.java:144)
at mycomp.android.utils.loader.RESTLoader.deliverResult(SourceFile:322)
at mycomp.android.utils.loader.RESTLoader.deliverResult(SourceFile:1)
at android.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:265)
at android.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:92)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
i am using following code to retrieve contacts from phone
private void readContacts() {
ContentResolver cr = getActivity().getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
Cursor c = null ;
Cursor pCur = null;
try {
String phone = null;
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
try {
DirectoryRecordEntry entry = null;
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
int idIndex = cur.getColumnIndexOrThrow(Contacts._ID);
long ids = cur.getLong(idIndex);
Uri rawContactUri = ContentUris.withAppendedId(
RawContacts.CONTENT_URI, ids);
Uri entityUri = Uri.withAppendedPath(rawContactUri,
Entity.CONTENT_DIRECTORY);
c= getActivity().getContentResolver().query(entityUri,
new String[]{
RawContacts.SOURCE_ID}, null, null, null);
String source_id = "";
// Getting null pointer exception here, c is null :(
while (c.moveToNext()) {
source_id = c.getString(0);
}
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
if (source_id != null && source_id.length()>0) {
entry = new OutlookContactEntry(name, "");
} else {
entry = new PhoneNumberEntry(name, "");
}
pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[]{id},
null);
while (pCur.moveToNext()) {
try {
phone = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int phoneType = pCur
.getInt(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
if (entry instanceof OutlookContactEntry) {
OutlookContactEntry oEntry = (OutlookContactEntry) entry;
oEntry.addContact(getType(phoneType), phone);
} else {
entry.getPhNumberList().add(phone);
}
} catch (Exception e) {
Log.e(CLASS_NAME, "Error in retrieving contacts from phone",e);
}
}
}
if (entry != null) {
if (entry instanceof OutlookContactEntry) {
OutlookContactEntry oEntry = (OutlookContactEntry) entry;
List<String> list =new ArrayList<String>(oEntry.getContacts().values());
if(!list.isEmpty()){
entry.setNumber(list.get(0));
}
}else{
if(!entry.getPhNumberList().isEmpty()){
entry.setNumber(entry.getPhNumberList().get(0));
}
}
objListRowRecord.put(name, entry);
}
} catch (Exception e) {
Log.e(CLASS_NAME, "Error in retrieving contacts from phone",e);
}
}
}
} catch (Exception e) {
Log.e(CLASS_NAME, "Error in retrieving contacts from phone",e);
}finally
{
try {
if(pCur!=null){
pCur.close();
}
if(c!=null){
c.close();
}
if(cur!=null){
cur.close();
}
cr=null;
} catch (Exception e) {
Log.e(CLASS_NAME, "Error closing cursor",e);
}
}
}
i have encountered this problem only after updating the kitkat to lollipop
It can be resolved by a null check but i really want to know the reason behind it.
Any help would be appreciated
Thanks
Amith
The documentation of ContentResolver.query() says:
Returns
A Cursor object, which is positioned before the first entry, or null
It returns null because it is allowed to do so.
You always need a null check when querying a content resolver.
/**
* This method is to read contacts.
*/
public void readContacts() {
localPhTempList.clear();
ContentResolver cr = activity.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String phone = null;
Cursor c = null;
Cursor pCur = null;
try {
if (cur != null && cur.getCount() > 0) {
while (cur.moveToNext()) {
try {
DirectoryRecordEntry entry = null;
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
int idIndex = cur.getColumnIndexOrThrow(Contacts._ID);
long ids = cur.getLong(idIndex);
Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, ids);
Uri entityUri = Uri.withAppendedPath(rawContactUri, Entity.CONTENT_DIRECTORY);
c = activity.getContentResolver().query(entityUri, new String[] {
RawContacts.SOURCE_ID }, null, null, null);
String source_id = "";
if (c != null) {
while (c.moveToNext()) {
source_id = c.getString(0);
}
}
if (c != null) {
c.close();
}
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
if (source_id != null && source_id.length() > 0) {
entry = new OutlookContactEntry(name, "-1");
} else {
entry = new PhoneNumberEntry(name, "-2");
}
pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " ='"
+ id + "'", null, null);
if (pCur != null) {
while (pCur.moveToNext()) {
try {
phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int phoneType = pCur.getInt(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
if (entry instanceof OutlookContactEntry) {
OutlookContactEntry oEntry = (OutlookContactEntry) entry;
String names = getType(phoneType);
String number = phone;
if (names != null && names.length() > 0 && number != null && number.length() > 0
/*
* && !number.equalsIgnoreCase("-1")
* && !number.equalsIgnoreCase("-1")
*/) {
oEntry.addContact(names, number);
}
} else {
entry.getPhNumberList().add(phone);
}
} catch (Exception e) {
Log.e(CLASS_NAME, "Error in retrieving contacts from phone", e);
}
}
if (pCur != null) {
pCur.close();
}
}
}
if (entry != null) {
if (entry instanceof OutlookContactEntry) {
OutlookContactEntry oEntry = (OutlookContactEntry) entry;
List<String> list = new ArrayList<String>(oEntry.getContacts().values());
if (!list.isEmpty()) {
entry.setNumber(list.get(0));
}
} else {
if (!entry.getPhNumberList().isEmpty()) {
entry.setNumber(entry.getPhNumberList().get(0));
}
}
// objListRowRecord.put(name, entry);
if (!(entry.getNumber().equalsIgnoreCase("-1") || entry.getNumber().equalsIgnoreCase("-2"))) {
localPhTempList.add(entry);
}
}
} catch (Exception e) {
Log.e(CLASS_NAME, "Error in retrieving contacts from phone", e);
}
}
}
} catch (Exception e) {
Log.e(CLASS_NAME, "Error in retrieving contacts from phone", e);
} finally {
try {
if (pCur != null) {
pCur.close();
pCur = null;
}
if (c != null) {
c.close();
c = null;
}
if (cur != null) {
cur.close();
cur = null;
}
cr = null;
} catch (Exception e) {
Log.e(CLASS_NAME, "Error closing cursor", e);
}
}
}
Always do a
Cursor cursor = query();//Your Custom Query Method
if(cursor != null){
//Iterate
for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
//Get cursor values
}
if(!cursor.isClosed()){cursor.close();}
}

use different sql query for toggle button

I'm searching for user input in a database. It is a dictionary app. I have a toggle button that allows user to switch between 2 languages. It works, however it doesn't work when I switch to a different language. Basically I want to apply a different sql query to when the button is switched to another language.
Here is my code:
try {
Cursor cursor = dictionary.getDictionaryDatabase().rawQuery("SELECT * FROM fr_definition JOIN fr_adresse_definition ON fr_definition.data_id = fr_adresse_definition.definition WHERE index_nom_adresse='"+word[0].toLowerCase().trim()+"'", null);
cursor.moveToFirst();
if (cursor.getCount() != 0) {
if (word[1] == null || word[1].equals("English")) {
translatedWord = cursor.getString(2);
} else {
//dictionary.getDictionaryDatabase().rawQuery("SELECT * FROM en_definition JOIN en_adresse_definition ON en_definition.data_id = en_adresse_definition.definition WHERE index_nom_adresse='"+word[0].toLowerCase().trim()+"'", null);
translatedWord = cursor.getString(1);
}
} else {
translatedWord = "The word is not in database";
}
cursor.close();
} catch (SQLiteException sqle) {
translatedWord = "The word is not in database";
}
dictionary.close();
Wouldn't something like this let you use your other query?
try {
Cursor cursor;
if (word[1] == null || word[1].equals("English")) {
cursor = dictionary.getDictionaryDatabase().rawQuery("SELECT * FROM fr_definition JOIN fr_adresse_definition ON fr_definition.data_id = fr_adresse_definition.definition WHERE index_nom_adresse='"+word[0].toLowerCase().trim()+"'", null);
cursor.moveToFirst();
if (cursor.getCount() != 0) {
translatedWord = cursor.getString(2);
}
} else {
cursor = dictionary.getDictionaryDatabase().rawQuery("SELECT * FROM en_definition JOIN en_adresse_definition ON en_definition.data_id = en_adresse_definition.definition WHERE index_nom_adresse='"+word[0].toLowerCase().trim()+"'", null);
cursor.moveToFirst();
if (cursor.getCount() != 0) {
translatedWord = cursor.getString(1);
}
}
cursor.close();
} catch (SQLiteException sqle) {
translatedWord = "The word is not in database";
}
dictionary.close();

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();
}
}

retrieving record from database using cursor in 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";
}

Query Android contact to get ACCOUNT_TYPE and ACCOUNT_NAME

I am able to obtain a list of contacts and their basic information like: name. phones, emails, ims, notes, organizations for backup purposes by using ContactsContract.Contacts.CONTENT_URI for a list of Contacts and other specific URIs for different information type.
I need, in order to fully restore all the information two more fields:
ContactsContract.RawContacts.ACCOUNT_TYPE
ContactsContract.RawContacts.ACCOUNT_NAME
Can anyone guide me how to obtain this info, knowing the Contact Id from ContactsContract.Contacts.CONTENT_URI ?
Thank you
public ContactAccount getContactAccount(Long id,ContentResolver contentResolver) {
ContactAccount account = null;
Cursor cursor = null;
try {
cursor = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.ACCOUNT_TYPE},
ContactsContract.RawContacts.CONTACT_ID +"=?",
new String[]{String.valueOf(id)},
null);
if (cursor != null && cursor.getCount() >0)
{
cursor.moveToFirst();
account = new ContactAccount();
account.setAccountName(cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)));
account.setAccountType(cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE)));
cursor.close();
}
} catch (Exception e) {
Utils.log(this.getClass().getName(), e.getMessage());
} finally{
cursor.close();
}
return(account);
}
The above answer is perfect if you are looking for account information using the contactID column. But, often information is stored using rawContactID. So, if you want to access account information for a raw-contact-id then you can use this method below.
The key difference is that I am using the _ID column from the rawContacts table. This maps to the rawContactID that you will see in other tables
public int updateAccountInfoForContactData(String rawContactID) {
int accountPos = 0;
Cursor cursor = null;
String accountName = null;
String accountType = null;
Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI;
String[] syncColumns = new String[] {
ContactsContract.RawContacts.ACCOUNT_NAME,
ContactsContract.RawContacts.ACCOUNT_TYPE,
};
String whereClause = ContactsContract.RawContacts._ID +"=?";
String[] whereParams = new String[]{String.valueOf(rawContactID)};
//Uri rawContactUri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, longContactID);
try {
cursor = mContext.getContentResolver().query(
rawContactUri,
syncColumns,
whereClause,
whereParams,
null);
if (cursor != null && cursor.getCount() >0)
{
cursor.moveToFirst();
if(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME) >= 0) {
accountName = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME));
}
if(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE) >= 0) {
accountType = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE));
}
cursor.close();
cursor = null;
}
} catch (Exception e) {
Log.d(TAG, "getting account info failed");
} finally{
if(cursor != null) {
cursor.close();
}
cursor = null;
}
return(accountPos);
}

Categories

Resources