Quotes around strings in sqlite query - java

I have a db made with this statement:
DATABASE_CREATE = "create table "
+ TABLE_BANDS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_NAME
+ " text unique not null, " + COLUMN_GENDER + " text, " + COLUMN_POPULARITY + " real not null);";
I add to it a row with this statement:
private long addBand(String bandName, String gender) {
ContentValues values = new ContentValues();
values.put(BandsSQLiteOpenHelper.COLUMN_NAME, "\"" + bandName.trim().toLowerCase() + "\"");
values.put(BandsSQLiteOpenHelper.COLUMN_POPULARITY, 1);
values.put(BandsSQLiteOpenHelper.COLUMN_GENDER, "");
long insertId = database.insert(BandsSQLiteOpenHelper.TABLE_BANDS, null,
values);
return insertId;
}
I get insertId > 0, so I think that the insertion was ok.
Then I try to select a row that I just inserted with this code:
public Band getBand(String name) {
Cursor cursor = database.query(BandsSQLiteOpenHelper.TABLE_BANDS,
new String[] {BandsSQLiteOpenHelper.COLUMN_NAME, BandsSQLiteOpenHelper.COLUMN_POPULARITY}, BandsSQLiteOpenHelper.COLUMN_NAME + " = \"" + name.trim().toLowerCase() + "\"", null,
null, null, null);
cursor.moveToFirst();
Band band = getBandFromCursor(cursor);
cursor.close();
return band;
}
But it always returns me a cursor with 0 length.
I tried to remove the quotes around the name, but after it query doent work.
Besides I tried to use a rawQuery, but the result is the same.
Cursor cursor = database.rawQuery("Select * from " + BandsSQLiteOpenHelper.TABLE_BANDS + " where band_name = \"" + name.trim().toLowerCase() + "\"", null);
UPDATE:
I tried single quotes:
Cursor cursor = database.query(BandsSQLiteOpenHelper.TABLE_BANDS,
new String[] {BandsSQLiteOpenHelper.COLUMN_NAME, BandsSQLiteOpenHelper.COLUMN_POPULARITY}, BandsSQLiteOpenHelper.COLUMN_NAME + " = \'" + name.trim().toLowerCase() + "\'", null,
null, null, null);
and
private long addBand(String bandName, String gender) {
ContentValues values = new ContentValues();
values.put(BandsSQLiteOpenHelper.COLUMN_NAME, "\'" + bandName.trim().toLowerCase() + "\'");
values.put(BandsSQLiteOpenHelper.COLUMN_POPULARITY, 1);
values.put(BandsSQLiteOpenHelper.COLUMN_GENDER, "");
long insertId = database.insert(BandsSQLiteOpenHelper.TABLE_BANDS, null,
values);
return insertId;
}
As before insertion is ok, selection returns 0 rows.

When inserting the values, I doubt you need to put the double quotes around the values you insert since you specified in your DB Creation string that the fields are TEXT.
As for your rawQuery, try this:
"SELECT * FROM " + BandsSQLiteOpenhelper.TABLE_BANDS + " WHERE band_name = '" + name.trim().toLowerCase() + "'";
Try single quotes instead of double quotes when using Strings as identifiers in WHERE statements.

Related

SQL - How to return a list of data

I have this SQL method below, it is suppose to return multiple rows of data, but it is only returning one item every time I try to display the data.
How do I fix that?
//Constant
public static final String COL_4 = "LikeSong";
//Database Table
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE UserInfo(ID INTEGER PRIMARY KEY AUTOINCREMENT, Users_Name TEXT, PlaylistName TEXT,likeAlbum TEXT,LikeSong TEXT)");
}
public String[] getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
String[] LikeSong = null;
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
LikeSong = note.split(",");
}
cursor.close();
db.close();
return LikeSong;
}
Inside the while loop in each iteration you change the value of LikeSong, so when the loop ends, LikeSong has the last value assigned to it.
I think that you want a list of arrays returned by your method getLikedSongs() like this:
public List<String[]> getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
List<String[]> list = new ArrayList<>();
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
LikeSong.add(note.split(","));
}
cursor.close();
db.close();
return LikeSong;
}
Okay...now I see. You are reassigning LikeSong for each iteration of the while loop and returning the String array after the while loop has completed. So obviously, you will get value of only the last row.

How to pass specific string to get the specific value from database android

I have three columns where trailer_number and trailer_id are strings
id trailer_number trailder_id
1 trailer1 766
2 trailer2 899
3 trailer3 577
Now if I pass the trailer_number, how to get the specific trailer_id.
Say for eg: trailer1 if i pass, how to return the string "766"?
I can do only if that specific string is exist or not but I am cluless how to pass to get the specific id.
public boolean isExist(String strTrailerNumber) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE TRAILER_NUMBER = '" + strTrailerNumber + "'", null);
boolean exist = (cur.getCount() > 0);
cur.close();
db.close();
return exist;
}
Tryout as below :
String query = "SELECT trailder_id FROM TABLE_NAME WHERE TRAILER_NUMBER =" + strTrailerNumber ;
Cursor cursor = database.rawQuery(query,null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() != true) {
string trailder_id = cursor.getString(cursor.getColumnIndex("trailder_id")));
}
}
There might be some syntax error in Query, change it. It will work.
use the query
"SELECT trailder_id FROM " + TABLE_NAME + " WHERE TRAILER_NUMBER = '" + strTrailerNumber + "'"
and use
cursor.moveToFirst()
String trailer_id = cursor.getString(0)
to get the trailder_id

Cannot Fetch a Data From Database

First of all i'm new to Android Development.
I'm having some issues with fetching data from database. Whenever i try to fetch a data, the cursor is being empty.
Here is my code:
public ArrayList<Word> getWords(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
ArrayList<Word> List = new ArrayList<Word>();
if(cursor != null){
cursor.moveToFirst();
while (cursor.moveToNext()){
List.add(new Word(cursor.getString(cursor.getPosition())));
}
}
cursor.close();
db.close();
return List;
}
The size of the cursor is always 1 but the size of the "List" variable is always 0.
I didn't understand the problem, thanks for helping me.
You are shifting the cursor position twice. Just remove the line cursor.moveToFirst(); The moveToNext method is sufficient as it moves to the first position on the first iteration.
you can use this code:
1-If you need first row:
if(cursor != null){
cursor.moveToFirst();
if(cursor.isAfterLast() == false){
List.add(new Word(cursor.getString(cursor.getPosition())));
}
}
2- if you need several rows :
if(cursor != null){
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
List.add(new Word(cursor.getString(cursor.getPosition())));
cursor.moveToNext();
}
}
I checked everything but your recommendations didn't worked. Just to be sure: I want to fetch all rows.
Try like this
public ArrayList<Word> getWords(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
ArrayList<Word> list = new ArrayList<Word>();
if(cursor != null){
while (cursor.moveToNext()){
list.add(new Word(cursor.getString(cursor.getPosition())));
}
}
cursor.close();
db.close();
return list;
}
I just realised that the program does not go into the while loop in the code that i given above. I think there is a problem with database.
I used that query to create database:
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME_TURKISH + " TEXT, " +
COLUMN_NAME_ENGLISH + " TEXT, " +
COLUMN_NAME_GERMAN + " TEXT, " +
COLUMN_NAME_FRENCH + " TEXT, " +
COLUMN_NAME_ARABIC + " TEXT, " +
COLUMN_NAME_RUSSIAN + " TEXT, " +
COLUMN_NAME_SPANISH + " TEXT, " +
COLUMN_NAME_ITALIAN + " TEXT)";
I feel like a idiot because i forgot to type the database name at the constructor method like that:
Old
super(context, null, null, 1);
Now
super(context, "database", null, 1);
Thanks for your help!

Cursor index out of bounds exception that is passing null check

I checked a bunch of questions here and I cannot find correct answer. I have problem with retrieving data from my database. I get android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0 exception. My code for creating database:
String KREIRAJ_TABELU = "CREATE TABLE " + IME_TABELE + "("
+ ID + " INTEGER PRIMARY KEY," + PITANJE + " TEXT,"
+ PRVI_NETACAN + " TEXT," + DRUGI_NETACAN + " TEXT," + TRECI_NETACAN + " TEXT," + TACAN_ODGOVOR + " TEXT" + ")";
db.execSQL(KREIRAJ_TABELU);
String dodajPitanjaIOdgovore = "INSERT INTO pitanja (ID,PITANJE,PRVI_NETACAN,DRUGI_NETACAN,TRECI_NETACAN,TACAN_ODGOVOR)\n" +
"VALUES (0,\"Ovo je prvo pitanje:\",\"Netacan odgovor\",\"Netacan odgovor\",\"Netacan odgovor\",\"Tacan odgovor\");\n" +
"\n" + ...
db.execSQL(dodajPitanjaIOdgovore);
And for retriving data I use this piece of code:
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(IME_TABELE, new String[]{ID,
PITANJE, PRVI_NETACAN, DRUGI_NETACAN, TRECI_NETACAN, TACAN_ODGOVOR}, ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if(cursor.getCount() > 0)
{
cursor.moveToFirst();
}
podaciOPitanjima podaci = new podaciOPitanjima(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
return podaci;
Edit: I also tried this:
if (cursor.moveToFirst()) {
podaciOPitanjima podaci = new podaciOPitanjima(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
}
else{
podaciOPitanjima podaci;
}
podaciOPitanjima podaci = new podaciOPitanjima(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
return podaci;
Change
if (cursor.getCount() > 0) {
cursor.moveToFirst();
}
//do operations here
To
if (cursor.moveToFirst()) {
//do operations here
}
Explanation - the problem is this line:
podaci = new poda...ima(Integer.parseInt(cursor.getString(0)), ...);
When you use cursor.getString the cursor is not actually at a row (because there is no row), so you cannot get a cell/column which is what this command is asking for.
The full solution:
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(IME_TABELE, new String[]{ID, PITANJE, PRVI_NETACAN, DRUGI_NETACAN, TRECI_NETACAN, TACAN_ODGOVOR}, ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
podaciOPitanjima podaci = null;
if (cursor.moveToFirst()) {
//Note: using getColumnIndex avoids errors if the columns are ever returned in a changed order
podaci = new podaciOPitanjima(
cursor.getInteger( cursor.getColumnIndex(ID) ),
cursor.getString( cursor.getColumnIndex(PITANJE) ),
cursor.getString( cursor.getColumnIndex(PRVI_NETACAN) ),
cursor.getString( cursor.getColumnIndex(DRUGI_NETACAN) ),
cursor.getString( cursor.getColumnIndex(TRECI_NETACAN) ),
cursor.getString( cursor.getColumnIndex(TACAN_ODGOVOR) ));
}
return podaci;
Now remember wherever you are calling this method, that you might get null back and that you need to check for that.

Using SQLite in Android to get RowID

I am creating an app to record assignments for different classes. Each class has it's own unique ID so the assignments listed for each class don't overlap into other classes. Here is a method I made to find the rowid for a certain class.
public int getIdFromClassName(String className){
String query = "SELECT rowid FROM " + CLASSES_TABLE_NAME + " WHERE " + CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
return res.getColumnIndex("id");
}
However, this always returns a value of -1.
Any thoughts on what to change to return the proper rowid value?
EDIT:
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table " + CLASSES_TABLE_NAME + " " +
"(id integer primary key, " + CLASSES_COLUMN_NAME + " text)"
);
db.execSQL(
"create table " + ASSIGNMENTS_TABLE_NAME + " " +
"(id integer primary key, " + ASSIGNMENTS_COLUMN_NAME + " text, " + ASSIGNMENTS_COLUMN_TOTAL_POINTS
+ " INTEGER, " + ASSIGNMENTS_COLUMN_CLASS_ID + " INTEGER)");
}
Try this query below to create a new column name rowID:
Cursor cursor= db.rawQuery("SELECT *,"+CLASSES_TABLE_NAME +".rowid AS rowID"+" FROM "+CLASSES_TABLE_NAME , null);
And after this query you can fetch the real rowid from the rowID column :
while (cursor.moveToNext()) {
long chatRow=cursor.getLong(
cursor.getColumnIndexOrThrow("rowID"));
}
The column returned by your query is called rowid, so you will not find a column called id.
Ensure that you use the same column name in the query and in the call to getColumnIndex.
And the index of this column is always zero; you also need to read the actual value from the column:
int colIndex = res.getColumnIndexOrThrow("rowid"); // = 0
if (res.moveToFirst()) {
return res.getInt(colIndex);
} else {
// not found
}
However, Android has an helper function that makes it much easier to read a single value:
public int getIdFromClassName(String className){
String query = "SELECT rowid" +
" FROM " + CLASSES_TABLE_NAME +
" WHERE " + CLASSES_COLUMN_NAME + " = ?;";
SQLiteDatabase db = this.getReadableDatabase();
return DatabaseUtils.longForQuery(db, query, new String[]{ className });
}
res.getColumnIndex("id") is going to get you the column index of the column with the name "id". and since you are getting -1, it cant find it.. are you sure your id column is not "_id"?
To get this to work you should do something like this..
res.getLong(res.getColumnIndex("_id"));
Cursor.getColumnIndex()
Cursor.getLong()
(I would recommend you use getLong() rather than getInt() because SQLite database ID's can get larger than int's).
You can try this:
public int getIdFromClassName(String className){
String query = "SELECT id FROM " + CLASSES_TABLE_NAME + " WHERE " + CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
int id=-1;
If(res!=null&&res.moveToFirst())
id=res.getInt(res.getColumnIndex("id"));
return id;
}
public int getIdFromClassName(String className) {
String query = "SELECT rowid FROM " + CLASSES_TABLE_NAME + " WHERE "
+ CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
if (res != null) {
if (res.moveToFirst()) {
do {
return Integer.parseInt(res.getString(res.getColumnIndex("id"))); // if your column name is rowid then replace id with rowid
} while (res.moveToNext());
}
} else {
Toast.makeText(context, "cursor is null", Toast.LENGTH_LONG).show();
}
}
Check your Cursor if its null check your Log that your table is created successfully and if its not null make sure your table has column id in it.

Categories