Android database don't do anything if selected row doesn't exist - android

I made a query that requests a random row from database using ID. But I have a little problem. I want it to show a message if it exists or it doesn't exist. For example my database like that:
ID - ingilizce - turkce
1 - hello - merhaba
4 - hi - selam
As you see, the second and third record don't exist. I generate a random number between 1 and 4 and I get the row that belongs to ID. So, when it generates a number like 2 or 3, it will generate a new random number.
My code is here:
public void kelimeUret() {
SQLiteDatabase db = kelimeler.getReadableDatabase();
rastgele = new Random();
Cursor kayit = db.rawQuery("SELECT count(*) FROM kelimeler", null);
kayit.moveToFirst();
int max = Integer.parseInt(kayit.getString(0));
int min = 1;
int rastgeleKayit = rastgele.nextInt(max - min + 1) + min;
Cursor kayit3 = db.rawQuery("SELECT * FROM kelimeler WHERE id=" + rastgeleKayit, null);
kayit3.moveToFirst();
int kayitSayisi = kayit3.getCount();
if (kayitSayisi<1) {
//Toast.makeText(getApplicationContext(), "bu kayıt yok", Toast.LENGTH_SHORT).show();
//kelimeUret();
// I COULDN'T DO HERE !
} else {
Cursor kayit2 = db.rawQuery("SELECT ingilizce FROM kelimeler WHERE id=" + rastgeleKayit, null);
kayit2.moveToFirst();
String sonuc = kayit2.getString(0);
olusturulanKelime = sonuc;
kelime = (TextView) findViewById(R.id.kelime);
kelime.setText(sonuc);
}
Thanks for your responds...

Cursor kayit3 = db.rawQuery("SELECT * FROM kelimeler WHERE id=" + rastgeleKayit, null);
kayit3.moveToFirst();
kayit3.getCount(); will return the number of records returned by the query. If there are no records, then it does not exist. If it returns more than 1 record, then the record exist.
Hope this helps

Related

update database android doesn't work [duplicate]

This question already has answers here:
Update table using rawQuery() method does not work
(5 answers)
Closed 7 years ago.
i'm discovering database in Android. I understand how to read it but i don't succed writing it. Here is the database:
private static final String DATABASE_CREATE = "create table lesPlats
(id integer primary key autoincrement, nom text not null, quantite integer);";
database.execSQL(DATABASE_CREATE);
i edit it:
values.put("nom", "plat1");
values.put("quantite", 0);
database.insert("lesPlats", null, values);
i want to increase the quantity of "plat1" (debug version in comment):
int n=1;
// Cursor c = database.rawQuery("SELECT * FROM lesPlats WHERE id="+n, null);
// c.moveToFirst();
// System.out.println("QUANTITY BEFORE: "+cursorToComment(c).quantite+ " (id: "+cursorToComment(c).id+")");
database.rawQuery("UPDATE lesPlats SET quantite = 1 WHERE id = " + n, null);
// c = database.rawQuery("SELECT * FROM lesPlats WHERE id="+n, null);
// c.moveToFirst();
// System.out.println("QUANTITY NEXT: "+cursorToComment(c).quantite+ " (id: "+cursorToComment(c).id+")");
with debugging, i got the result
QUANTITY BEFORE: 0 (id: 1)
QUANTITY NEXT: 0 (id: 1)
So there is a mistake somewhere. Could you tell me if the code is good? specially this one:
database.rawQuery("UPDATE lesPlats SET quantite = 1 WHERE id = " + n, null);
This means that quantity is set to 1 at the id=1, isn't it?
i try with UPDATE, i have the same result...
read and close the cursor before calling the second raw, because the query won't get executed without it :
c = database.rawQuery("UPDATE lesPlats SET quantite = 1 WHERE id = " + n, null);
c.moveToFirst();
c.close();
sorry guys, i've forgot the to set quantity in the cursorToComment procedure...
private Comment cursorToComment(Cursor cursor) {
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setNom(cursor.getString(1));
comment.setQqte(cursor.getInt(2)); //here!!
return comment;
thx a lot
So, three ways to change the database:
ContentValues values = new ContentValues();
values.put("quantite", 1);
database.update("lesPlats", values, "id=?", new String[]{"1"});
or
database.execSQL("UPDATE lesPlats SET quantite = 1 WHERE id = " + n);
or
c = database.rawQuery("UPDATE lesPlats SET quantite = 1 WHERE id = " + n, null);
c.moveToFirst();
c.close();
pfiou!

How to update database when it's empty? Android

If you look at my code at the bottom, I have database with column 'used'. If it's 1 it means that it haven't been used, when it is used it set to update the number to 0. But when all of the rows have used number 0, that I would like to update used from 0 to 1 again. How to do that? I do not have a clue. Tried with cd.getCount() but did not work, try some other stuff too but again could not managed to get it to work. So I asking if anyone can help me and tell me what to put into code. Thank you!
This is the error I am getting:
02-25 18:46:16.962: E/AndroidRuntime(9728): android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
public void set(){
SQLiteDatabase db;
String vprasanje = "";
db=openOrCreateDatabase("baza.db",MODE_PRIVATE, null);
Cursor cd=db.rawQuery("SELECT * FROM vprasanja WHERE kategorija=" + kategorija4 + " AND used = 1 ORDER BY RANDOM() LIMIT 1", null);
cd.moveToFirst();
vprasanje = cd.getString(cd.getColumnIndex("text"));
//patch
String id2 = (cd.getString(cd.getColumnIndex("id")));
int idd2 = Integer.parseInt(id2);
db.execSQL("UPDATE vprasanja SET used=0 WHERE id =" + idd2 + ";");
beseda = (TextView) findViewById(R.id.textView3);
beseda.setText("");
beseda.setText(vprasanje);
db.close();
busy = 0;
}
Ok, so there are a couple of things in your code that need to be fixed. First, you need to check if cursor.moveToFirst() actually happened. You can't try to get strings if there are no records in the database.
First thing then:
if(cd.moveToFirst()){
vprasanje = cd.getString(cd.getColumnIndex("text"));
//patch
String id2 = (cd.getString(cd.getColumnIndex("id")));
int idd2 = Integer.parseInt(id2);
db.execSQL("UPDATE vprasanja SET used=0 WHERE id =" + idd2 + ";");
beseda = (TextView) findViewById(R.id.textView3);
beseda.setText("");
beseda.setText(vprasanje);
db.close();
busy = 0;
}
However, as long as you dont insert stuff into the database, this will always be false, because there will never be any records in your database. You'll want to insert stuff in case you can't update it:
db.rawQuery("INSERT INTO .... SET ... VALUES ...");

Dynamic SQLite queries

I'm trying to implement dynamic queries in my Android app, to let the users search according to some criteria. In this case I'm trying to search simply by an integer value. Here's my attempt:
...
public String[][] listarNegocio(int idProyecto,
int minimo,
int maximo)
{
String[][] arrayDatos = null;
String[] parametros = {String.valueOf(idProyecto)};
Cursor cursor = null;
cursor = querySQL("SELECT *" +
" FROM negocio" +
" WHERE ? in (0, id_proyecto)", parametros);
if(cursor.getCount() > 0)
{
int i = minimo - 1;
arrayDatos = new String[maximo - minimo + 1][20];
while(cursor.moveToNext() && i < maximo)
{
// Here I fill the array with data
i = i + 1;
}
}
cursor.close();
CloseDB();
return(arrayDatos);
}
public Cursor querySQL(String sql, String[] selectionArgs)
{
Cursor oRet = null;
// Opens the database object in "write" mode.
db = oDB.getReadableDatabase();
oRet = db.rawQuery(sql, selectionArgs);
return(oRet);
}
...
I tested this query using SQLFiddle, and it should return only the rows where the column id_proyecto equals the parameter idProyecto, or every row if idProyecto equals 0. But it doesn't return anything. If I remove the WHERE clause and replace "parametros" with "null", it works fine.
Additionally, I need to search by text values, using LIKE. For example, WHERE col_name LIKE strName + '%' OR strName = ''. How should I format my parameters and the query to make it work?
You should do one query for each case. For an id that exists, do SELECT * FROM negocio WHERE id_proyecto = ?. For an id that doesn't exist (I'm assuming 0 isn't a real id), just query everything with SELECT * FROM negocio.
Code should be something like this:
if(parametros[0] != 0){
cursor = querySQL("SELECT *" +
" FROM negocio" +
" WHERE id_proyecto = ?", parametros);
} else {
cursor = querySQL("SELECT *" +
" FROM negocio", null);
}
Regarding your second question, it depends on what you're looking for, you could use LIKE '%param%' or CONTAINS for occurrences in between text, LIKE param for partial matches or just = param if you're looking an exact match.

How to shuffle database Table entries using cursors and swapping values

This is a simple method to randomly shuffle certain database table entries based on a specific column value. Thanks to cbrulak's help, it now functions appropriately. It is not the most efficient by any means, but I thought I would just post it after the fix, as someone may find it somewhat useful.
/* The method will shuffle the specific entries in the table, based on column value */
public void shuffleDeck(int deck_id){
int i, j, count;
int loop1, loop2;
int num;
int id1, id2;
Random rand = new Random();
String front1, back1, front2, back2;
/* Create two separate content values for swapping the values between the two rows */
ContentValues updated_1 = new ContentValues();
ContentValues updated_2 = new ContentValues();
String[] columns = new String[]{CARD_ROWID, CARD_FRONT, CARD_BACK};
/* Create two cursors pointing to the same query */
Cursor cursor1 = Database.query(CARDS_TABLE, columns, DECK_ROWID + " = " + deck_id,
null, null, null, null);
Cursor cursor2 = Database.query(CARDS_TABLE, columns, DECK_ROWID + " = " + deck_id,
null, null, null, null);
cursor1.moveToFirst();
cursor2.moveToFirst();
int iRow = cursor1.getColumnIndex(CARD_ROWID);
int iFront = cursor1.getColumnIndex(CARD_FRONT);
int iBack = cursor1.getColumnIndex(CARD_BACK);
/* Get total number of entries in the cursor */
count = cursor1.getCount();
/* Loop through */
for(i=1; i<=count; i++){
num = rand.nextInt(count) + 1;
/* Acquire the values from the current row that will be inserted into the randomly selected row */
id1 = cursor1.getInt(iRow);
front1 = cursor1.getString(iFront);
back1 = cursor1.getString(iBack);
/* Move to the next row in cursor2 for a random number of times */
for (j=1; j<num; j++){
cursor2.moveToNext();
/* Fail safe to make sure it doesn't go out of bounds */
if(cursor2.isLast())
break;
}
/* Acquire the values from the random row */
front2 = cursor2.getString(iFront);
back2 = cursor2.getString(iBack);
id2 = cursor2.getInt(iRow);
/* Check to see if the second cursor is also pointing to the same position. */
if(!(front1.equals(front2) && back1.equals(back2))){
updated_1.put(CARD_FRONT, front2);
updated_1.put(CARD_BACK, back2);
updated_2.put(CARD_FRONT, front1);
updated_2.put(CARD_BACK, back1);
/* Call the database to UPDATE the values */
Database.update(CARDS_TABLE, updated_1, CARD_ROWID + " = " + id1, null);
Database.update(CARDS_TABLE, updated_2, CARD_ROWID + " = " + id2, null);
/* Clear the content values */
updated_1.remove(CARD_FRONT);
updated_1.remove(CARD_BACK);
updated_2.remove(CARD_FRONT);
updated_2.remove(CARD_BACK);
/* Requery the cursors */
cursor1 = Database.query(CARDS_TABLE, columns, DECK_ROWID + " = " + deck_id,
null, null, null, null);
cursor2 = Database.query(CARDS_TABLE, columns, DECK_ROWID + " = " + deck_id,
null, null, null, null);
/* Move cursor1 to the same position it was, right before requerying it */
for(loop1 = 1; loop1<=i; loop1++){
cursor1.moveToNext();
/* Fail save in case it tries to go out of bound */
if(cursor1.isLast())
break;
}
/* Move cursor2 to the same position it was, right before requerying it */
for(loop2 = 1; loop2<=j; loop2++){
cursor2.moveToNext();
/* Fail save in case it tries to go out of bound */
if(cursor2.isLast())
break;
}
}
/* Move the cursors to the new positions */
cursor1.moveToNext();
cursor2.moveToFirst();
}
cursor1.close();
cursor2.close();
}
request a new cursor after the update(s).
See: Android - Can you update a Cursor for SQLite results?
And more important: http://developer.android.com/reference/android/database/Cursor.html#requery() (they say to request new ones)
Bonus points for you: use a content provider. Save you tons of headache.

Can't get sqlite to update properly on Android

I am trying to update my sqlite database in Android.
I have this function, adjustPosition, which should adjust the position column of my rows based on the position I pass in.
For example, if position=4 and I have two rows with positions 4,5 respectively, then they should be 3,4 by the time the function returns.
public void adjustPosition(int position){
while(true){
Cursor query = mDb.rawQuery("select _ID, position from icon where position = " + position, null);
if(query != null){
if(query.getCount()==0){
query.close();
return;
}
query.moveToFirst();
long id = query.getLong(0);
int newPosition = position-1;
String sqlQuery = "update icon set position=" + newPosition + " where _ID=" + id;
boolean result = mDb.rawQuery(sqlQuery, null) != null;
String sqlQuery2 = "select position from icon where _ID="+id;
query = mDb.rawQuery(sqlQuery2, null);
query.moveToFirst();
int posn = query.getInt(0); // should equal newPosition, which is 3
position++; // have a breakpoint here
query.close();
} else {
return;
}
}
}
I have a breakpoint at the line 'positon ++;' . The value of posn should be 3, but for some reason it is 4. I have tried the SQL query using the SQLite Manager plugin in Firefox and it works fine so I don't think my SQL syntax is the problem. Do I have to commit db changes or something?

Categories

Resources