SQL in android dosent work - android

I want to update a row in a SQL table in a column (`click'). I can see the row in debug but it isn't recognized.
If click==0 so change to click==1.
Does someone know what is my mistake?
My code is:
public void UpdateClicked2(String name, int table) {
ContentValues values = new ContentValues();
String selectQuery = "SELECT * FROM " + MySQLiteGUESTS.TABLE_NAME
+ " WHERE " + MySQLiteGUESTS.COLUMN_TABLE + "=" + table;
Cursor cursor = database.rawQuery(selectQuery, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
GuestInfo comment = cursorToComment(cursor);
if (comment.getName().toString() != name)
cursor.moveToNext();
else {
if (comment.getClick() == 1) {
values.put(MySQLiteGUESTS.COLUMN_CLICK, 0);
} else
values.put(MySQLiteGUESTS.COLUMN_CLICK, 1);
}
}
String newString = MySQLiteGUESTS.COLUMN_NAME + " = " + name;
database.update(MySQLiteHelper.TABLE_NAME, values, newString, null);
}

if (comment.getName().toString() != name)
Instead of this
Use this:
if (comment.getName().toString().equals(name))
{
}

Related

How to return a string value from sqlite query?

Here is my query. I want to get the string value and return the single value to the activity class from where I have called the getSelectedMerchantCode function. My code is not working. Its returning "error"
public String getSelectedMerchantCode(String merchantname){
String selection = "Error";
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT merchantCode FROM " + "merchantList"+ " WHERE " + "merchantName" + "='" + merchantname + "'", null);
if(c.getCount() == 1){
c.moveToFirst();
selection = c.getString(c.getColumnIndex("merchantCode"));
return selection;
}
c.close();
db.close();
return null;
}
Try this way..
public List<String> getMyItems(String name) {
List<String> stringList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT Item_Name FROM " + USER_TABLE_NAME + " WHERE Item_Name= " + name;
Cursor c = db.rawQuery(selectQuery, null);
if (c != null) {
c.moveToFirst();
while (c.isAfterLast() == false) {
String name = (c.getString(c.getColumnIndex("Item_Name")));
stringList.add(name);
c.moveToNext();
}
}
return stringList;
}

rawQuery() exact match

I am using the following method to query my SQLite database with LIKE statement.
public List<Bean> getWords(String englishWord) {
if(englishWord.equals(""))
return new ArrayList<Bean>();
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " LIKE ? ORDER BY LENGTH(" + ENGLISH + ") LIMIT 100";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{"%" + englishWord.trim() + "%"});
List<Bean> wordList = new ArrayList<Bean>();
while(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
wordList.add(new Bean(english, bangla));
}
return wordList;
} catch (SQLiteException exception) {
exception.printStackTrace();
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
I would like to change the above code for that it will query for exact match. I tried to modify the code as below but I do not how to get the mal string.
public void getoneWords(String englishWord) {
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " =?";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{englishWord});
while(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
}
} finally {
if (cursor != null)
cursor.close();
}
}
Method getoneWords for what. You should return mal and english in this function.
return new Bean(english, mal);
If you need first word, just cursor.moveToFirst and delete while loop:
String english = cursor.getString(1);
String mal = cursor.getString(2);
return new Bean(english, mal);
I finally solved this problem myself.
public String getoneWords(String englishWord) {
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " =?";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
String meaning = "";
try {
cursor = db.rawQuery(sql, new String[] {englishWord});
if(cursor.getCount() > 0) {
cursor.moveToFirst();
meaning = cursor.getString(2);
}
return meaning;
}finally {
cursor.close();
}
}
In your getoneWords() you are not returning the queried values.
As you have two return values you would either need to wrap them in a Pair or create a "holder" Object (e.g. class Words(String english, String mal)) for the return values.
If your Query returns multiple matches you would need to return a list of those Objects. Otherwise, your above Code would just return the last match.
So you need to alter your function to return the queried
public Pair<String,String> getoneWords(String englishWord) {
Pair<String,String> result = null;
...
if(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
result = new Pair<String,String>(english, mal);
}
...
return result;
}

CursorIndexOutOfBoundsException:

I am new to the android i am trying to get the cursor values related to the particular column value. but it's showing null.
public int getDashBoardCount() {
String countQuery = "SELECT * FROM " + DASHBOARD_TABLE + " WHERE " + VECHICAL_TYPE + " = " + 'c';
From here also i am getting no such column: c (code 1): , while compiling: SELECT * FROM dashboard_table WHERE vehicle_type = c
String countQuery = "SELECT * FROM " + DASHBOARD_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public DashBoardAvaCapModel getVechicalRelAva(String vechical_type) {
SQLiteDatabase db = null;
Cursor cursor = null;
DashBoardAvaCapModel dash = null;
try {
db = this.getReadableDatabase();
cursor = db.query(DASHBOARD_TABLE, new String[]{_ID,
AVAILABLE, CAPACITY, BOOKED, VECHICAL_TYPE}, VECHICAL_TYPE + "=?",
new String[]{String.valueOf(vechical_type)}, null, null, null, null);
int idkey = cursor
.getColumnIndex(_ID);
int available = cursor
.getColumnIndex(AVAILABLE);
int capactity = cursor
.getColumnIndex(CAPACITY);
int booked = cursor
.getColumnIndex(BOOKED);
int vechicaltype = cursor
.getColumnIndex(VECHICAL_TYPE);
if (cursor != null && cursor.moveToFirst())
dash = new DashBoardAvaCapModel(Long.valueOf(cursor.getString(idkey)),
cursor.getString(available), cursor.getString(capactity), cursor.getString(booked), cursor.getString(vechicaltype));
Log.e("dash", "" + cursor.getString(available));
} catch (final Exception ex) {
String exp = String.valueOf(ex);
Log.e("Databa", "" + exp);
} finally {
cursor.close();
db.close();
}
return dash;
}
After writing this line
cursor = db.query(DASHBOARD_TABLE, new String[]{_ID,
AVAILABLE, CAPACITY, BOOKED, VECHICAL_TYPE}, VECHICAL_TYPE + "=?",
new String[]{String.valueOf(vechical_type)}, null, null, null, null);
pls try to write
cursor.moveToFirst();
For first one you can use like
String countQuery = "SELECT * FROM " + DASHBOARD_TABLE + " WHERE " + VECHICAL_TYPE + " = '" + c + "'"
where c is any variable
Hope this will help you

Android sqlite how to check if a record exists

I would like to check whether a record exists or not.
Here is what I've tried:
MainActivity.class
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Ontext changed " + new String(s.toString()));
strDocumentFrom = s.toString();
if(s.toString().isEmpty()){
} else {
try{
strTransactionDate = dbHelper.getTransactionDateByDocumentNumber(strDocumentFrom);
//strTotalAmount = dbHelper.getTotalAmountByDocumentNumber(strDocumentFrom);
//strVan = dbHelper.getVanByDocumentNumber(strDocumentFrom);
//etTransactionDate.setText(strTransactionDate);
//etTotalAmount.setText(strTotalAmount);
//Log.d("Van", "" + strVan);
//etVan.setText(strVan);
} catch (SQLiteException e) {
e.printStackTrace();
Toast.makeText(ReceivingStocksHeader.this,
"Document number does not exist.", Toast.LENGTH_SHORT).show();
}
}
DBHelper.class
// TODO DISPLAYING RECORDS TO TRANSRCVHEADER
public String getTransactionDateByDocumentNumber(String strDocumentNumber){
String[] columns = new String[]{KEY_TRANSACTIONDATE};
Cursor c = myDataBase.query(TBL_INTRANS,
columns, null,
null, null, null, null, null);
if(c != null){
c.moveToFirst();
String date = c.getString(0);
return date;
} else {
Log.d("Error", "No record exists");
}
return null;
}
But it doesn't get it to the catch block to display the toast.
What am I doing wrong in here?
public static boolean CheckIsDataAlreadyInDBorNot(String TableName,
String dbfield, String fieldValue) {
SQLiteDatabase sqldb = EGLifeStyleApplication.sqLiteDatabase;
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = sqldb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
I hope this is useful to you...
This function returns true if record already exists in db. Otherwise returns false.
These are all good answers, however many forget to close the cursor and database. If you don't close the cursor or database you may run in to memory leaks.
Additionally: You can get an error when searching by String that contains non alpha/numeric characters. For example: "1a5f9ea3-ec4b-406b-a567-e6927640db40". Those dashes (-) will cause an unrecognized token error. You can overcome this by putting the string in an array. So make it a habit to query like this:
public boolean hasObject(String id) {
SQLiteDatabase db = getWritableDatabase();
String selectString = "SELECT * FROM " + _TABLE + " WHERE " + _ID + " =?";
// Add the String you are searching by here.
// Put it in an array to avoid an unrecognized token error
Cursor cursor = db.rawQuery(selectString, new String[] {id});
boolean hasObject = false;
if(cursor.moveToFirst()){
hasObject = true;
//region if you had multiple records to check for, use this region.
int count = 0;
while(cursor.moveToNext()){
count++;
}
//here, count is records found
Log.d(TAG, String.format("%d records found", count));
//endregion
}
cursor.close(); // Dont forget to close your cursor
db.close(); //AND your Database!
return hasObject;
}
Raw queries are more vulnerable to SQL Injection. I will suggest using query() method instead.
public boolean Exists(String searchItem) {
String[] columns = { COLUMN_NAME };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = { searchItem };
String limit = "1";
Cursor cursor = db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null, limit);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
Source: here
SELECT EXISTS with LIMIT 1 is much faster.
Query Ex: SELECT EXISTS (SELECT * FROM table_name WHERE column='value' LIMIT 1);
Code Ex:
public boolean columnExists(String value) {
String sql = "SELECT EXISTS (SELECT * FROM table_name WHERE column='"+value+"' LIMIT 1)";
Cursor cursor = database.rawQuery(sql, null);
cursor.moveToFirst();
// cursor.getInt(0) is 1 if column with value exists
if (cursor.getInt(0) == 1) {
cursor.close();
return true;
} else {
cursor.close();
return false;
}
}
You can use SELECT EXISTS command and execute it for a cursor using a rawQuery,
from the documentation
The EXISTS operator always evaluates to one of the integer values 0
and 1. If executing the SELECT statement specified as the right-hand
operand of the EXISTS operator would return one or more rows, then the
EXISTS operator evaluates to 1. If executing the SELECT would return
no rows at all, then the EXISTS operator evaluates to 0.
I have tried all methods mentioned in this page, but only below method worked well for me.
Cursor c=db.rawQuery("SELECT * FROM user WHERE idno='"+txtID.getText()+"'", null);
if(c.moveToFirst())
{
showMessage("Error", "Record exist");
}
else
{
// Inserting record
}
One thing the top voted answer did not mention was that you need single quotes, 'like this', around your search value if it is a text value like so:
public boolean checkIfMyTitleExists(String title) {
String Query = "Select * from " + TABLE_NAME + " where " + COL1 + " = " + "'" + title + "'";
Cursor cursor = database.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
Otherwise, you will get a "SQL(query) error or missing database" error like I did without the single quotes around the title field.
If it is a numeric value, it does not need single quotes.
Refer to this SQL post for more details
SQLiteDatabase sqldb = MyProvider.db;
String Query = "Select * from " + TABLE_NAME ;
Cursor cursor = sqldb.rawQuery(Query, null);
cursor.moveToLast(); //if you not place this cursor.getCount() always give same integer (1) or current position of cursor.
if(cursor.getCount()<=0){
Log.v("tag","if 1 "+cursor.getCount());
return false;
}
Log.v("tag","2 else "+cursor.getCount());
return true;
if you not use cursor.moveToLast();
cursor.getCount() always give same integer (1) or current position of cursor.
Code :
private String[] allPushColumns = { MySQLiteHelper.COLUMN_PUSH_ID,
MySQLiteHelper.COLUMN_PUSH_TITLE, MySQLiteHelper.COLUMN_PUSH_CONTENT, MySQLiteHelper.COLUMN_PUSH_TIME,
MySQLiteHelper.COLUMN_PUSH_TYPE, MySQLiteHelper.COLUMN_PUSH_MSG_ID};
public boolean checkUniqueId(String msg_id){
Cursor cursor = database.query(MySQLiteHelper.TABLE_PUSH,
allPushColumns, MySQLiteHelper.COLUMN_PUSH_MSG_ID + "=?", new String [] { msg_id }, null, null, MySQLiteHelper.COLUMN_PUSH_ID +" DESC");
if(cursor.getCount() <= 0){
return false;
}
return true;
}
Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:
public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
}
because of possible data leaks best solution via cursor:
Cursor cursor = null;
try {
cursor = .... some query (raw or not your choice)
return cursor.moveToNext();
} finally {
if (cursor != null) {
cursor.close();
}
}
1) From API KITKAT u can use resources try()
try (cursor = ...some query)
2) if u query against VARCHAR TYPE use '...' eg. COLUMN_NAME='string_to_search'
3) dont use moveToFirst() is used when you need to start iterating from beggining
4) avoid getCount() is expensive - it iterates over many records to count them. It doesn't return a stored variable. There may be some caching on a second call, but the first call doesn't know the answer until it is counted.
Try to use cursor.isNull method.
Example:
song.isFavorite = cursor.isNull(cursor.getColumnIndex("favorite"));
You can use like this:
String Query = "Select * from " + TABLE_NAME + " where " + Cust_id + " = " + cust_no;
Cursor cursorr = db.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursorr.close();
}
cursor.close();
private boolean checkDataExistOrNot(String columnName, String value) {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM" + TABLE_NAME + " WHERE " + columnName + " = " + value;
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false; // return false if value not exists in database
}
cursor.close();
return true; // return true if value exists in database
}
I prefer to do it this way because it's fast and less expensive than other methods:
Cursor cursor = db.rawQuery("SELECT 1 FROM table WHERE condition = 1 LIMIT 1", null);
try {
if (cursor.moveToNext()) {
//Record exists
} else {
//Record doesn't exists
}
} finally {
cursor.close();
}
My version:
public boolean isTitleExists(String title, String type) {
int isExists = 0;
try {
String query = "SELECT EXISTS (SELECT 1 FROM titles WHERE title = ? and type = ?)";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, title);
statement.setString(2, type);
ResultSet rs = statement.executeQuery();
rs.next();
isExists = rs.getInt(1);
rs.close();
statement.close();
} catch (SQLException e) {
Common.console("isTitleExists error: " + e.getMessage());
}
return isExists == 1;
}

Android SQLite Query: Trouble with WHERE clause

Please let me know why my where clause isn't working. I tried using the query instead of rawquery but no luck.
try {
String categoryex = "NAME";
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
MyData = dbHelper.getWritableDatabase();
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + where Category = '+categoryex'" , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("Category"));
String age = c.getString(c.getColumnIndex("Text_Data"));
results.add( firstName + " Directions: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (MyData != null)
MyData.execSQL("DELETE FROM " + tableName);
MyData.close();
}
try... (you left out a double-quote before where.
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" +categoryex + "'" , null);
I think you should use rawQuery in this form:
rawQuery("SELECT * FROM ? where Category = ?", new String[] {tableName, categoryex});
I think it's more secure this way.
Your quotes are buggered:
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" + categoryex + "'" , null);
You also should read up on SQL injection attacks.
it will be more easy if you use this technique instead of rawQuery,its easy way change your table name, columns and where conditions accordingly.
public ArrayList<Invitees> getGroupMembers(String group_name) {
ArrayList<Invitees> contacts = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {COLUMN_CONTACT, COLUMN_PHONE_NUMBER};
String selection = COLUMN_GROUP_NAME + "=?";
String[] selectionArgs = {group_name};
Cursor cursor = db.query(GROUPS_TABLE_NAME, projection, selection, selectionArgs, null, null, null);
if (cursor.moveToFirst()) {
do {
Invitees invitees = new Invitees();
invitees.setUserName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTACT)));
invitees.setInviteePhone(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PHONE_NUMBER)));
contacts.add(invitees);
} while (cursor.moveToNext());
}
return contacts;
}

Categories

Resources