I'm writing an android application and I need to search the data base, this is the method I use:
public Cursor getData(String table, String keyword, SQLiteDatabase db){
String selection;
Cursor cursor;
switch (table){
case "User":
String [] projection = {id,name,phone};
selection = "username LIKE ?";
String [] selection_arg = {keyword};
cursor = db.query("User",projection,selection,selection_arg,null,null,null);
break;
//omitted
default:
return null;
}
return cursor;
The user put in the keyword
keyword = search_user.getText().toString();
Cursor cursor = dbHelper.getData(ShippingApplication.User.USER_TABLE,keyword,db);
The code does not work, when I debug, I see the mQuery of the db variable is:
SQLiteQuery: SELECT userID, userName, phoneNumber FROM User WHERE userName LIKE ?
It looks like the query does not pass the value of the keyword in to the sql command.
Could someone tell me what's wrong?
EDIT 2: I change the code a little bit and now it works:
String selection = ShippingApplication.User.name + " LIKE '%" + keyword + "%'";
Cursor cursor = db.query(The table name,projection,selection,null,null,null,null);
try this way
please check your SQLiteDatabase object is not null
after that check Table is created or not
i get the cursor count i already debug it and it's working fine for me
public Cursor getData(String table, String keyword, SQLiteDatabase db){
String selection;
Cursor cursor;
switch (table){
case "Tbl_staticContent":
String [] projection = {"PageTitle","Content"};
selection = "PageTitle LIKE ?";
String [] selection_arg = {keyword};
cursor = db.query("Tbl_staticContent",projection,selection,selection_arg,null,null,null);
Log.e("count",""+cursor.getCount());
//I have create table and stored data and also check the like condtion also it's work fine and get the cursor.getCount() > 0 also .
break;
default:
return null;
}
return cursor;
}
Related
I'm working on an small android app that maintains a small database of tools which I lend out to other people.
As part of the app, I am incorporating an sqllite database, where I am having a bit of trouble performing queries and working with cursors once the queries have been executed.
The code in question is as follows:
String COLUMN_NAME = "toolName";
String[] columns = { COLUMN_NAME };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = {tool};
Cursor cursor = mToolDb.query(ToolStatisticContract.ToolStatisticEntry.TABLE_NAME, columns,
selection, selectionArgs, null, null, null, null);
return Integer.parseInt(cursor.getString(3));
The contract for the database is as follows:
public class ToolStatisticContract {
public static final class ToolStatisticEntry implements BaseColumns {
public static final String TABLE_NAME = "tooltable";
public static final String COLUMN_TOOL_NAME = "toolName";
public static final String COLUMN_LIFESPAN = "lifespan";
public static final String COLUMN_USAGE = "usageTime";
}
}
I am essentially trying to extract out the value from COLUMN_USAGE, which seems to be producing errors with regards to parsing the value to an integer. The value in the COLUMN is actually an integer typecasted as a String from a previous segment of code, so I'm fairly certain the error is encompasssed with the code snippets above.
Thanks again in advance for all your help!
The code in question is as follows
The net SQL statement is something like:
SELECT toolName FROM tooltable WHERE toolName = ?
And there is no column with index 3, since you are only returning 1 column.
You need to:
Have usageTime in your column list (COLUMNS)
Move the Cursor to a valid row (as it initially is positioned before the first row)
Pass getInteger() the value that lines up with COLUMNS to retrieve usageTime
You could use the following. This uses null instead of columns, which will get all columns (i.e. resolves to SELECT * FROM table). It checks that a row has been returned and only then does it try to get the data. It also closes the cursor (you should close a cursor when done with it). It uses cursor.getInt() to get the integer value rather than convert it from a string to int. It assumes that you'll only get 1 row (if no rows then 0 will be returned).
int returnvalue = 0;
String COLUMN_NAME = "toolName";
String[] columns = { COLUMN_NAME };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = {tool};
Cursor cursor = mToolDb.query(ToolStatisticContract.ToolStatisticEntry.TABLE_NAME, null,
selection, selectionArgs, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
returnvalue = cursor.getInt(2);
//or returnvalue = Integer.parseInt(cursor.getString(2));
}
cursor.close();
return returnvalue;
Note! I haven't checked this just coded it from memory, so apologies for the odd mistake.
To do the above using specific columns then you could use:-
String COLUMN_NAME = "toolName";
String[] columns = { COLUMN_USAGE };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = {tool};
Cursor cursor = mToolDb.query(ToolStatisticContract.ToolStatisticEntry.TABLE_NAME, columns,
selection, selectionArgs, null, null, null, null);
In which case the column index would be 0 (that is the index is according to the column's in the cursor). However it might be better to use, the following which gets the column index according to the column's name:-
cursor.getInt(cursor.getColumnIndex(COLUMN_USAGE);
The easiest way to read a single value from the database is to use a helper function that allows you to avoid having to handle cursor objects:
String query = "SELECT usageTime FROM tooltable WHERE toolName = ?";
String[] selectionArgs = { tool };
long returnvalue = DatabaseUtils.longForQuery(mToolDb, query, selectionArgs);
I am developing an application where the user inputs title and the date. I want to prevent the duplicated titles being inputted on the same day in to database. I am checking if the title exists on the selected date. However my query seems not to work and i don't know why, the application just crashes.Is this query correct? Can someone help?
public boolean checkExist(String title, String date) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE "+TITLE+"=?" +"AND" + DATE+"=?", new String[] {title,date});
boolean exists = c.moveToFirst();
c.close();
return exists;
}
One issue that you have is that c.moveToFirst will always fail if a match does not exist as you are trying to move to a row in an empty cursor.
The resolution is to not use c.moveToFirst and instead get the count of the rows and then set the return value accordingly.
e.g.
public boolean checkExist(String title, String date) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE "+TITLE+"=?" +"AND" + DATE+"=?", new String[] {title,date});
boolean exists = c.getCount() > 0;
c.close();
return exists;
}
The second issue is that the query itself is wrong as you do not have spaces either side of the AND keyword. That is instead of
Cursor c = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE "+TITLE+"=?" +"AND" + DATE+"=?", new String[] {title,date});
You should have
Cursor c = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE "+TITLE+"=?" +" AND " + DATE+"=?", new String[] {title,date});
Personally, I setup constants for SQL keywords that include the space and then use these. So I'd have something along the lines of +TITLE+"=?" + SQLAND + DATE+"=?". Where SQLAND would be defined along the lines of String SQLAND=" AND ";
PS look at Cricket_007's answer, the code is neater/better it's easier to read.
Your spacing is off. TITLE+"=?" +"AND" + DATE becomes TITLE=?ANDDATE=?
I would suggest this. See DatabaseUtils.queryNumEntries
public boolean checkExist(String title, String date) {
SQLiteDatabase db = getReadableDatabase();
String[] args = new String[] {title,date};
String filter = String.format("%s=? AND %s=?", TITLE, DATE);
return DatabaseUtils.queryNumEntries(db, TABLE_NAME, filter, args) > 0;
}
you should be using c.getCount() instead of c.moveToFirst()
if the value is greater than 0, then it exists
I'm trying to do a particular function for my code. Suppose, in my database, there is an entry called tandoori chicken. How do I code the SQL part so that I can filter the database with chicken tandoori and not just fixed on tandoori chicken?
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "FoodDatabase1.sqlite";
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
And the getFood function.
/*
* Receive searchQuery in string form
* return Cursor object
*/
public Cursor getFood(String searchQuery) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"_id", "FOOD", "CALORIES"};
String sqlTables = "fooddb1";
String whereClause=null;
String[] whereArgs=null;
/*
*if searchQuery is empty then null will be passed in query() function which
*will display all rows
*if searchQuery is not null it will look for match in the table
*/
if(!searchQuery.equals("")){
whereClause="Food LIKE ?";
/*
*LIKE statement will look for substring in the table if found it will add that row to cursor
*/
whereArgs= new String[] {
"%"+searchQuery+"%"
};
}
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, whereClause, whereArgs,
null, null, null);
c.moveToFirst();
return c;
}
You just need to split the substrings by space. For example, you've tandoori chicken as search query string. So, now you need to split the query string by space to make two separate words- tandoori and chicken.
Then the sql query should look like
Select * from foodTable where Food like 'tandoori chicken' or 'chicken tandoori'
To achieve this you might consider doing something like this.
String[] queryWords = searchQuery.split(" "); // Split by space
Now make the words and put them in an ArrayList.
private ArrayList<String> getQueryStrings(String[] queryWords) {
private ArrayList<String> queryStringList = new ArrayList<String>();
// Now let us do some combination of words here and add each combination in the ArrayList.
for(int i = 0; i < possibleCombinationCount; i++)
queryStringList.add(getWordsCombination(i));
return queryStringList;
}
Now make the query string as you like.
String builder = "";
for(String wordsComb : getQueryStrings()) {
// make the query with or
if(builder.length != 0) builder += " or ";
builder += "'%" + wordsComb + "%'";
}
String query = "Select * from foodTable where Food like " + builder;
Now run the rawQuery() on your database.
db.rawQuery(query);
This solution may work well for two or three words in a string while it won't work well for long strings.
If your search is flexible like you just want to find the rows matched with the given strings you might consider using the IN statement.
Select * from foodTable where Food in (queryWords[0], queryWords[1], ....)
Just you need to build the database query of your own with the values separated from the query string by space in queryWords array.
I found this answer relevant to your question too.
I am trying to create a SQLite database for my Android app.
Everything worked fine until I got to the JUnit Testing for the query function in ContentProvider.
I read the forum very in depth, and saw that some people have the errors below
Create table has typos in it - here's my table creation statement
CREATE TABLE movie (
_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
overview TEXT DEFAULT 'NO OVERVIEW',
poster_path TEXT DEFAULT 'NO POSTER',
release_date TEXT DEFAULT 'NO DATE AVAILABLE',
vote_average TEXT DEFAULT 'NO VOTES YET',
sort_type INTEGER NOT NULL,
favorite INTEGER DEFAULT 0
);
Not updated Database_Version constant once the column was added.
I tried updating the Database_Version constant and I also tried changing the name of the database, so it is created from scratch.
Deleted all of my old app from my Android device.
Read this post.
I did check for all of the nuances it speaks about.
However, I still have my exception being thrown
android.database.sqlite.SQLiteException: no such column: MovieContract.Movie.favorite (code 1): , while compiling: SELECT * FROM movie WHERE MovieContract.Movie.favorite = ? ORDER BY MovieContract.Movie.title
My testCase method that throws the error.
Error is being thrown on the line Cursor movieCursor...
public void testBasicMovieQuery(){
MovieDBHelper dbHelper = new MovieDBHelper(mContext);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues movieValues = TestUtilities.createMovieValues();
long recordNum = db.insert(MovieContract.Movie.TABLE_NAME, null,movieValues);
assertTrue("Unable to Insert WeatherEntry into the Database", recordNum != -1);
db.close();
String selection = "MovieContract.Movie.FAVORITE = ?";
String [] selectionArgs = new String [] {"'1'"};
String sortOrder = "MovieContract.Movie.TITLE";
Cursor movieCursor = mContext.getContentResolver().query(
MovieContract.Movie.CONTENT_URI,
null,
selection,
selectionArgs,
sortOrder
);
TestUtilities.validateCursor("testBasicWeatherQuery", movieCursor, movieValues);
movieCursor.close();
}
Here is my query method in my ContentProvider; so when I have 'selection' defined it throws me the 'no such column' but if I put all null, besides the URI it will throw the Unknown Uri exception from the default, even though the Uri actually exists in UriMatcher.
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor cursor;
Log.v("QUERY MovieProvider", uri.toString());
switch (uriMathcher.match(uri)){
case MOVIE_WITH_ID:{
Log.v("MovieProvider QUERY", "MOVIE WITH ID");
//cursor = getMovieWithId(uri);
cursor = dbHelper.getReadableDatabase().query(MovieContract.Movie.TABLE_NAME ,null, "MovieContract.Movie._ID =", selectionArgs,null,null,sortOrder);
}
break;
case MOVIE:{
Log.v("MovieProvider QUERY", "MOVIE");
//Log.v("MovieProvider QUERY", selection);
//Log.v("MovieProvider QUERY", selectionArgs[0]);
cursor = dbHelper.getReadableDatabase().query(MovieContract.Movie.TABLE_NAME, null,selection, selectionArgs, null, null, sortOrder);
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
Please let me know if any additional information is required.
My Github repository is here
Please change these lines:
String selection = "MovieContract.Movie.FAVORITE = ?";
String [] selectionArgs = new String [] {"'1'"};
String sortOrder = "MovieContract.Movie.TITLE";
to
String selection = MovieContract.Movie.FAVORITE + " = ?";
String [] selectionArgs = new String [] {"1"};
String sortOrder = MovieContract.Movie.TITLE;
or to (will work as well)
String selection = "favorite = ?";
String [] selectionArgs = new String [] {"1"};
String sortOrder = "title";
i am trying to do a query of my database for a string lets call it "Test" and then find out what row that particular string is in and save that number to use. I thought i had this figured out before but now it is not working for some reason and i get an error saying no such column "Test".
here is my code
public String getRow(String value){
ContactDB db = new ContactDB(this);
db.open();
Cursor curs = db.getId(value);
String test = curs.getString(curs.getColumnIndex(db.NAME));
curs.close();
Log.v("Contact", "Row ID: " + test);
db.close();
return test;
}
"Test" is sent into that as value
this is in my database
//---retrieve contact id---
public Cursor getId(String where){
Cursor c = db.query(DATABASE_TABLE, new String[] {ID},where,null,null,null,null);
if (c != null)
c.moveToFirst();
return c;
}
i dont remember changing anything from when i first tested it so i dont know why it wont work now
There are 2 errors that i could notice:
In the query
Cursor c = db.query(DATABASE_TABLE, new String[] {ID},where,null,null,null,null);
only the ID column is selected whereas you are trying to fetch details for column NAME
String test = curs.getString(curs.getColumnIndex(db.NAME));
include the name column as well in the select clause : something like
Cursor c = db.query(DATABASE_TABLE, new String[] {ID,NAME},where,null,null,null,null);
In the where clause you need to write the condition string excluding "where"
in your case String where contains value "Test". Hence the filter condition should be as
String whereClasue = NAME + " = '" + where + "'";
The query should be something like this:
public Cursor getId(String where){
Cursor c = db.query(DATABASE_TABLE, new String[] {ID,PHONE_NUMBER,NAME},NAME + " = '" + where + "'",null,null,null,null);
if (c != null)
c.moveToFirst();
return c;
}