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");
}
Related
I currently I have my database set up like the following:
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LOCKERNUMBER
+ " TEXT NOT NULL, " + KEY_STATUS + " INTEGER, " + KEY_PIN
+ " INTEGER);");
And I am trying to write a method to get the pin code from the column for a specific locker number. Any ideas? I am very new I would like think I would need to use the query function and a cursor. I just one to get the integer value and store it into an int variable so I can compare the pin codes from what the user types in to the one in the database.
Queries to database returns in a Cursor object. You should use the db.query() method to get a row(s). Pass the table name, an array of columns you want to get (or null if you want all of them), pass a selection string that should be like "id = ?" or "key > ?", etc, then pass a String array containing the value for those ? inside the previous string,
and finally pass null for having, groupBy and orderBy unless you want to use them.
Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ROWID }, "id = ?", new String[] { Integer.toString(id) }, null, null, null);
After you get the Cursor, do cursor.moveToFirst() or cursor.moveToPosition(0) (can't remember the exact method, but the point is to move the cursor to the first retrieved row)
then you're going to iterate through the cursor with
while(cursor.moveToNext()) {
int keyRowIdColumnIndex = cursor.getColumnIndex(KEY_ROWID);
int yourValue = cursor.getInt(keyRowIdColumnIndex);
int keyLockNumberColumnIndex = cursor.getColumnIndex(KEY_LOCKNUMBER);
int pin = cursor.getInt(keyLockNumberColumnIndex);
}
This is a pretty straight forward task and there is a bunch of tutorials, examples, similar questions on SO:
How to perform an SQLite query within an Android application?
In general - you need to query the database passing your search arguments. See the documentation.
It will return you a Cursor with the matching results, which you can then iterate over and manipulate as you wish.
Fyi - storing password in a database table is a bad idea. On Android databases can be accessed and easily read. You either need to encrypt your data or think of another way to store it if it's important.
//Try This code
public String getLabeId(String LockNo)
{
ArrayList<String> Key_Pin_array = new ArrayList<String>();
Cursor cur = db.rawQuery("SELECT * FROM DATABASE_TABLE where KEY_LOCKERNUMBER = '" + LockNo + "'", null);
try {
while (cur.moveToNext())
{
System.out.println("Key_Pin" + cur.getString(3));
Key_Pin_array.add(cur.getString(3));
}
}
catch (Exception e)
{
System.out.println("error in getLabelID in DB() :" + e);
}
finally
{
cur.close();
}
return id;
}
textAs the title describes I'm trying to get all rows from a table where strings of a column contains a string anywhere in it. But they way I'm doing it now always return -1 rows.
This is how i'm doing it now but I have no idea of what I might be doing wrong. Suggestions?
Cursor cursor = database.query(DBHelper.TABLE_RECENT, null, DBHelper.COLUMN_TEXT+ " LIKE '%"+club_id+"%'", null, null, null, null);
Just write cursor.moveToFirst(); before getting data from cursor or just under query line.
Hope it will help you.
I guess, you're mis interpreting the structure of query. the second parameter is what you want to select. such as "select column1, column2 etc. Here's a line from my code, and it works for me.
Cursor cursor = db.query(table_employees, new String[] {KEY_ID, KEY_NAME,KEY_DEPARTMENT, KEY_PHONE_NUMBER, KEY_SALARY}, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null);
here "new string[] {key_id.....", the second parameter, is column names, that you wanted to select.
OR
alternately, you may simply do as:
String query = "Select * from "+DB_TABLE+ "Where" +column1 + "=" + t +"and"+ column2 + "=" +tt
db.rawQuery(query);
if you do something like,
String query = "Select * FROM Product where name LIKE '%" + Text + "%'"
Log.d("search query", query);
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
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
}
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;
}