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
}
Related
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);
}
I have a DB helper that does this function:
public Cursor getCourseNames() throws SQLException {
mDb = mDbHelper.getReadableDatabase();
return mDb.query("Course",null, COURSE_ROWID, null, null, null, null, null);
}
The table it is pulling from looks like this:
private static final String COURSE_ID = "CourseID";
private static final String COURSE_NAME = "Name";
private static final String COURSE_CODE = "CourseCode";
private static final String COURSE_ROWID = "_id";
private static final String COURSE_CREATE =
"create table " +
"Course" + " ( " +
COURSE_ROWID + " integer primary key autoincrement, " +
COURSE_ID + "integer not null," +
COURSE_NAME + "text not null, " +
COURSE_CODE + "text not null" + ");";
In my main activity I try this and get a null pointer...
public void buildCoursetoChapterList(){
Cursor cursor = dbHelper.getCourseNames();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cursor, null, null);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
Anyone have an idea what my problem is?
I put data into the db earlier on:
if(dbHelper.checkCourseForData() !=null)
{
setContentView(R.layout.classlist);
}
else
{
dbHelper.addFirstClassToDb(course_code, name, course_id);
Log.d+i("Course added to DB", course_code + " " + name + " " + course_id);
}
tried this and still nothing, I want to select all the Name values within Course.
No clue... losing hope.
public Cursor checkCourseForData() throws SQLException {
String[] values = {COURSE_NAME};
Cursor mCursor = mDb.query("Course",values,COURSE_ROWID + "=" + "Name", null, null, null, null, null);
if (mCursor != null) { mCursor.moveToFirst(); }
return mCursor;
}
It should be this
public Cursor getCourseNames() throws SQLException {
String[] values = {COURSE_NAME};
mDb = mDbHelper.getReadableDatabase();
return mDb.query("Course",values,COURSE_ROWID, null, null, null, null, null);
}
Explanation :
the medthod in the api has been defined as
public Cursor query (String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having, String orderBy)
So you need to pass the strings accordingly.
User my example as a reference it works for me
private String name;
private String Events_Table = "events";
private String[] Columns = {"_id", "Name", "Date", "Time_Slot", "Venue", "Details", "EHName", "EHNumber"} ;
private String WhereClause = Columns[1]+"=?" ;
Cursor cursor = db.query(Events_Table, Columns, WhereClause, new String[] {name}, null, null, null);
Consider Reading this
Parameters
table The table name to compile the query against.
columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
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;
}
when I try to search my database for a specific entry by using 'Washing Machine' as the search string to try and find the Database entry for 'Washing Machine', an error appears saying:
04-16 21:43:28.951: E/AndroidRuntime(545): FATAL EXCEPTION: main
04-16 21:43:28.951: E/AndroidRuntime(545): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lukeorpin.theappliancekeeper/com.lukeorpin.theappliancekeeper.EntryStatis tics}: android.database.sqlite.SQLiteException: near "Machine": syntax error: , while compiling: SELECT _id, appliance_name, appliance_wattage, energy_rates FROM ApplianceDetails WHERE appliance_name=Washing Machine
and more specifically to:
at com.lukeorpin.theappliancekeeper.Database.getWattage(Database.java:122)
04-16 21:43:28.951: E/AndroidRuntime(545): at com.lukeorpin.theappliancekeeper.EntryStatistics.onCreate(EntryStatistics.java:47)
Here is the code for the search query for the Database:
public String getWattage(String spinnerChoice) {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_WATTAGE, KEY_ENERGY};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + spinnerChoice, null, null, null, null);
if (c != null){
c.moveToFirst();
String wattage = c.getString(2);
return wattage;
}
return null;
}
public String getEnergyRate(String spinnerChoice) {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_WATTAGE, KEY_ENERGY};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + spinnerChoice, null, null, null, null);
if (c != null){
c.moveToFirst();
String energyRate = c.getString(3);
return energyRate;
}
return null;
}
and this is the original class where the method was created:
final String spinnerChoice = getIntent().getStringExtra("Name");
if(spinnerChoice==null){
return;
}
Database data = new Database(this);
data.open();
String returnedWattage = data.getWattage(spinnerChoice);
String returnedEnergyRate = data.getEnergyRate(spinnerChoice);
data.close();
Does anyone have any ideas why this error message is appearing? Thanks
EDIT: Here is the line of code that the error is pointing too (line 122):
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + spinnerChoice, null, null, null, null);
Given the error message, it seems like you don't have quotes denoting a string for the appliance_name value comparison. It should be
WHERE appliance_name = 'Washing Machine'
I'm not familiar with the api, but you can try changing line 122 to
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "='" + spinnerChoice + "'", null, null, null, null);
You need to enclose you search string in single quotes (in your SQL query).
Ok, so here is my database create statement:
create table entry (
_id integer primary key autoincrement,
date integer not null,
checknum integer,
payee text not null,
amount integer not null,
category text,
memo text,
tag text
);
After the datbase is created, and I make a call like:
mChecknum = cursor.getColumnIndex("checknum");
mChecknum is -1. I have pulled the database from the device and used SQLite Browser on it, and the checknum field is there.
Block around statement in question:
mDbHelper.open();
Cursor cursor = mDbHelper.fetchAll();
startManagingCursor(cursor);
COL_DATE = cursor.getColumnIndex("date");
Log.v("Main:123", "COL_DATE: " + String.valueOf(COL_DATE) );
COL_CHECKNUM = cursor.getColumnIndex("checknum");
Log.v("Main:125", "COL_CHECKNUM: " + String.valueOf(COL_CHECKNUM) );
COL_PAYEE = cursor.getColumnIndex("payee");
COL_DATE returns 1 and COL_PAYEE returns 2. Why is COL_CHECKNUM being ignored/passed over?
In my situation getColumnIndex was returning error on the column which had name which contained the "." symbol i.e.:
int colIndex = cursor.getColumnIndex("Item No.");
and despite the column "Item No." was inside the cursor (the debugger Watch showed it) trying to get the column index failed.
In my fetch/fetchAll database functions, I forgot to update the query with the new column.
For example, before i added the new column, my fetchAll code looked like:
public Cursor fetchAll() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE,
KEY_PAYEE, KEY_AMOUNT, KEY_CATEGORY, KEY_MEMO, KEY_TAG},
null, null, null, null, KEY_DATE + " desc");
}
After adding the new column to the database, my fetchAll function looks like:
public Cursor fetchAll() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE,
KEY_CHECKNUM, KEY_PAYEE, KEY_AMOUNT, KEY_CATEGORY, KEY_MEMO, KEY_TAG},
null, null, null, null, KEY_DATE + " desc");
}