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!
Related
I am creating a SQLite database in android. But there is some error appearing up whenever I call the method "displayDatabase()".
Please Help!!
Here is the displayDatabase() Method:
public void displayDatabase() {
DataDbHelper mDbHelper = new DataDbHelper(this);
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {DataContract.DataEntry.COLUMN_PROJECT_NAME,
DataContract.DataEntry.COLUMN_HEAD,
DataContract.DataEntry.COLUMN_CITY,
DataContract.DataEntry.COLUMN_COST};
Cursor c = db.query(DataContract.DataEntry.TABLE_NAME,
projection,
null,
null,
null,
null,
null);
TextView textView = (TextView) findViewById(R.id.textview);
try {
//textView.setText("The database contains - " + c.getColumnCount() + "Columns containing data");
textView.setText("Hello Welcome\n");
textView.append("-" + DataContract.DataEntry._ID
+ "---" + DataContract.DataEntry.COLUMN_PROJECT_NAME
+ "---" + DataContract.DataEntry.COLUMN_HEAD
+ "---" + DataContract.DataEntry.COLUMN_CITY
+ "---" + DataContract.DataEntry.COLUMN_COST + "\n");
int currentId = c.getColumnIndex(DataContract.DataEntry._ID);
int projectNameId = c.getColumnIndex(DataContract.DataEntry.COLUMN_PROJECT_NAME);
int headId = c.getColumnIndex(DataContract.DataEntry.COLUMN_HEAD);
int cityId = c.getColumnIndex(DataContract.DataEntry.COLUMN_CITY);
int costId = c.getColumnIndex(DataContract.DataEntry.COLUMN_COST);
while (c.moveToNext()) {
int id = c.getInt(currentId);
String projectName = c.getString(projectNameId);
String head = c.getString(headId);
String city = c.getString(cityId);
String cost = c.getString(costId);
textView.append("-" + id
+ "---" + projectName
+ "---" + head
+ "---" + city
+ "---" + cost);
}
} finally {
c.close();
}
}
And here is the error appearing in the logcat :
CursorWindow: Failed to read row 0, column -1 from a CursorWindow
which has 11 rows, 4 columns. 03-15 10:00:58.359 6348-6348/?
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.student.sampledatabase, PID: 6348
java.lang.IllegalStateException: Couldn't read row 0, col -1 from
CursorWindow. Make sure the Cursor is initialized correctly before
accessing data from it.
Add this column, DataContract.DataEntry._ID, to your projection.
The Cause of the Error
The reason for the failure is that an attempt is being to get a column at offset -1, which will never exist as offsets can be from 0 to the number of columns in the cursor less 1.
The reason why -1 is being used is because that is the value returned from the
Cursor getColumnIndex method when the column name passed to the method does not exist in the cursor.
The reason why you are getting the -1 is that you have not included the column who's name is as per DataContract.DataEntry._ID resolved in the cursor so the line :-
int currentId = c.getColumnIndex(DataContract.DataEntry._ID);
results in currentId being -1
Thus the above error when the following line is executed :-
int id = c.getInt(currentId);
The Fix
One fix, would be to specify null instead of projection, this would result in all columns of the table being retrieved and is the equivalent of using SELECT * FROM .......
e.g. by using :-
Cursor c = db.query(DataContract.DataEntry.TABLE_NAME,
null,
null,
null,
null,
null,
null);
Another fix would be to change :-
String[] projection = {DataContract.DataEntry.COLUMN_PROJECT_NAME,
DataContract.DataEntry.COLUMN_HEAD,
DataContract.DataEntry.COLUMN_CITY,
DataContract.DataEntry.COLUMN_COST};
to instead be :-
String[] projection = {DataContract.DataEntry._ID,
DataContract.DataEntry.COLUMN_PROJECT_NAME,
DataContract.DataEntry.COLUMN_HEAD,
DataContract.DataEntry.COLUMN_CITY,
DataContract.DataEntry.COLUMN_COST};
Thus the column will then be included in the Cursor and the offset will be the offset of that column (0 in the case above as it is the first column in the result).
I made an quiz android app where the user get score every time he finish the quiz and after that the score will be saved in the database and after that the user can display the saved score. and my question is how I can display or sort these score on the page score from the biggest score to the smallest.
this is my code where I get the score and name of the user and set it on a textview:
TextView tv1 = (TextView) findViewById(R.id.TextView1);
DbHelper info = new DbHelper(this);
userInfo.open();
String data = userInfo.getData();
userInfo.close();
tv1.setText(data);
my getData method:
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ID2, KEY_NAME, KEY_SCORE};
Cursor c = ourDbase.query(MyTABLE, columns , null, null, null, null, null);
String result ="";
int TheRow = c.getColumnIndex(KEY_ID);
int TheName = c.getColumnIndex(KEY_NAME);
int TheScore = c.getColumnIndex(KEY_SCORE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(TheRow ) + " " + c.getString(TheName ) + " " + c.getString(TheScore ) + "\n";
}
return result;
}
You can set ascending or descending in the last argument of your query. In your case, your getData() method can return your string with the KEY_SCORE column in descending order by changing the query line to this:
Cursor c = ourDbase.query(MyTABLE, columns , null, null, null, null, KEY_SCORE + " DESC");
Good Luck!
I try to get all unique values from database coulmn using SELECT DISTINCT sql command.
But i get exception when my activity is loading, i have this error code in logcat:
05-05 09:08:32.637: E/AndroidRuntime(1314): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workoutlog/com.example.workoutlog.AddWorkOutPage}: android.database.sqlite.SQLiteException: near "SELECT": syntax error (code 1): , while compiling: SELECT * FROM exerciseTable WHERE SELECT DISTINCTexercise_typefromexerciseTable
I think that i have not wrote the command correctly, here is my code:
public String[] getAllExercies() {
String selecet = "SELECT DISTINCT" + COLUMN_EXERCISE + "from" + TABLE_NAME;
Cursor c = ourDatabase.query(TABLE_NAME, null, selecet, null, null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_EXERCISE);
String[] list = new String[c.getCount()-1];
int j = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
list[j] = c.getString(dayExercise);
j++;
}
return list;
}
I think you should first checkout these answers here and here in order to see the working of .query() function.
Please note that while using ourDatabase.query() function, the parameters are as follows:
String Table Name: The name of the table to run the query against
String [ ] columns: The projection of the query, i.e., the columns to retrieve
String WHERE clause: where clause, if none then pass null
String [ ] selection args: The parameters of the WHERE clause
String Group by: A string specifying group by clause
String Having: A string specifying HAVING clause
String Order By by: A string Order By by clause
So your third variable should be a WHERE clause, something like:
String[] args = { "first string" };
Cursor c = ourDatabase.query("TABLE_NAME", null, "exercise_type=?", args, null, null, null);
Since you don't need a WHERE clause, for your purposes you might want to use rawQuery() method instead.
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " FROM " + TABLE_NAME;
ourDatabase.rawQuery(selecet, null);
Update
Try the answer from here. Do something like this:
Cursor c = ourDatabase.query(true, "exerciseTable", new String[] {"exercise_type"}, null, null, "exercise_type", null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_EXERCISE);
//... continue with your further code
Hope this helps else please comment.
Issue:
you have not maintained the space between the words.
Explaination:
suppose, String COLUMN_EXERCISE = "exercise";
and String TABLE_NAME = "tbl_workout";
then
String selecet = "SELECT DISTINCT" + COLUMN_EXERCISE + "from" + TABLE_NAME;
simply means,SELECT DISTINCTexercisefromtbl_workout
Solution:
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " from " + TABLE_NAME;
Edit:
Kindly use following syntax to fire rawQuery
Cursor c = ourDatabase.rawQuery(selecet,null);
I hope it will be helpful !
You miss all the spaces in your query, you should replace with this:
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " FROM " + TABLE_NAME;
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
I'm trying to create a simple Login form, where I compare the login id and password entered at the login screen with that stored in the database.
I'm using the following query:
final String DATABASE_COMPARE =
"select count(*) from users where uname=" + loginname + "and pwd=" + loginpass + ");" ;
The issue is, I don't know, how can I execute the above query and store the count returned.
Here's how the database table looks like ( I've manged to create the database successfully using the execSQl method)
private static final String
DATABASE_CREATE =
"create table users (_id integer autoincrement, "
+ "name text not null, uname primary key text not null, "
+ "pwd text not null);";//+"phoneno text not null);";
Can someone kindly guide me as to how I can achieve this? If possible please provide a sample snippet to do the above task.
DatabaseUtils.queryNumEntries (since api:11) is useful alternative that negates the need for raw SQL(yay!).
SQLiteDatabase db = getReadableDatabase();
DatabaseUtils.queryNumEntries(db, "users",
"uname=? AND pwd=?", new String[] {loginname,loginpass});
#scottyab the parametrized DatabaseUtils.queryNumEntries(db, table, whereparams) exists at API 11 +, the one without the whereparams exists since API 1. The answer would have to be creating a Cursor with a db.rawQuery:
Cursor mCount= db.rawQuery("select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass +"'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();
I also like #Dre's answer, with the parameterized query.
Use an SQLiteStatement.
e.g.
SQLiteStatement s = mDb.compileStatement( "select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass + "'; " );
long count = s.simpleQueryForLong();
See rawQuery(String, String[]) and the documentation for Cursor
Your DADABASE_COMPARE SQL statement is currently invalid, loginname and loginpass won't be escaped, there is no space between loginname and the and, and you end the statement with ); instead of ; -- If you were logging in as bob with the password of password, that statement would end up as
select count(*) from users where uname=boband pwd=password);
Also, you should probably use the selectionArgs feature, instead of concatenating loginname and loginpass.
To use selectionArgs you would do something like
final String SQL_STATEMENT = "SELECT COUNT(*) FROM users WHERE uname=? AND pwd=?";
private void someMethod() {
Cursor c = db.rawQuery(SQL_STATEMENT, new String[] { loginname, loginpass });
...
}
Assuming you already have a Database (db) connection established, I think the most elegant way is to stick to the Cursor class, and do something like:
String selection = "uname = ? AND pwd = ?";
String[] selectionArgs = {loginname, loginpass};
String tableName = "YourTable";
Cursor c = db.query(tableName, null, selection, selectionArgs, null, null, null);
int result = c.getCount();
c.close();
return result;
how to get count column
final String DATABASE_COMPARE = "select count(*) from users where uname="+loginname+ "and pwd="+loginpass;
int sometotal = (int) DatabaseUtils.longForQuery(db, DATABASE_COMPARE, null);
This is the most concise and precise alternative. No need to handle cursors and their closing.
If you are using ContentProvider then you can use:
Cursor cursor = getContentResolver().query(CONTENT_URI, new String[] {"count(*)"},
uname=" + loginname + " and pwd=" + loginpass, null, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
If you want to get the count of records then you have to apply the group by on some field or apply the below query.
Like
db.rawQuery("select count(field) as count_record from tablename where field =" + condition, null);
Another way would be using:
myCursor.getCount();
on a Cursor like:
Cursor myCursor = db.query(table_Name, new String[] { row_Username },
row_Username + " =? AND " + row_Password + " =?",
new String[] { entered_Password, entered_Password },
null, null, null);
If you can think of getting away from the raw query.
int nombr = 0;
Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
nombr = cursor.getCount();