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();
}
}
Related
In the below given program Iam inserting imei_number in the table .However I have to retrieve the inserted data and display it in different method.Please guide.thanks in advance
onCreate()
{
try {
imeiDB = this.openOrCreateDatabase(IMEI_DB_NAME, MODE_PRIVATE, null);
imeiDB.execSQL("CREATE TABLE IF NOT EXISTS " +
IMEI_TABLE_NAME +" (IMEI_number_db VARCHAR);");
imeiDB.execSQL("INSERT INTO " + IMEI_TABLE_NAME +" Values ("+IMEI_number_db+");");
Cursor c = imeiDB.rawQuery("SELECT IMEI_number_db FROM " + IMEI_TABLE_NAME , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
IMEI_number = c.getString(c.getColumnIndex("IMEI_number_db"));
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (imeiDB != null)
imeiDB.execSQL("DELETE FROM " + IMEI_TABLE_NAME);
imeiDB.close();
}
}
/****************/
fetch the data in another method
private collectdata()
{
String IMEI_number ="";
Cursor c = imeiDB.rawQuery("SELECT IMEI_number_db FROM " + IMEI_TABLE_NAME , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
IMEI_number = c.getString(c.getColumnIndexOrThrow("IMEI_number_db"));
}while (c.moveToNext());
}
}
}
The only one column do you search in the query is IMEI_number_db, so the cursor only has one column. You should change this:
IMEI_number = c.getString(c.getColumnIndex("IMEI_number_db"));
For this:
IMEI_number = c.getString(0);
You can also try the following code.
IMEI_number = c.getString(c.getColumnIndexOrThrow("IMEI_number_db"));
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";
}
I have a simple code that manages to successfully query an SQLite Database and convert that result from cursor to string in order to display it on screen.
My problem now would be invalid queries that make the App Crash. Would there be a way to successfully handle invalid queries? Preferably something that would keep my app from crashing and would just redirect the user to the home page and display a toast of warning.
So far my method for searching looks like this:
public String search(DataBaseHelper myDB){
SQLiteDatabase db = myDB.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
cursor.moveToFirst();
String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) + " " +
cursor.getString(cursor.getColumnIndex("Room"));
//Toast msg = Toast.makeText(getBaseContext(),data, Toast.LENGTH_SHORT);
//msg.show();
cursor.close();
return data;
}
Cursor cursor = NULL ;
try
{
cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
if(cursor != NULL)
{
try {
if (cursor.moveToNext()) {
String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) +
" " + cursor.getString(cursor.getColumnIndex("Room"));
} else {
// Query result was empty, deal with it here.
}
} finally {
// Cursors should be closed
cursor.close();
}
}
}
catch (SQLiteException e) // (Exception e) catch-all:s are bad mmkay.
{
//print exception
}
Cursor cursor = null;
String data = "";
try
{
cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
}catch (Exception e) {
// TODO: handle exception
}
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);
}
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());
}
}
}