SQLitedatabase query - java

I have three columns in my database id ,message and message status and I only want to select only those rows from the list whose message status is 'r' and want to return the cursor from query for only id and message. I am new to databases,Please help.
My current code which is selecting all the rows is:
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,MySQLiteHelper.COLUMN_MESSAGE };
public List<Message> getAllMessages() {
List<Message> message = new ArrayList<Message>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_NAME,allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Message message1 = cursorToMessage(cursor);
message.add(message1);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return message;
}

SQLiteDatabase database = this.getReadableDatabase();
String queryz = "SELECT " + COLUMN_ID + "," + COLUMN_MESSAGE + " FROM " + TABLE_NAME + " WHERE " + COLUMN_MESSAGE_STATUS + "= 'r'";
Cursor c = database.rawQuery(queryz, null);

You need to pass a Where clause yo your query. It is the 4th parameter of the query(). It takes a String, and you should not include the Sqlite3 keyword WHERE (Android does that for you). The clause can be structured like MySQLiteHelper.COLUMN_MESSAGE+"="+"r"

Try this code,
public static final String KEY_ROWID = "row";
public static final String KEY_NAME = "name";
public Cursor fetchNamesByConstraint(String filter) {
Cursor cursor = mDb.query(true, DATABASE_NAMES_TABLE, null, "row LIKE '%" + filter + "%' or name LIKE '%" + filter + "%'",null, null, null, null);
}

Related

IllegalStateException on Cursor

I am getting this error when trying to read from the SQLite DB
IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
DbHelper dbHelper = new DbHelper(this);
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = dbHelper.readNumber(database);
String ItemId;
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
//getting the ERROR here
ItemId = cursor.getString(cursor.getColumnIndex(DbContract.ITEMID));
number = cursor.getString(cursor.getColumnIndex(DbContract.PHONE_NUMBER));
callType = cursor.getString(cursor.getColumnIndex(DbContract.CALL_TYPE));
callDate = cursor.getString(cursor.getColumnIndex(DbContract.CALL_DATE));
callDuration = cursor.getString(cursor.getColumnIndex(DbContract.CALL_DURATION));
arrayList.add(new PhNumber(ItemId, number, callType, callDate, callDuration));
if (debug) {
Log.i(TAG, "DATA FOUND IN DB:\n" + "\t ID: " + ItemId + ", Number: " + number + "\n");
}
}
cursor.close();
dbHelper.close();
result = true;
if (debug) {
Log.d(TAG, " Number of items in DB: " + arrayList.size());
}
}
readNumber
public Cursor readNumber(SQLiteDatabase database) {
String[] projections = {"id", DbContract.PHONE_NUMBER};
return (database.query(DbContract.TABLE_NAME, projections, null, null, null, null, null));
}
This is my DB
private static final String CREATE = "create table " + DbContract.TABLE_NAME +
"(id integer primary key autoincrement,"
+ DbContract.ITEMID + " text, "
+ DbContract.PHONE_NUMBER + " text, "
+ DbContract.CALL_TYPE + " text, "
+ DbContract.CALL_DATE + " text, "
+ DbContract.CALL_DURATION + " text, "
+ DbContract.SYNC_STATUS + " text)";
In your projection, created by readNumber call, you have only the id and PHONE_NUMBER columns returned. Probably DbContract.ITEMID is not equal to id and when trying to lookup the DbContract.ITEMID in the cursor it is not found. To fix this you need to use ITEMID in readNumber method, something like:
public Cursor readNumber(SQLiteDatabase database) {
String[] projections = {DbContract.ITEMID, DbContract.PHONE_NUMBER};
return (database.query(DbContract.TABLE_NAME, projections, null, null, null, null, null));
}
Another issue is that you are trying to access other fields too, like: CALL_TYPE, CALL_DATE, etc.
So, in order to fix the issue you either:
Do not try to retrieve the fields that are not part of the result.
Add the needed fields in the projection too.
Found the issue:
I was trying to access the columns that were not added in the projects in readNumber method adding those projections solved the issue.
readNumber
public Cursor readNumber(SQLiteDatabase database) {
String[] projections = {
DbContract.ITEMID,
DbContract.PHONE_NUMBER,
DbContract.CALL_TYPE,
DbContract.CALL_DATE,
DbContract.CALL_DURATION};
return (database.query(DbContract.TABLE_NAME, projections, null, null, null, null, null));
}

Retrieving row data from SQLite Db based on Unique Identifier

I have implemented an SQLite DB into my app and i am trying to write functions that will retrieve the data in a row associated with the unique identifier. I have tried a lot of stackoverflow answers and none seem to be working in my situation.
I have a database helper class where i have created the database through code and am writing the functions. See code below:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "TrackerNew.db";
public static final String TABLE_NAME = "tracker_new_table";
public static final String COL_2 = "LINETYPE";
public static final String COL_3 = "PACKAGETYPE";
public static final String COL_4 = "QUANTITY";
public static final String COL_5 = "DURATION";
public static final String COL_6 = "STARTTIME";
public static final String COL_7 = "ENDTIME";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1); }
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (LINETYPE TEXT PRIMARY KEY,PACKAGETYPE TEXT,QUANTITY TEXT,DURATION TEXT,STARTTIME TEXT,ENDTIME TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String linetype, String packagetype, String quantity, String duration, String starttime, String endtime) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,linetype);
contentValues.put(COL_3,packagetype);
contentValues.put(COL_4,quantity);
contentValues.put(COL_5,duration);
contentValues.put(COL_6,starttime);
contentValues.put(COL_7,endtime);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
//FUNCTIONS TO GET DATA BY ROW
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public Cursor getProgressBar1() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.query("select * from "+ TABLE_NAME + "where" + COL_2="S1");
return res;
}
public Cursor getProgressBar2() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.query("select * from "+ TABLE_NAME + "where" + COL_2="S2");
return res;
}
}
If you can see my functions at the bottom of my code i am trying to write raw queries to get the data by ID( S1,S2 Etc.)
Can anyone help me out with the code inside these functions?
Thanks!
The issue is that you are trying to create a string using:-
"select * from "+ TABLE_NAME + "where" + COL_2="S1"
This will not compile because you have misplaced the = and overwritten or omitted the + concatenation. I believe that you should have (see later):-
"select * from "+ TABLE_NAME + "where" + COL_2 + "=S1"
(+ added after COL_2 and = moved inside the quotes.
However I then believe that this would fail because you have omitted spaces before and after where, so the above would then resolve to:-
select * from tracker_new_tablewhereLINETYPE = S1
With spaces around where as per :-
"select * from "+ TABLE_NAME + " where " + COL_2 + "=S1"
It will then resolve to :-
select * from tracker_new_table where LINETYPE=S1
However, SQLite will then fail as S1 is not numeric and thus must be in quotes, so you need to actually code :-
"select * from "+ TABLE_NAME + " where " + COL_2 + "='S1'"
However coding :-
public Cursor getProgressBar1() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.query("select * from "+ TABLE_NAME + "where" + COL_2="S1");
return res;
}
Will then fail as the Cursor query method expects at least 7 parameters, as per :-
query(String table, String[] columns, String selection, String[]
selectionArgs, String groupBy, String having, String orderBy)
Query the given table, returning a Cursor over the result set.
SQLiteDatabase
So to use the query method the parameters would be:-
1) The name of the table to be queried so db.query(TABLE_NAME ......
2) A string array of the column names to extract, null means all and equates to *, so db.query(TABLE_NAME,null ......
3) The selection string (SELECT clause) (which can include placeholders i.e ? as per 4th parameter). Without place holders db.query(TABLE_NAME,null,COL_2 + "='S1'", or with a placeholder (generally considered the preferred method), db.query(TABLE_NAME,null,COL_2 + "=?" ......
4) The values to replace the placeholder(s) on a use once basis. So for a single place holder new String[]{"S1"} could be used, so the code now becomes db.query(TABLE_NAME,null,COL_2 + "=?",new String[]{"S1"} ......
5) A GROUP BY clause, null if not using one.
6) A HAVING clause, null if not using one.
7) An ORDER BY clause, null it not using one.
(Note clauses do not have the respective KEYWORDS the query method inserts them it also handles escaping/quoting)
The full query could/should be:-
Cursor res = db.query(TABLE_NAME,null,COL_2 + "=?",new String[]{"S1"},null,null,null);
Finally
And the ProgressBar1 method would be:-
public Cursor getProgressBar1() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.query(TABLE_NAME,null,COL_2 + "=?",new String[]{"S1"},null,null,null);
return res;
}
Edit after comment
As you want to also search for "S2" and "S3" then perhaps a single method could cope e.g.
public Cursor getProgressBar(String linetype) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.query(TABLE_NAME,null,COL_2 + "=?",new String[]{linetype},null,null,null);
return res;
}
Then for progress bar 1 you could use:-
Cursor progressbar1 = getProgressbar("S1");
for progress bar 2
Cursor progressbar2 = getProgressbar("S2");
etc
You could also shorten the getProgressBar method to :-
public Cursor getProgressBar(String linetype) {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_NAME,null,COL_2 + "=?",new String[]{linetype},null,null,null);
}
or even :-
public Cursor getProgressBar(String linetype) {
return this.getWritableDatabase().query(TABLE_NAME,null,COL_2 + "=?",new String[]{linetype},null,null,null);
}
Just try to modify this query:
Cursor res = db.query("select * from "+ TABLE_NAME + "where" + COL_2="S1");
to:
Cursor res = db.rawQuery("select * from "+ TABLE_NAME + " where " + COL_2 + " = ?", new String[] {"S1"});
and in getProgressBar2() method too. For more info look to https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

android.database.sqlite.SQLiteException: table has no such column

So I guess it is a very common issue, searching the web I found that I am not the only one who faced a such issue and yes I know that there is a question with almost the same title, however that did not help to solve the issue I am facing ... so let's start from the beginning
I am simply trying to insert into a table that I created.
This table has three columns: "id", "name", "value", and was created as following
public static final String TABLE_NAME = "cookie";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_VALUE = "val";
private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 2;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_NAME + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_VALUE + "text not null, "
+ COLUMN_NAME + " text not null"
+ ");";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
Now I am trying to insert into this table as following
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NAME, "username");
values.put(MySQLiteHelper.COLUMN_VALUE, username);
long insertId = database.insert(MySQLiteHelper.TABLE_NAME, null, values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_NAME, allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null, null, null, null);
cursor.moveToFirst();
nameValuePair newComment = cursorToNameValuePair(cursor);
cursor.close();
However I am getting this error
table cookie has no column named val
I searched for similar issues online, most of the solution where talking about a change happened to the database so I need to either
1- Un-install the application before trying to run in debugging mode again
2- update the database version from 1 to 3
However that did not help .. So looking forward for your solutions :)
Problem is here
+ COLUMN_VALUE + "text not null, "
into DATABASE_CREATE String. You missed space between column name and column type.
It should be
+ COLUMN_VALUE + " text not null, "

WHERE clause in Android SQLite

String[] columns = new String[]{ KEY_NAME, KEY_NUM };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + name, null, null, null, null);
This is the code I am using for returning those columns which match a particular string I have passed in i.e. name. However, this does not work. Also, If I replace the 'where' clause by null, all the rows are returned correctly. Please Help. Thanks!
The source table rows are thus
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "surveyString";
public static final String KEY_NUM = "numOfQuestions";
You should pass the where values into the "selectionArgs" parameter in your query.
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=?", new String[]{name}, null, null, null);
Have you tried put ' between the variable?
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "='" + name + "'", null, null, null, null);
public void addUserNotes(String notes,int id){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NOTES, notes);// Contact Phone Number
db.insert(TABLE_CONTACTS, null, values);
String s=Integer.toString(id);
final String[] whereArgs = {s};
db.update(TABLE_CONTACTS, values, "id = ?", whereArgs);
db.close(); // Closing database connection
}

Android sqlite helper error while getting data back

Hi all im using a sqlite helper class, but i have a little problem using a select statement.
I want to get the id of a datebase item by its name.
I use this select method:
public Cursor selectShift (String name){
SQLiteDatabase db = dbHandler.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, null, "name=" + name, null, null, null, null);
c.moveToFirst();
db.close();
return c;
}
And when i call this i use this:
if(handler.selectShift(name)!=null){
Cursor c = handler.selectShift(name);
id = c.getInt(c.getColumnIndex("_id"));
c.close();
}
And then is get this error:
android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
As if its not exists, but i checked the name string is correct, and when i display the names in a listview i see that name, so it exists.
Can someone help me how to fix this?
1 - there shoudld be check is there any data in cursor or not......c.getCount>0 or c.moveToFirst() or c.isAfterLast().......
if(handler.selectShift(name)!=null){
Cursor c = handler.selectShift(name);
if (c.moveToFirst()){ //<--------------
do{ //<---------if you not need the loop you can remove that
id = c.getInt(c.getColumnIndex("_id"));
}while(cursor.moveToNext());
}
c.close();
}
2- not sure but looks in select query as '<variable>' are not there in where clause with variable
"SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = '" + comment + "'";
or better to use parametrized statement
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new Sring[] {comment});
The issue appears to be here
"name=" <-It should be "name = "+name
Following should work
Cursor cursor= db.query(TABLE_IMAGES,null, "name" +" = ?", new String[]{name}, null, null, null);
Unless your name variable is already formatted (or not a TEXT) for sql I am guessing you need a little quotation. Maybe something like this
Cursor c = db.query(TABLE_NAME, null, "name= \'" + name + "\'", null, null, null, null);
Thanks for your help, i found the problem. It was in the cursor method, the solution is:
public Cursor selectShift (String name){
SQLiteDatabase db = dbHandler.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, new String[] {"_id"}, "name LIKE '"+name+"%'", null, null, null, null);
c.moveToFirst();
db.close();
return c;
}

Categories