App crashed with cursor getInt - android

I want to get number of rows inside a table using a SELECT COUNT(*) as nb query. Then when I want to get the result by using cursor.getInt(0) then the app crashed ! So I replaced my code with this :
public int getParcelleCount() {
String countQuery = "SELECT * FROM " + T_PARCELLE;
Cursor cursor = bd.rawQuery(countQuery, null);
int nb = 0;
if (cursor != null) {
nb = cursor.getCount();
}
cursor.close();
return nb;
}
And it works ! So why is the first option wrong ?

Your previous code did not work because you were trying to get values without moving to first. You have check for not null that was correct. But it was throwing Cursor Index Out Of Bounds Exception(You can search on internet). So you have to move cursor to first and then try to get values.
Try below code.
String countQuery = "SELECT COUNT(*) AS NB FROM " + T_PARCELLE;
Cursor cursor = bd.rawQuery(countQuery, null);
int nb = 0;
if (cursor.moveToFirst()) {
do
{
nb = cursor.getInt(0);
}while(cursor.moveToNext());
}
cursor.close();
return nb;

Related

Displaying data on Android after retrieving data form Android Sq lite

I am retrieving data according to dates but when running my app its shows nothing.
Here's my code :
SQL QUERY :
private Cursor getAllCurrentData()
{
String[] selectArg = new String[]{};
return db.query(Db_Contract.Db_Fieds.TABLE_NAME,
null ,
Db_Contract.Db_Fieds.DATE+ "= 2018-11-10",
selectArg,
null,
null,
Db_Contract.Db_Fieds.TIMESTAMP);
}
Displaying Data :
private void totalMoney()
{
Cursor cursor = getAllCurrentData();
double sum = 0.000d;
double getMoney;
while (cursor.moveToNext()) {
getMoney = cursor.getDouble(cursor.getColumnIndex(Db_Contract.Db_Fieds.MONEY));
sum += getMoney;
}
total.setText("Total money spent: " +sum);
}
I am new to Android Programming. Where I am doing wrong ?. Please correct me
First make sure you are connected to database and cursor returned by db.query() is not empty/null. Then Iterate over cursor like
private void totalMoney()
{
openDatabase();
Cursor cursor = getAllCurrentData();
cursor.moveToFirst();
double getMoney = 0;
while (!cursor.isAfterLast()) {
getMoney = cursor.getDouble(cursor.getColumnIndex(Db_Contract.Db_Fieds.MONEY));
sum += getMoney;
cursor.moveToNext();
}
total.setText("Total money spent: " + sum );
closeDatabase();
}

App crashes if SQLite cursor has no results

I have an app that uses a cursor to run an SQlite query.
public Cursor totaltrips(){
Cursor cursor = database.rawQuery("SELECT * AS TTotal FROM " + DatabaseHelper.TABLE_NAME, null);
return cursor;
}
The results are stored to an Arraylist with a maximum of 5 values. If there are no records in the database the app crashes. If I have one or more database entries it works fine. Does anyone know how I can stop it from crashing when there are no database entries?
// get column value
if (Distance.moveToNext())
result = String.valueOf(Distance.getDouble(Distance.getColumnIndex("myTotal")));
tnmView.setText(result);
List<String> distancearray = new ArrayList<String>();
Cursor cursor = dbManager.totaldistance();
do{
distancearray.add(cursor.getString(1));
}while ((cursor.moveToNext()));
ttrips = cursor.getCount();
Log.i("Graph", "TTRIPS = " + ttrips);
// Be sure here to have at least the 5 desired elements into the list
while(distancearray.size() < 5){
distancearray.add("0");
}
The app crashes with the error
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
On the line
do{
distancearray.add(cursor.getString(1));
}while ((cursor.moveToNext()));
Check if cursor actually has results, try something like this for example:
int numResults = cursor.getCount();
if (numResults > 0) {
do {
distancearray.add(cursor.getString(1));
} while ((cursor.moveToNext()));
}
Replace
do{
distancearray.add(cursor.getString(1));
}while ((cursor.moveToNext()));
with
if (cursor != null) {
while (cursor.moveToNext()) {
distancearray.add(cursor.getString(1));
}
cursor.close();
}
Check if cursor is null and has more than one value.Close cursor after uses.
if(cursor!=null&&cursor.getCount()>0){
cursor.moveToFirst();
while(cursor.hasNext()){
//do stuff here
}
cursor.close();
}

Cursor not working in Android sqlite

My android app has 2 tables Projects and Tasks.
Each Project can have multiple Tasks.
Like below
Now I want to sum up all proportion values of the single task table
I did it.. but the issue is its adding proportion values from all task tables !
The cursor I coded is as follows
public int sumproportion(long projectId){
int value = 0;
int p = 0;
Cursor cu = mDatabase.rawQuery("SELECT * FROM " + DBHelper.TABLE_TASKS, null);
ArrayList temp = new ArrayList();
if (cur != null) {
if (cur.moveToFirst()) {
do {
temp.add(cur.getString(cur.getColumnIndex("proportion"))); // "Title" is the field name(column) of the Table
} while (cur.moveToNext());
}
}
Object ia[] = temp.toArray();
for(int i=0; i<ia.length; i++)
{
p = Integer.parseInt((String) ia[i]);
value = value + p;
}
System.out.println("Value is: " + value);
return value;
}
When I added cursor as below
Cursor cur = mDatabase.query(DBHelper.TABLE_TASKS, mAllColumns,
DBHelper.COLUMN_TASK_PROJECT_ID + " ="+String.valueOf(projectId),
null, null, null, null);
It doesn't add anything. Can any one help fix it please?
First of all, you can just use query like this SELECT SUM(proportion) from TABLE_TASK. proportion should have numeric type.
Secondly, verify that your Cursor return any rows. Probably you pass wrong projectId if there no rows.

Single value from cursor to int

I can't seem to figure out how I get the result from my select query (which should be one number) into my int min. Found different solution using Google but none worked.
I need the min value in order to check if the score that the current player has is higher than the lowest score in order to get in the highscores.
public int getMin(){
System.out.println("in getmin");
String selectQuery = "SELECT MIN(score) FROM tblscore;";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
int min = "something here to put the result in the int"
cursor.close();
db.close();
return min;
}
You could read the value through a cursor, but for single-valued queries like this, there is helper function in the DatabaseUtils class which makes things simpler:
public int getMin(){
String selectQuery = "SELECT MIN(score) FROM tblscore";
SQLiteDatabase db = this.getReadableDatabase();
try {
return (int)DatabaseUtils.longForQuery(db, selectQuery, null);
} finally {
db.close();
}
}
First you need to point the cursor to the first line:
cursor.moveToFirst();
Then you can use Cursor.getInt to get the value:
int min = cursor.getInt(0);

Skip deleted/empty rows sqlite

I am populating AChartEngine from sqlite database and I need all of the data to be displayed. The problem I'm having is when I delete a record the graph series stops populating at the deleted record. I need to find a way to skip over deleted/empty records and continue populating my graph. I need it to do it the same way listview skips over deleted records and keeps on displaying all rows. I am very new to a lot of this and am having a very difficult time with this. I have tried to write if statements in order to skip deleted/empty rows but nothing seems to work. Thank you for helping!
in my graphing activity:
for (int i = 1; !c.isAfterLast(); i++) {
String value1 = db.getValue1(i);
String value2 = db.getValue2(i);
c.moveToNext();
double x7 = Double.parseDouble(value1);
double y7 = Double.parseDouble(value2);
myseries.add(x7, y7);
}
I am getting error: CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
If I surround with try and catch it will populate rows up until the deleted record.
"EDIT"
in my sqlite database:
public String getValue1(long l) {
String[] columns = new String[]{ EMP_DEPT };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value1 = c.getString(0);
return value1;
}
return null;
}
public String getValue2(long l) {
String[] columns = new String[]{ EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value2 = c.getString(0);
return value2;
}
return null;
}
Your issue is that your safety net for commands on rows that don't exist is to use if (c != null){ and then perform your commands inside that block, but a Cursor request from a query will never come up null, it will instead result in a cursor object with no rows.
A more appropriate solution to use this as your safety net instead if (c.moveToFirst()){ Because the method itself returns a boolean for if the method actually carried itself out in the first place - true if it moved and false if not (which occurs when there's no rows to move into). another check, if you wish, would be to see how many rows the cursor has with c.getCount().
Additionally, you should combine your methods so that you don't make redundant queries to the database:
public String[] getValues(long l) {
String[] results = new String[2];
String[] columns = new String[]{ EMP_DEPT, EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c.moveToFirst()) {
results[0] = c.getString(0);
results[1] = c.getString(1);
} else {
Log.d("GET_VALUES", "No results formed from this query!");
}
return results;
}
You should use a single query to get all values at once:
SELECT Date1 FROM MyTable WHERE id BETWEEN 1 AND 12345
or:
db.query(EMP_TABLE, columns, EMP_ID + " BETWEEN 1 AND " + ..., ...);
Then missing values will just not show up when you iterate over the cursor.

Categories

Resources