Android SQLLiteDataBase cursor returning 0 rows - java

For the life of me, I can't get the cursor to return any data. I've verified that their is data in the database and my insertions are working. The official error is:
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
Top level declarations:
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
this.db = this.DBHelper.getWritableDatabase();
}
My function:
public String getRandomEntry()
{
int rand;
Random random = new Random();
int numEntries = (int)this.getCount();
if(numEntries == 0)
return "ERROR: Database is empty.";
rand = random.nextInt(numEntries);
Cursor cursor = DBHelper.getWritableDatabase().rawQuery(
"SELECT * FROM " + DATABASE_TABLE
+ " WHERE " + COLUMN_A + " = " + 0, null);
Log.i("numEntries", Integer.toString(numEntries));
Log.i("rand", Integer.toString(rand));
Log.i("cursor", Integer.toString(cursor.getCount()));
cursor.moveToFirst();
return cursor.getString(0);
}
I've also tried grabbing the cursor as such:
Cursor cursor = db.rawQuery(
"SELECT * FROM " + DATABASE_TABLE
+ " WHERE " + COLUMN_A + " = " + 0, null);
Please give me your thoughts! Thank you!!

Nothing seems random here at all. It appears that you are looking for column_a with a value of 0 every time.
I would assume that column_a has nothing with a value of 0.

First of all try to query this way:
String args[] = new String[]{"0"};
Cursor cursor = db.rawQuery(
"SELECT * FROM " + DATABASE_TABLE + " WHERE " + COLUMN_A + " = ?", args);
If this not helps check your db with external tool if you query return rows there.

Related

How to get row cursor with primary key android

I have a table with the following
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL( "CREATE TABLE " + TABLE_NAME + " (" + "ID" + " INTEGER PRIMARY KEY," +
COLUMN_TOPIC + " TEXT," + COLUMN_LOCATION + " TEXT)");
}
I am trying to get all the data at a given rowid
public void getRowCursor(int position){
SQLiteDatabase database = getWritableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " +
"ID" + "=" + String.valueOf(position), null);
cursor.moveToFirst();
cursor.close
//or
Cursor cursor = database.query(TABLE_NAME, null, "ID", new String[]{
String.valueOf(position)}, null, null, null, null );
cursor.moveToFirst();
cursor.close
database.close
}
I get an error
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
I did populate the table. How do I return a cursor based on the position of entry.
How do I return a cursor based on the position of entry
First, your method getRowCursor() should return a Cursor.
Also, you should not close the returned cursor because I assume that you want to use its results somehow.
Your code with the method rawQuery() should work like this:
public Cursor getRowCursor(int position) {
SQLiteDatabase database = getWritableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE ID = " + String.valueOf(position);
Cursor cursor = database.rawQuery(sql, null);
// cursor.moveToFirst();
return cursor;
}
But, the safe and recommended way to pass parameters to a query is with ? placeholders instead of concatenating them inside the sql statement and passing them as array items in the 2nd argument of rawQuery():
public Cursor getRowCursor(int position) {
SQLiteDatabase database = getWritableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE ID = ?";
Cursor cursor = database.rawQuery(sql, new String[] {String.valueOf(position)});
// cursor.moveToFirst();
return cursor;
}
Note that moveToFirst() moves the cursor's index at the 1st row of the cursor (if it exists).
I commented out this call, because you should use it after you call getRowCursor() like this:
Cursor cursor = getRowCursor(10); // or any other ID
if (cursor.moveToFirst()) { // the cursor contains at least 1 row
....
} else { // the cursor is empty
....
}
and when you are done with the cursor:
cursor.close();

Android studio SQL - How to return data in a string array

I have an SQL method here. I would like to return the data in a String[] array.
How do I do that exactly?
Thank you!
public String[] getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
String[] LikeSong;
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);
}
cursor.close();
db.close();
return LikeSong;
}
You must define the array's length and this can be done only after the Cursor fetches all the rows. Then set its length to the nimber of rows of the Cursor.
Then inside the while loop set the items of the array:
public String[] getLikedSongs() {
String[] LikeSong = null;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
if (cursor.getCount() > 0) {
LikeSong = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
LikeSong[i] = cursor.getString(0);
i++;
}
}
cursor.close();
db.close();
return LikeSong;
}

Max from a column

Activity
Cursor mSent = myDBHlpr.getMostMessagesSent(getActivity());
while (mSent.moveToNext()) {
mMostMessagesSent.setText(mSent.getString(mSent.getColumnIndex("Name")));
}
mSent.close();
Helper
public Cursor getMostMessagesSent(FragmentActivity usageSettings) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_USER_DATA + " WHERE " + KEY_MESSAGES_SENT + "=(SELECT MAX(" + KEY_MESSAGES_SENT + ")" + " FROM " + TABLE_USER_DATA + ")", null);
return cursor;
}
The data is not showing... im sure i have made some silly error but dont know where... can someone please help me out
Query
SELECT * FROM UserData WHERE MessagesSent=(SELECT MAX(MessagesSent) FROM UserData);

Cannot resolve symbol moveToNext()

What's going on here guys? I've tried cleaning my gradle, I know for a fact that my database contains these columns. It's driving me nuts y'all.
public Cursor select_week(int week){
SQLiteDatabase db1 = this.getWritableDatabase();
Cursor res = db1.rawQuery("select " + COL_3 + "," + COL_4 + " from Regular_Season where Week =" + week + ";", null);
return res;
}
Cursor res = myDb.select_week(week);
while (res.moveToNext()) {
Button p1_button = (Button)findViewById(R.id.radio0);
p1_button.setText(res.getString(0));
Button p2_button = (Button)findViewById(R.id.radio1);
p1_button.setText(res.getString(1));
Button p3_button = (Button)findViewById(R.id.radio1);
p1_button.setText(res.getString(2));
Button p4_button = (Button)findViewById(R.id.radio1);
p1_button.setText(res.getString(3));
}

Specific query error - SQLite Android

my problem is with very specific query. My SQLite datbase is only 1 table with 11 entries. It creates just fine, but upon execution of this piece of code it crashes. When I change the query to simply:
SELECT * FROM Items
Then it works fine, but I need more narrow results, therefore I modify with the "WHERE" clause. But then it crashes and the application stops. If I comment out the Cursor... it runs fine.
public int findPictureNumber(String itemtitle) {
String query = "SELECT nr_of_pics FROM Items WHERE ItemTitle = \"" + itemtitle + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
...
}
Where is the error? I can't seem to find it even after narrowing it down to those lines of code.
EDIT:
This is a method for adding an item to a database.
public void newItemFuro () {
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
String title = "Furo";
String author = "Fernando Brizio";//í
String category = "Decoracao";//çã
int date = 2012;
String type = "Taca";//ç
String country = "Portugal";
String colour = "Castanho/Cortica";//ç
String material = "Castanho/Cortica";//ç
boolean isFavourite = false;
String imgres = "furoo";
int nr_of_pics = 3;
Item item = new Item(title, author, category, date, type, country, colour, material, isFavourite, imgres, nr_of_pics);
dbHandler.addItem(item);
}
//helper for types
public static final String VARCHAR_TYPE = " VARCHAR(50)";
public static final String BOOL_TYPE = " BOOLEAN";
public static final String INT_TYPE = " INTEGER";
Here it creates the table:
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS +
"("
+ COLUMN_ENTRY_ID + INT_TYPE +" PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_TITLE + VARCHAR_TYPE + ","
+ COLUMN_AUTHOR + VARCHAR_TYPE + ","
+ COLUMN_CATEGORY + VARCHAR_TYPE + ","
+ COLUMN_DATE + INT_TYPE + ","
+ COLUMN_TYPE + VARCHAR_TYPE + ","
+ COLUMN_COUNTRY + VARCHAR_TYPE + ","
+ COLUMN_COLOUR + VARCHAR_TYPE + ","
+ COLUMN_MATERIAL + VARCHAR_TYPE + ","
+ COLUMN_FAVOURITE + BOOL_TYPE + ","
+ COLUMN_IMGRES + VARCHAR_TYPE + ","
+ COLUMN_NUMBER_OF_PICS + INT_TYPE +
")";
db.execSQL(CREATE_ITEMS_TABLE);
}
Adding item:
public void addItem(Item item) {
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE, item.getItemTitle());
values.put(COLUMN_AUTHOR, item.getAuthor());
values.put(COLUMN_CATEGORY, item.getCategory());
values.put(COLUMN_DATE, item.getDate());
values.put(COLUMN_TYPE, item.getType());
values.put(COLUMN_COUNTRY, item.getCountry());
values.put(COLUMN_COLOUR, item.getColour());
values.put(COLUMN_MATERIAL, item.getMaterial());
values.put(COLUMN_FAVOURITE, item.getFavourite());
values.put(COLUMN_IMGRES, item.getImgres());
values.put(COLUMN_NUMBER_OF_PICS, item.getNumberOfPics());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_ITEMS, null, values);
db.close();
}
Here full function for searching nr_of_pics:
public int findPictureNumber(String itemtitle) {
String query = "SELECT nr_of_pics FROM Items WHERE ItemTitle = '" + itemtitle + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
int PicsNumber=0;
if (cursor.moveToFirst()) {
cursor.moveToFirst();
PicsNumber=Integer.parseInt(cursor.getString(0));
cursor.close();
return PicsNumber;
} else {
//wtf?
}
db.close();
return 0;
}
And the errors say as follows:
(1) table Items has no column named imgres
Error inserting colour=Castanho/Cortiça author=Fernando Brízio
imgres=furo category=Decoração title=Furo type=Taça date=2012
nr_of_pics=3 material=Castanho/Cortiça is_favourite=false
country=Portugal
android.database.sqlite.SQLiteException: table Items has no column named imgres (code 1): , while
compiling: INSERT INTO
Items(colour,author,imgres,category,title,type,date,nr_of_pics,material,is_favourite,country)
VALUES (?,?,?,?,?,?,?,?,?,?,?)
You do not give any exception but I think you have error in your SQL. You need to use ' instead of ".
Change your query as below.
String query = "SELECT nr_of_pics FROM Items WHERE ItemTitle = '" + itemtitle + "'";
It is clear that you don't have any column that named "imgres"!
You should modify your query
"INSERT INTO Items(colour,author,imgres,category,title,type,date,nr_of_pics,material,is_favourite,country)
VALUES (?,?,?,?,?,?,?,?,?,?,?)"

Categories

Resources