Can anybody tell me what I am doing wrong? The table that I am querying is empty, so I think that the cursor should be empty. But instead, it returns a cursor with 1 row and 1 column. Even so, I don't see why this results in an error. All I am trying to do is return the single value (if it exists) from my query.
Can somebody help me understand this? Thank you!
Cursor cursor = db.rawQuery("SELECT max(GAME_COLUMN) FROM GAMES_TABLE", null);
if (cursor.moveToNext()) {
System.err.println("why am I here?");
nextGame = cursor.getInt(cursor.getColumnIndex("GAME_COLUMN"));
}
Bad request for field slot 0,-1. numRows = 1, numColumns = 1
This is because there is no column named GAME_COLUMN in the result. Make your query
SELECT max(GAME_COLUMN) AS GC FROM GAMES_TABLE
and then query for GC :-
Cursor cursor = db.rawQuery("SELECT max(GAME_COLUMN) AS GC FROM GAMES_TABLE", null);
if (cursor.moveToNext()) {
System.err.println("why am I here?");
nextGame = cursor.getInt(cursor.getColumnIndex("GC"));
}
Related
I don't know what's wrong with my code I follow the rule but I get wrong result. I want to search db and find all rows data but I only get last row from sqlite. my code to search database is bellow:
public ArrayList<ArrayList<ContractSaveDataFromDB>> ActiveContractData(String phone, String numberId)
{
ArrayList<ContractSaveDataFromDB> UserData = new ArrayList<ContractSaveDataFromDB>();
ArrayList<ArrayList<ContractSaveDataFromDB>> SendUserData =
new ArrayList<ArrayList<ContractSaveDataFromDB>>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
res2.moveToFirst();
do{
UserData.clear();
int index;
ContractSaveDataFromDB contractSaveDataFromDB=new ContractSaveDataFromDB();
index = res2.getColumnIndex("buyAmount");
String buyAmount = res2.getString(index);
contractSaveDataFromDB.setBuyAmount(buyAmount);
UserData.add(contractSaveDataFromDB);
SendUserData.add(UserData);
} while(res2.moveToNext());
res2.close();
db.close();
return SendUserData;
I don't know what's wrong. I appreciate if you help me to solve my problem.
you already added where clause so maybe it is filtering your results try to remove it by change this
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
to this
Cursor res2=db.query("usersAccount",null,null,null,null,null,orderBy);
I believe that your issues is that you are trying to use an ArrayList of ArrayList of ContractSaveDataFromDB objects.
I believe that an ArrayList of ContractSaveDataFromDB objects would suffice.
It would also help you if you learnt to do a bit of basic debugging, as an issue could be that you are not extracting multiple rows.
The following is an alternative method that :-
uses the ArrayList of ContractSaveDataFromDB objects,
introduces some debugging by the way of writing some potentially useful information to the log
and is more sound, as it will not crash if no rows are extracted
i.e. if you use moveToFirst and don't check the result (false means the move could not be accomplished) then you would get an error because you are trying to read row -1 (before the first row) as no rows exists in the cursor.
:-
public ArrayList<ContractSaveDataFromDB> ActiveContractData(String phone, String numberId) {
ArrayList<ContractSaveDataFromDB> SendUserData = new ArrayList<ContractSaveDataFromDB>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2 = db.query("usersAccount", null, whereClause, whereArgs, null, null, orderBy);
Log.d("RES2 COUNT", "Number of rows in Res2 Cursor is " + String.valueOf(res2.getCount()));
while (res2.moveToNext()) {
ContractSaveDataFromDB current_user_data = new ContractSaveDataFromDB();
current_user_data.setBuyAmount(res2.getString(res2.getColumnIndex("buyAmount")));
Log.d("NEWROW", "Adding data from row " + String.valueOf(res2.getPosition()));
SendUserData.add(current_user_data);
}
res2.close();
db.close();
Log.d("EXTRACTED", "The number of rows from which data was extracted was " + String.valueOf(SendUserData.size()));
return SendUserData;
}
If after running you check the log you should see :-
A line detailing how many rows were extracted from the table
A line for each row (if any were extracted) saying Adding data from row ? (where ? will be the row 0 being the first)
A line saying The number of rows from which data was extracted was ? (? will be the number of elements in the array to be returned)
I'm trying to get the number of entries my DB holds - in the most simple way possible.
I'm trying to use the rawQuery "SELECT Count(*) FROM Students" and then from the cursor to do an getInt method to get the number and use it later on.
this is my method
public int getNumberOfEntries() {
SQLiteDatabase db = helper.getWritableDatabase();
String query = ShaqedDB.NUMBER_OF_ENTRIES;
Cursor d = db.rawQuery(query, null);
d.moveToFirst();
while (!d.isAfterLast()) {
int numberReturned = d.getInt(0);
d.moveToNext();
return numberReturned;
}
return 0;
}
I've looked everywhere - and I cannot find a solution to why am I keep getting the cursor error that the cursor cannot read row 0, col 1... even though I think I point it to col 0
if you don't need to write, you should use getReadableDatabase(); instead of getWritableDatabase();. In
d.getInt(0);
0 is the index of column you want to retrieve the value. Don't hardcode the value. Ask the cursor to retrieve the column index
d.getInt(d.getColumnIndexOrThrow("COLUMN_NAME"));
about your query, you want to now the number of results returned by your query. You can retrieve this value asking the cursor's count:
public int getNumberOfEntries() {
SQLiteDatabase db = helper.getReadableDatabase();
String query = ShaqedDB.NUMBER_OF_ENTRIES;
Cursor d = db.rawQuery(query, null);
return d.getCount();
}
I'm trying to get all the IDs in the table by cursor. The table has 4 rows, and when I try to access the cursor by any index aside from 0 , the App crashes.
Guys, the problem still exists and even c.getInt(0) doesn't work...I really dont know where my mistake is???
the logcat also suggests that the error might be comes from
Toast.makeText(getApplicationContext(), "id="+dbd.getIDs()[0], Toast.LENGTH_SHORT).show();
I mean c.getint(0) returns the id, c.getint(2) returns error. Here is the code:
public int []getIDs() {
SQLiteDatabase db = this.getReadableDatabase();
SQLiteCursor c = (SQLiteCursor) db.rawQuery("SELECT " + BaseColumns._ID + " FROM Demo ", null);
int []r = new int[c.getCount()];
c.moveToFirst();
do{
r[c.getPosition()] = c.getInt(0);
}while(c.moveToNext());
c.close();
db.close();
return r;
}
Your select is a projection onto the ID column (select columns from ..., columns are the column ids you are interested in, and you specified just one). Thus the answer just has one column, namely the ID. Any access to columns with index > 0 will not work.
To access the other columns name them in the projection in your query.
c.getInt(0) return only value of first colunn from current row.
try this code:
do{
int r = c.getInt(0);
Log.d("Your class name","id value = "+r);
}while(c.moveToNext());
You can imagine Cursor as a table. There are rows and columns. And a cursor is pointing on a particular row in this table. Thus, to get all id's you should move across all rows.
c.getInt(ind) In this statement index is pointing on the column with index ind. Thus, in your code you try to get the second and third column and according to your code there is no these column.
To get a proper code you should create a loop and traverse all rows of your cursor. Also you should use c.getInt(0) to get the columns values.
Assuming you are selecting the appropriate Data, your problem is that you're not preparing the Cursor to be iterated.
Before iterating, call:
c.moveToFirst();
Like this:
int []r = new int [c.getCount()];
c.moveToFirst();
do{
r[c.getPosition()] = c.getInt(0);
}while(c.moveToNext());
c.close();
db.close();
return r;
This is well indicated in LogCat. I can't remember how it's put, but the message is very suggestive. Please post as much of the Log as possible, especially the good bits.
Also, I modified 'r' to be an array. As it was you were only returning the value of the last row.
I need help with summing all the values in one of the columns(KEY_CONTENT6) in my database(MYDATABASE_TABLE). I keep having force close issues, somebody tell me what I'm doing wrong!
Heres my code:
public Cursor sumAll(){
float columntotal = 0;
Cursor cursor1 = sqLiteDatabase.rawQuery(
"SELECT SUM("+Float.valueOf(KEY_CONTENT6)+") FROM MYDATABASE_TABLE", null);
if(cursor1.moveToFirst()) {
columntotal = cursor1.getFloat(0);
}
cursor1.close();
String sumtotal = Float.toString((float)columntotal);
return cursor1;
}
The column KEY_CONTENT6 is a string for various reasons which is why I used Float.valueOf() but I'm guessing that's where my problem is.
You're closing the cursor then returning it. You probably want to return the column total or sum total, not the cursor
I query the table by using this function below
public Cursor getTableInfo() throws SQLException
{
return db.query(TableName, null,
null,
null,
null,
null,
null);
}
I got the error "View Root.handleMessage(Message)line:1704". I could insert the data but can't query the data. I called this function below
Cursor c = db.getTableInfo();
int cRow = c.getCount();
if (cRow == 0)
{
Toast.makeText(NewContact.this,
"No Record",
Toast.LENGTH_LONG).show();
}
In SQLite, is there any case-sensitive in the name of database, table, column?
Please help me.
Your db request looks ok and it should return all records from your table.
So maybe there are just no records in the table?
Also it's unclear whether you have problem with db related stuff or with smth else, because the code provided looks ok.
I would rather evaluate the outcome of c.moveToFirst() instead of c.getCount(). The latter means the cursor iterates over the whole dataset which is a more costly operation.