Check if data is exist in SQLite Android - android

I use this function to get specific data from SQlite:
SearchRes getSresultByName(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
new String[] { name }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
SearchRes searchres = new SearchRes(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2));
return searchres;
}
And it works just fine, I need to create similar function to test if value is exist in the table, so I tried this:
boolean checkIfExist(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
new String[] { name }, null, null, null, null);
if (cursor == null)
return false;
else
return true;
}
But I always get TRUE. Can you help me figure out what is the problem?

you should not be checking if cursor is null you should be checking if anything exists in the cursor
if(cursor.moveToFirst()){
return true
}else{
return false;
}

You can try Cursor getCount() to check the number of rows in the result of the query.. Following is the sample code:
boolean checkIfExist(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
new String[] { name }, null, null, null, null);
if (cursor.getCount() > 0)
return true;
else
return false;
}
answer by #tyczj is also good..

Related

IllegalArgumentException in filtering ListView

I am using this code to filter my listview:
Cursor fetchCountriesByName(String inputText) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor;
if (inputText == null || inputText.length () == 0) {
String[] columns = new String[] {DBHelper.ID,DBHelper.FNAME,DBHelper.LNAME,DBHelper.ADDRESS };
cursor = db.query(DBHelper.TABLE_NAME, columns, null, null, null, null, null);
}
else {
cursor = db.query(true, TABLE_NAME, new String[] {DBHelper.ID,
DBHelper.FNAME,DBHelper.LNAME},DBHelper.ADDRESS+ " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
I got an error
java.lang.IllegalArgumentException: column 'patient_address' does not exist
But the column names are same. There is a column called patient_address
What's the reason of this error? Please guide.
Try this
cursor = db.query(true, TABLE_NAME, new String[] {DBHelper.ID,
DBHelper.FNAME,DBHelper.LNAME},DBHelper.ADDRESS+ " like '%?%'", new String[]{inputText },
null, null, null, null);
the parameter is error.

SQLite, getting last item in table

I need some help with using the database that I created. I need to access the last item in the database. This is my code that gets a single item. How can I change it to only get the last?
// Getting single user
User getuser(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT,
KEY_GOAL, KEY_BMI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if(cursor!=null && cursor.getCount()!=0){
cursor.moveToFirst();
}
User user = new User(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getInt(2),cursor.getInt(3), cursor.getInt(4),
cursor.getString(5), cursor.getFloat(6));
return user;
}
Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT,
KEY_GOAL, KEY_BMI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, KEY_ID + " DESC", "LIMIT 1");
if the id uniquely identifies the user then you will be getting only one row as the result for the id you are passing so you dont have to worry about it is the last or first in the database. if it is just that you want the last row in your database then you dont have to pass an id you can do a select * and after retrieving move the cursor to last ie cursor.moveToLast().
Do this if you just want the last row
User getuser() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT,
KEY_GOAL, KEY_BMI }, null,
null, null, null, null, null);
if(cursor!=null && cursor.getCount()!=0){
cursor.moveToLast();
}
User user = new User(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getInt(2),cursor.getInt(3), cursor.getInt(4),
cursor.getString(5), cursor.getFloat(6));
return user;
}
and your call can be like this
User currentUser = db.getUser();
If you are passing an id to get a user details an the id uniquely identifies the user then what you have done will work
Are you perhaps looking for cursor.moveToLast()? This will move the cursor to the last record selected from your query. You can then get the fields values as usual using cursor.getString(n) etc.
You simply need to change a little in your code,
// Getting single user
User getuser(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT,
KEY_GOAL, KEY_BMI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if(cursor!=null && cursor.getCount()!=0){
cursor.moveToLast(); // Change here
}
User user = new User(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getInt(2),cursor.getInt(3), cursor.getInt(4),
cursor.getString(5), cursor.getFloat(6));
return user;
}
Try this one:
Cursor c = db.rawquery("Select *from tablename");
c.movetoLast();
and if you want to get the data from last to first use this codes:
Cursor c = db.rawquery("Select *from tablename");
c.movetoLast();
int count = c.getCount();
for(int i = 0; i < count; i++){
c.movetoPrevious();
}

My android sqlite database app gets close when I search the name which does not exist in the table

Here is a code/method to find if some name exists in the table or not..
Contact getContact(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
db.close();
cursor.close();
// return contact
return contact;
}
I already have a function to get all names in an arrayList. I can call it before calling the above function to solve my problem. But I want to ask about is there any other (straight) way to do it
When you call cursor.moveToFirst() it will return true if there is a valid result there, or false in the case no results are found. If cursor.moveToFirst() returns false, then calling any of the getXXX() methods will fail.
Try something like this:
if( cursor.moveToFirst() )
{
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
}
cursor.close();
Note that the Cursor returned from SQLiteDatabase.query is guaranteed to be non-null.
if (cursor == null)
Toast.makeText(getApplicationContext(), "No Records Exist", Toast.LENGTH_SHORT).show();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if(cursor.moveToFirst()){
do {
Double lat = cursor.getDouble(2);
Double lon = cursor.getDouble(1);
} while (trackCursor.moveToNext());
}
Here is a code for getting all the contacts in a list from the table...
/**
* Getting all the contacts in the database
*/
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return contact list
return contactList;
}
Then it is invoked in another function that returns "true" if name is present in the table "false" otherwise...
/**
* checks if name already present in the database
* #param name
* #return
*/
public boolean checkDbData(String name){
List<Contact> contactList =getAllContacts();
boolean checkName = false ;
for(Contact cn: contactList){
String dbName = cn.getName();
if(name.equals(dbName)){
checkName = true ;
}
}
return checkName;
}
And if this function returns "true", then the above given function is invoked to get the contacti.e.
Contact getContact(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
db.close();
cursor.close();
// return contact
return contact;
}
Note: we can also get this contact from the contactList, both can be used to get the required contact (i.e. "name" in this case)

SQLiteException when querying in Android

I receive this exception "bind or column index out of range" in this line:
Cursor cursor = db.query(TABLE_NAME, null, ID, new String[] { id }, null, null, null);
I want to check if the given id exists in the database, but always the query throw this exception and I don't know what is wrong. I tried with this and the exception it's the same:
Cursor cursor = db.query(TABLE_NAME, null, ID+" = ?", new String[] { id }, null, null, null);
This is the method I've programmed. If there is something wrong here, please, tell me:
public boolean existsAcc(String id)
{
//Check the parameters
if (id == null)
{
throw new IllegalArgumentException(
"The id parameter cannot be null");
}
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, null, ID, new String[] { id }, null, null, null);
if (!cursor.moveToFirst())
{
cursor.close();
return false;
}
cursor.close();
return true;
}
I don't know why Chirag deleted his answer, but he was rigth. Changing
Cursor cursor = db.query(TABLE_NAME, null, ID, new String[] { id }, null, null, null);
to
Cursor cursor = db.query(TABLE_NAME, null, ID + " = '" + id + "'", null, null, null, null);
does the trick.

No Such Column found

I am trying do a sign up process. Where i have a method inside the DbAdaptor where i check if the username exists.
public Boolean checkUsername(String username) throws SQLException {
Cursor mCursor = db.query(TABLE_USERS, new String[] { ID,
KEY_NAME, KEY_USERNAME}, KEY_USERNAME + "="
+ username, null, null, null, null, null);
if (mCursor != null) {
return true;
}
return false;
}
From the Edit text i sent a value "harsha" as username to test it. but i am getting the following error
http://variable3.com/files/screenshots/2010-12-26_1215.png
the code inside the activity is this
DBAdapter db = new DBAdapter(RegisterActivity.this);
db.open();
if (db.checkUsername(username))
Toast.makeText(RegisterActivity.this, "Found",
Toast.LENGTH_LONG).show();
else
Toast.makeText(RegisterActivity.this, "Not Found",
Toast.LENGTH_LONG).show();
db.close();
you need to send the harsha as 'harsha' with single quote
public Boolean checkUsername(String username) throws SQLException {
Cursor mCursor = db.query(TABLE_USERS, new String[] { ID,
KEY_NAME, KEY_USERNAME}, KEY_USERNAME + "="
+"'"+username+"'", null, null, null, null, null);
if (mCursor != null) {
return true;
}
return false;
You're checking the cursor and not the moveToNext() result. The cursor is valid but does not return a result set.

Categories

Resources