Adding data from a SQLite column - java

I'm, trying to add a credit score from multiple records of an SQLite table.
Each record has a column called credit score, I want to add them all together but I'm having trouble.
Here is the code:
String[] projection2 = { BorrowMeTable.COLUMN_CREDIT_SCORE };
Cursor databaseCursor2 = getContentResolver().query(uri, projection2,
null, null, null);
int number = 0;
if (databaseCursor2 != null) {
databaseCursor2.moveToFirst();
while (databaseCursor2.moveToNext()) {
number = number + databaseCursor2.getInt(
databaseCursor2.getColumnIndexOrThrow(
BorrowMeTable.COLUMN_CREDIT_SCORE));
}
}
Log.d("SCORE", Integer.toString(number));
The problem is the while statement, when it is in place it doesn't pull any data. When I remove it, it pulls the correct data but only from one record.

Use the sum funstion in SQLite
Cursor cursor = sqliteDatabase2.rawQuery(
"SELECT SUM(COLUMN_CREDIT_SCORE) FROM BorrowMeTable", null);
You can URI match this in your ContentProvider as a different URI
Then simply get the scalar value:
if(cursor.moveToFirst()) {
return cursor.getInt(0);

Use do->while to start from first record
do{
number = number + databaseCursor2.getInt(
databaseCursor2.getColumnIndexOrThrow(
BorrowMeTable.COLUMN_CREDIT_SCORE));
}while (databaseCursor2.moveToNext());

Related

Android Studio - SQLite Cursor not returning any data

I am trying to return the names of distinct values in the 'category' column of an SQLite database. The cursor does not appear to be returning any results.
I'm building an Android app using a pre-existing database of bird species. The aim is to allow the user to explore the database through the app. The problem I'm having is in trying to return the distinct categories of bird species that exist in the database. The database appears to be opening successfully - no SQLite exception is being thrown, - but after using the query, the '.moveToNext' method does not appear to be returning any data.
public ArrayList<String> getCategory(String[] name){
String TABLE_BIRDS = "main";
String[] COLUMN = name;
ArrayList<String>categories = new ArrayList<>();
if (name[0]!=null)
{
Log.d(LOG_TAG, name[0]);
} else {
Log.d(LOG_TAG, "name[0] has not been passed");
}
x = db.query(true, TABLE_BIRDS, new String[] { COLUMN[0] } , null, null, COLUMN[0], null, null, null );
if (x.moveToNext()) {
Log.i(LOG_TAG, x.getString(x.getColumnIndex("category")));
}
else {
Log.i(LOG_TAG, "The cursor is not returning any data");
}
//Simple cursor loop
if (x.moveToNext()){
String category = new String();
category = x.getString(x.getColumnIndex(category));
categories.add(category);
Log.i("cursor loop", category);
}
return categories;
In the above code, the log messages are showing that: getCategory is receiving the expected string "category" before the query, but right after the query, the if/else loop is reporting that "The cursor is not returning any data".
What I expected is that the query would return six Strings, the cursor loop would add them to the ArrayList 'categories', and this ArrayList would be returned.
Please any help would be appreciated.
Here is a simpler version of your method:
public ArrayList<String> getCategory(String[] name) {
String TABLE_BIRDS = "main";
ArrayList<String> categories = new ArrayList<>();
if (name[0] != null) {
Log.d(LOG_TAG, name[0]);
} else {
Log.d(LOG_TAG, "name[0] has not been passed");
}
Cursor x = db.query(true, TABLE_BIRDS, new String[]{name[0]}, null, null, null, null, null, null);
while (x.moveToNext()) {
String category = x.getString(0);
categories.add(category);
Log.i("cursor loop", category);
}
if (x.getCount() == 0) {
Log.i(LOG_TAG, "The cursor is not returning any data");
}
x.close();
return categories;
}
I guess name[0] contains the string 'category' which is the column that you want to query.
Since you pass true as the 1st argument in the method query() this means that you will get distinct values, so no need for the group by argument.
You don't need the variable COLUMN since you have what you need in the variable name.Also you don't need getColumnIndex() since the cursor returns only 1 column.
Edit
Instead of:
Cursor x = db.query(true, TABLE_BIRDS, new String[]{name[0]}, null, null, null, null, null, null);
try rawQuery():
Cursor x = db.rawQuery("SELECT DISTINCT " + name[0] + " FROM " + TABLE_BIRDS, null);
Assuming the cursor is not null, you should
iterate over the results with a while/for loop.
e.g :while(x.moveToNext()) {
//your logic
}
It is always useful when debugging this kind of issues to install an SQLite DB browser then check the cursor's query against your DB to see if you have any data.

SQLite, return data as an array

I have an SQLite Database in my android application with the following structure:
public void onCreate(SQLiteDatabase db) {
String CREATE_LISTS_TABLE = "CREATE TABLE " + TABLE_LISTS +
"("+
_ID + " INTEGER PRIMARY KEY , " +
NOTE + " TEXT" +
")";
db.execSQL(CREATE_LISTS_TABLE);
}
And this works, in that I can insert data into it without a problem. However I need to store the notes inside an array. I currently have the following query:
public List<String> getAllNotes() {
List<String> notes = new ArrayList<>();
String GET_ALL_NOTES = "SELECT * FROM " + TABLE_LISTS;
SQLiteDatabase db = getReadableDatabase();
if(db!=null)
{
Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex("notes"))));
cursor.moveToNext();
}
cursor.close();
}
db.close();
return notes;
}
However, this gives the following error:
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I was wondering how to fix this, I have read the android developer stuff but I can't seem to get anything to work.
Thanks in advance
Check the value of "NOTE", and use it in:
notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex(NOTE))));
I think a best way to make the call should be something like this:
// Check the cursor
if(cursor != null) {
if (cursor.moveToFirst()) {
// Variables to be used
String note;
// Col position
int colNote = cursor.getColumnIndex(NOTE);
do {
// Get the information
note = cursor.getString(colNote);
// Add the note
notes.add(note);
} while (cursor.moveToNext());
}
// Close the cursor
cursor.close();
}
Because you are fetching only integer and string from database, instead of using ArrayList , you can try using HashMap. So you can get the value by just giving the key. Below simple code will work for ArrayList too with minor changes..
Try this
HashMap<Integer,String> notes = new HashMap<Integer,String>() ;
Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);
while (cursor.moveToNext())
{
int i = cursor.getInt(0);
String s = cursor.getString(1);
notes.put (i,s) ;
}
cursor.close();

Storing SQL query output in an Array

I'm looking for a way to store the results/output of an SQL Query into an Array. I have a for loop which runs a query and each time the query is ran I would like to store the results in an array/arraylist. I tried using a cursor but I cannot store multiple strings in a cursor.
Here is the for loop:
for (int i=1;i<code.length;i++) {
Cursor cursor = myDataBase.query("codes", new String[]{"description"}, ("code = '" + code[i] + "'"), null, null, null, null);
cursor.moveToFirst();
String temp = cursor.getString(i);
result.add(i, temp);
cursor.close();
This doesn't seem to work.
Any suggestions or examples that could help?
Thanks
Assuming that code is a list of ids and the table name is named codes, and that you would like to retrieve the list of descriptions for all the codesTry you should this (using StringUtils.join from Apache commons):
String codes = StringUtils.join(code,",");
Cursor cursor = myDataBase.rawQuery("select description from codes where code in (?)",new String[]{codes});
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
result.add(cursor.getString(1));
}
cursor.close();

Android - Fetching only rows with a value in a column in java

First of all, please bear with me, I have minimal experience with SQLite. I am writing an app in Java for the Android platform and I've run into an issue while attempted to query a SQLite database.
I have implemented a database and I am unsure of how to write a method which returns a cursor of only specific rows with a certain value in a certain column. Say there is a column titled "date", I would like to write a method which returns all the columns that do not have the value string "null" in the "date" column.
I know how to write a fetchAll() method and how to write a fetch() for specific rows given an ID, but I not multiple specific rows.
If anyone can help me it would be greatly appreciated.
These will return all the row where Date!=null
public Cursor fetch()
{
return db.query(DATABASE_TABLE,
null,
DATE + "!=''",
null,
null,
null,
null);
}
If you don't need all columns then use
public Cursor fetch()
{
return db.query(DATABASE_TABLE,new String[] {
DATE,
TIME
},
DATE + "!=''",
null,
null,
null,
null);
}
For fetching multiple row using curosor, Have a go with this, You could customize it for your need:
public List<String> getNotNullValues(String value) {
String[] resultCols = new String[] { "Give your result column name here" }; //u could specify multiple column name here
List<String> list = new ArrayList<String>();
int count = 0;
Cursor cr = getWord("DATE", "Your Table Name", "Value of the column",
resultCols,"!="); //Cr is the cursor for resulted query
if (null == cr) {
return null;
}
do {
list.add(cr.getString(0)); //Fill the list or whatever here while traversing with the cursor
} while (cr.moveToNext());
cr.close();
return list;
}
}
public Cursor getWord(String columnName, String tblName, String rowId,
String[] columns, String condition) {
String selection = columnName + condition ; //condtion for selecting a value : "= ?"
String[] selectionArgs = new String[] { rowId };
return query(selection, tblName, selectionArgs, columns);
}
here are the steps:
Form the query with condition, column name and required column name
Get the cursor to the resulting query
Move the cursor to the next record till cr.moveToNext() returns false
For further reference:
Complete Step by Step SQLite Example:
http://mobile.tutsplus.com/tutorials/android/android-sqlite/
Youtube Video Tutorial
http://www.youtube.com/watch?v=kMaBTolOuGo
Multiple Table Creation
http://androidforbeginners.blogspot.com/2010/01/creating-multiple-sqlite-database.html
PS: All the links are tested and working well!!
Happy Coding!!

How to get highest row number using query?

I have an sqlitedb, row _id auto increments. How do I form a query to get the highest number in row _id and put that into a variable? I know how to do it in sql but not using the query method.
As answered elsewhere on this site:
String query = "SELECT MAX(row_id) AS max_id FROM mytable";
Cursor cursor = db.rawQuery(query, null);
int id = 0;
if (cursor.moveToFirst())
{
id = cursor.getInt(0);
}
Cursor Days = db.query(true, DATABASE_TABLE, new String[]{"_id"},
"_id="+"(select max(_id) from" +DATABASE_TABLE+")" , null, null, null, null, null);
This should also work.
cursor.getLong(cursor.getColumnIndex("row_id"))
Did you try this? When you insert the data in database, autoincrement increases the id for primary key and I assume row_id must be your one of the keys.
you can get this by count and also by using MAX(column name) function in your query.
max function returns the maximum value
Cursor newCursor = newContentResolver.query
(
CONTENT_URI,
new String[]{"_id"},
null,
null,
null
);
if(newCursor.moveToLast())
{
int index = newCursor.getColumnIndex("_id");
String id = newCursor.getString(index);
Log.v("TAG", "Highest id : "+id);
}
This is one way of getting the highest row id. Since the generation is auto increment, we are assured that the last row is the highest in the database. moveToLast() moves the cursor to the last row.

Categories