I've got very strange problem.
My snippet is looking like that
public Wynik getData(int pomiar, int godzina) {
Wynik wynik = null;
String query = "SELECT * FROM " + "insulina" + " WHERE godzina = " + godzina +
" AND cukier = " + pomiar;
SQLiteDatabase db = this.getReadableDatabase();
try (Cursor cursor = db.rawQuery(query, null)) {
Log.i("tag", "cursor length:" + cursor.getCount());
if (cursor.getCount() > 0) {
String s = DatabaseUtils.dumpCursorToString(cursor);
Log.d("s", s);
cursor.moveToFirst();
wynik = new Wynik
(cursor.getInt(cursor.getColumnIndexOrThrow("godzina")),
cursor.getString(cursor.getColumnIndexOrThrow("insulina")),
cursor.getInt(cursor.getColumnIndexOrThrow("dawka")),
cursor.getString(cursor.getColumnIndexOrThrow("cialo")));
}
cursor.close();
return wynik;
(sorry for not English convention, but it was meant to be quick, routinely project)
Whole app idea is to help my friend with his grandmother's diabetes. He would insert an result of blood sugar level test (cukier) and time of test is checked automatically (godzina).
Based on those, app should return a whole result (wynik), with required dose of insulin (dawka), type of it (insulina) and part of body from which the blood should be taken (cialo).
Database looks like this:
So for example. The blood result is 10 (it's only thing which user is inserting) and it's 7 P.M (19, by 24-hours convention - the program is giving the closest hour of test, so it's 18). So, the query looks like
SELECT * FROM insulina WHERE godzina = 18 AND cukier = 10
And here's my problem. The app is recognizing cursor length as 0 (it should be 1) even if my other app related to database creation (DB Browser for SQLite) is giving out my result properly with the same query
Also Android Studio says that database is sucessfully opened.
I cannot find a fault here. And I'm really confused with this problem.
I think the query should be :
String query = "SELECT * FROM insulina WHERE godzina = ? AND cukier = ?";
SQLiteDatabase db = this.getReadableDatabase();
try (Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(godzina), String.valueOf(pomiar)})) {
//... rest of code
Also looks like you're using "try with resources" so the close isn't explicitly necessary.
Related
I want to insert records to my sqllite database but before insertion i have to check if the record exists .
I used this code but still say no such column and stopped working although the record exists .
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_TEAM + " WHERE "
+ TEAM_TABLE_NAME + " = " + name+";";
Log.e(LOG, selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
if (c != null) {
return true;
}
return false;
This is the recommended way to use rawQuery():
String selectQuery = "SELECT * FROM " + TABLE_TEAM + " WHERE " + TEAM_TABLE_NAME + " = ?";
Cursor c = db.rawQuery(selectQuery, new String[] {name});
so you pass name as a parameter to the query and avoid the risk of sql injection.
In your code you only check if the Cursor object is null and not if it contains any rows which is the right thing to do.
So return the result of getCount() > 0 like this:
return c.getCount() > 0;
This will return true if the name already exists in the table.
As for the no such column error, this is something different.
First make sure that TEAM_TABLE_NAME is the correct name of the column and if it is then maybe you made changes to the names of the columns tha are not reflected to the database.
So uninstall the app from the device so the database is deleted and then rerun to recreate the database with the new names of the columns.
so i recently learn to write a code in android using sqlite and i try to select data from sqlite but this error occur
ive tried some suggestion from the internet and read my book but i didnt solve my problem
public Penyakit getPenyakit1(String namaGejal){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT idPen FROM " + TABLE_CONTACTS + " WHERE " +
namapen + " =\"" + namaGejal + "\"";
Cursor cursor = db.rawQuery(query,null);
Penyakit penyakit = new Penyakit();
if(cursor.moveToFirst()){
cursor.moveToFirst();
penyakit.set_nomber(Integer.parseInt(cursor.getColumnName(0)));
penyakit.set_namaPen(cursor.getColumnName(1));
penyakit.set_idPenyakit(Integer.parseInt(cursor.getColumnName(2)));
penyakit.set_namGej(cursor.getColumnName(3));
penyakit.set_idGejala(Integer.parseInt(cursor.getColumnName(4)));
cursor.close();
} else {
penyakit=null;
}
return penyakit;
}
this is logcat
Process: com.example.lordbramasta.pakar, PID: 18914
java.lang.NumberFormatException: For input string: "idPen"
at java.lang.Integer.parseInt(Integer.java:615)
at java.lang.Integer.parseInt(Integer.java:650)
at com.example.lordbramasta.pakar.DBAdapter.getPenyakit1(DBAdapter.java:79)
i expected the value of idPen get selected , thank you
Your problem is this line:
penyakit.set_nomber(Integer.parseInt(cursor.getColumnName(0)));
cursor.getColumnName(0) returns idPen as this is the name of the only column returned by your query:
SELECT idPen FROM ....
and your code is trying to cast the string "idPen" to an integer.
So getColumnName() returns the name of the column at a specified index and not the value of the column.
You should do
penyakit.set_nomber(Integer.parseInt(cursor.getString(0)));
or if the data type of the column idPen is INTEGER then:
penyakit.set_nomber(cursor.getInt(0));
Also don't try to get any other columns because your query returns only 1.
Note: remove that cursor.moveToFirst(); inside the if block because it is already executed.
Probably you need to use a ' instead of ". So, change the query to the following:
String query = "SELECT idPen FROM " + TABLE_CONTACTS + " WHERE " +
namapen + " =\'" + namaGejal + "\'";
I'm suggesting you to use SQLiteDatabase.query() instead rawQuery like this:
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
"idPen"
};
// Filter results WHERE "namapen" = 'namaGejal'
String selection = "namapen" + " = ?";
String[] selectionArgs = { namaGejal };
// How you want the results sorted in the resulting Cursor
String sortOrder = null; // null for default order
Cursor cursor = db.query(
TABLE_CONTACTS, // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
// do something with the cursor
Please take a look Read information from a database
If you want to get all columns data from your TABLE_CONTACTS use SELECT * FROM
I am new in Android Studio and I just started to work with the SQLite
I created a SQLite file (db) and I created a function that put some data in the table:
public String FirstInsert()
{
String meassage = new String();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_2,"hi how are you?");
cv.put(COL_3,"blabla");
cv.put(COL_4,"blabla");
cv.put(COL_5,"blabla");
cv.put(COL_6,"blabla");
cv.put(COL_7,"blabla");
cv.put(COL_8,"blabla");
cv.put(COL_9,"blabla");
cv.put(COL_10,"blabla");
cv.put(COL_11,"blabla");
long result = db.insert(TABLE_NAME,null,cv);
if(result == -1)
{
meassage = new String("Bad");
}
else
{
meassage = new String("Good");
}
return meassage;
}
I want the do more spesific select that take only one item, the COL_2 and the row is number that I get so I wrote this code:
public Cursor GetQuestions(int num)
{
//num++;
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT QUESTION FROM " + TABLE_NAME + "ORDER BY " + num + "ASC LIMIT 1",null);
return res;
}
this is the right code? and if it is why I got an error here too?
Thank you very much for trying to help!
yes,that's because not having space between words of sqlite code
and it's better to close your cursor and your db after every query
like this
res.close();
db.close();
I just saw that i had to do space in the SQLite code like this:
Cursor res = db.rawQuery("SELECT QUESTION FROM " + TABLE_NAME + "**&**ORDER BY " + num + "**&**ASC LIMIT 1",null);
& = space (I write & to show where I added the spaces.
Am just curious, is date a reserved word i SQLite? I have a column which is named date, and trying to run this query:
DELETE FROM cases WHERE date <= date('now','-1 day')
By doing this:
String query = "DELETE FROM cases WHERE date <= date('now','-1 day')";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
boolean found = cursor.moveToFirst();
if(found) {
int result = cursor.getCount();
Log.w("DeleteOldCases: ", "Result: " + Integer.toString(result));
db.close();
}
But the cursor just gives me a false back, when calling moveToFirst. But in my database there are actually rows that are older than one day. Can anybody explain whats wrong here?
Thanks!
Yes it seems to be a reserved word.
look at: http://www.sqlite.org/lang_datefunc.html
date(timestring, modifier, modifier, ...)
It's strange to have a cursors form DELETE statement. Try to split the operation in
SELECT * FROM cases WHERE date <= date('now','-1 day')
then execute your checks
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
boolean found = cursor.moveToFirst();
if(found) {
int result = cursor.getCount();
Log.w("DeleteOldCases: ", "Result: " + Integer.toString(result));
db.close();
}
and then execute the DELETE part
DELETE FROM cases WHERE date <= date('now','-1 day')
This question is quite old but it deserves a proper answer.
No, date is not a reserved word.
The problem with your code is that you are using the method rawQuery() to delete from the table, which is not the way to do it.
rawQuery() should be used to return rows from the table in the form of a Cursor object.
Since your sql statement does not return any rows the method moveToFirst() returns false.
What you should use is the method delete() which returns the number of deleted rows:
int result = db.delete("cases", "date <= date('now', '-1 day')", null);
I'm working on a SMS application and I faced some problems retrieving the data from the ContentProvider using the GROUP BY clause.
I have read a lot of threads of similar questions, but they still do not provide a working solution for me.
What I want, is to get the most recent SMS from every thread. To achive this I have to select the maximum value of DATE column, and group it by THREAD_ID, I believe.
Suppose the SMS table looks like this:
============================
THREAD_ID | MESSAGE | DATE |
============================
1 | Hello | 555
1 | Hi | 666
2 | Test | 333
2 | Test 2 | 999
And the result should return the:
1 - Hi - 666
2 - Test 2 999
This is what I have so far, but the below code retrieves the most recent SMS from the whole table, not from specific category. It look like the GROUP BY clause is neglected.
String CONTENT_URI = "content://sms/";
Uri uri = Uri.parse(CONTENT_URI);
String selection = "date=(SELECT max(date) FROM sms )";
selection+=") GROUP BY (thread_id";
Cursor c = managedQuery(uri, null, selection, null, null);
if (c != null) {
while (c.moveToNext()) {
textView.append(c.getString(c.getColumnIndex(Column.THREAD_ID))
+ " - " + c.getString(c.getColumnIndex(Column.ADDRESS))
+ " - " + c.getString(c.getColumnIndex(Column.READ))
+ " - " + c.getString(c.getColumnIndex(Column.BODY))
+ " - " + c.getString(c.getColumnIndex(Column.DATE))
+ "\n");
}
c.close();
} else {
textView.setText("Cursor is null");
}
Thank you in advance, I would appreciate very much if you could help me find a solution for this case.
The GROUP BY clause is neglected because SELECT give only 1 value (in your code).
I don't know very well SQL but I think this should work (sry, I don't know exact syntax)
SELECT thread, message, MAX(date)
FROM sms
GROUP BY thread
use a library like CPH here to do all the boilerplate stuff for you. The example code shows all the query stuff that you need.
Implement as following
public Cursor query (SQLiteDatabase db, String[] projectionIn, String selection, String[] selectionArgs, String groupBy, String having, String sortOrder)
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
/* a String is a Object, so it can be null!*/
String groupBy = null;
String having = null;
switch (sUriMatcher.match(uri)) {
...
...
...
case EPISODES_NEXT:
groupBy = "ShowID";
queryBuilder.setTables(EpisodenTable.TableName);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
Cursor c = queryBuilder.query(db, projection, selection, selectionArgs,
groupBy, having, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}