Queue SUM of SQLite column - android - android

I have a listview populated from an SQLite database. I have several items that I successfully populate into the listview, however I'm having trouble with one last thing.
I'm trying to queue the sum total of the column KEY_CONTENT6 which is a string type, however it only contains numbers. I'd like to keep it as a string, so to add it up I'm using Double.valueOf(). The problem is this code force closes on queue and I cant figure out whats wrong:
public Cursor queueAll(){
String[] columns =
new String[]{KEY_ID, "sum("+ Double.valueOf(KEY_CONTENT6) +")",
KEY_CONTENT9, KEY_CONTENT10 };
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null , null, KEY_CONTENT10, null, KEY_CONTENT9+ " DESC");
return cursor;
}

simply use SUM, no need to use anything else..
String[] columns =
new String[]{KEY_ID, "sum(KEY_CONTENT6)",
KEY_CONTENT9, KEY_CONTENT10 };
It is valid for SQLite. Because, no matter what you set data type in SQLite, it stores values as string. So, type conversion is somewhat built-in in SQLite.

You can't use java in a SQL statement, either stick to strait sql or iterate over the cursor and use java to do your calculation.
You can find everything there is to know about sqlite here http://www.sqlite.org/docs.html

SQLite is basically typeless, so you might be able to use SUM on your column even though it is a string. However, if it's meant to be a numeric column, why not give it a number type??

Related

SQLite how to sum the values of column in `GridView`

I've had a look around and found a few similar cases but none where there is a need for specificity in the entries to sum. So here I am.
I have a method filterPayments that returns all entries in my PayTable based on a specific GroupID and is then displayed in my GridView. From there I want to sum the values of 2 of the 5 columns in PayTable, specifically my Interest and Due columns. I'm not sure how to do this in a query, let alone do it only for specific columns.
Question
How do I add the values of all entries in a specific column.
Is it possible to do this in a SQLite query? If so how do I use the returned value of filterPayments and perform the summation only on specific columns? If it isn't then how can I do this?
Below are my code snippets.
filterPayments
Cursor filterPayments(String Payment) {
SQLiteDatabase db = this.getWritableDatabase();
String[] columns = new String[]{"_id", colGroupID, colPayBal, colInterest, colDue, colDateDue, colPaid};
Cursor c = db.query(viewPmnts, columns, colGroupID + "=?", new String[]{Payment}, null, null, null);
return c;
}
GridView
public void Paygrid() {
dbHelper = new DatabaseHelper(this);
String Payment = String.valueOf(txt.getText());
Cursor a = dbHelper.filterPayments(Payment);
startManagingCursor(a);
String[] from = new String[]{DatabaseHelper.colPayBal, DatabaseHelper.colInterest, DatabaseHelper.colDue, DatabaseHelper.colDateDue, DatabaseHelper.colPaid};
int[] to = new int[]{R.id.Amount, R.id.Interest, R.id.Due, R.id.DateDue, R.id.Paid};
SimpleCursorAdapter saa = new SimpleCursorAdapter(this, R.layout.paygrid, a, from, to);
intgrid.setAdapter(saa);
}
I suggest pulling all the data from column and then sum them in Java or android. That would be the simplest way.
There are no core sqlite functions that does it.
https://www.sqlite.org/lang_corefunc.html
You can however create custom sqlite functions. Look below.
How to create custom functions in SQLite
I hope I get your question right. But if you have two columns with the column names interest and due you can get the sum of both columns with the SQL query
SELECT interest + due FROM PayTable;
This also applies for multiplication (and its inverse counterparts). Unfortunately it gets more tricky for non-integer exponentiation (like square root). As far as I know, you need the already mentioned own SQLite function. If you are lucky you can load a module wrapping the math.h from the C standard lib (search for extension-functions.c)
For other ways of summing in tables look at this question for PostgreSQL (It's the same for SQLite)

SELECT entry in SQLite, without a WHERE condition?

I followed advice in this question, but for my purposes I don't want a WHERE.
I don't know the value, so I cannot say rawQuery("... WHERE x = ?", y), I don't care what y is, it's just a cell I want, and it is known that there is a single row.
If it is not possible to lose the condition (perhaps because of causing an indeterminate number of results?) - then how can I say "from column z and row 0"?
I'm lacking either terminology, or outright understanding, because my searches are turning up nothing.
Edit: Eclipse doesn't complain at:
result = db.rawQuery("SELECT col FROM tbl", my_unused_string_array);
I'm not at a testing stage yet, and I can't enter this into the SQL db reader I was using to test SELECT col FROM tbl and ~ with WHERE.. will it work?
As per your edit, you don't need to specify WHERE clause, if you want to get all the records from a table:
result = db.rawQuery("SELECT col FROM tbl", new String[0]);
The SQL query "SELECT * FROM table" will return the entire table. "SELECT colX, colY FROM table" will return columns colX and colY for all the rows in the table. If your table contains just one row, "SELECT col FROM table" will return the value of col for that one row.
To use the SQLiteDatabase API to make that query, you would say:
result = db.rawQuery("SELECT col FROM tbl", null);
... because you are not supplying any query parameters.
Assuming that there is just one row seems dangerous to me. I would not use the "LIMIT" clause, because, while that will always get one row, it will hide the fact that there is more than one row, if that happens. Instead, I suggest that you assert that the cursor contains one row, like this:
if (1 != result.getCount()) {
throw Exception("something's busted");
}
Instead of Raw query use
Cursor cur = db.query(Table_name, null, null, null, null,
null, null);
and get the desired attributes from cursor.
where the query method has parameters in following manner:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Parameters:
table The table name to compile the query against.
columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself).
Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
Returns
A Cursor object, which is positioned before the first entry.

Selecting int values using a cursor query

I am new to Android, and having some basic problems. One of them is the use of queries.
I store a boolean value as either 1 or 0 in the table (INTEGER field). However, when I select either on 1 or 0 using the query below I get no results. What am I doing wrong?
Cursor cursor = _db.query(_objectName, _fields.keySet().toArray(new String[0]), "parentId=? AND published=?", new String[] {String.valueOf(menuItem), String.valueOf(1)}, null, null, "level");
There is nothing wrong with your query. The problem must be elsewhere. Check your code and table structure. Maybe you are not sending the right values for parentId and published columns or the data in the table is not in the format you expected.
Use raw query
"Select * from "+TABLE_NAME+" where published = '"+String.valueOf(1)+"'";
You can put your integer value insted of 1

Getting unique rows from column sqlite android cursor

Hi I cant get unique rows tried this from the documentation:
public Cursor getcepaUnico(){
return database.query(true, "vino", new String[] {"_id", "cepa"}, null, null, null, null, "cepa", null);}
but shows duplicated rows even if the DISTINCT boolean is changed.
Also tried this:
public Cursor getCepaUnico() {
return database.rawQuery("select DISTINCT cepa from vinos", null);}
And the app crash after calling the method.
Setting distinct to true should have returned distinct results. Is it possible that your code which loops through the cursor is incorrect? You might want to post that also for review.
Regarding your rawQuery, you are using a different table name which is probably what is causing the crash. It should be "select DISTINCT cepa from vino" (not vinos) to match your query statement.
Not sure if this will solve your problem, but sometimes I just pull the db from the emulator (in the DDMS view in Eclipse) and run the query directly using an sqlite editor when my raw queries don't work; if the query shows what you want in the editor then use the query in the rawQuery method.
Firefox has a good sqlite editor.

Android SQLite very slow lookup

I am trying to create a dictionary application on Android. I have a database of 80000 articles. When user enters a word in an EditText, I want to show suggestions in a ListView, To do that I use the following code:
public Cursor query(String entry){
String[] columns = new String[]{"_id", "word"};
String[] selectionArgs = new String[]{entry + "%"};
return mDB.query("word", columns, "word LIKE ?", selectionArgs, null, null, null);
}
and I use SimpleCursorAdapter for the ListView.
The problem is that suggestions appear very late. I think the reason is LIKE in the SQL. I do not know any other way to do that. Is there anything I can do to boost the performance of getting the suggestions?
You might find that adding an index on the word column helps a lot. See the documentation.
So you might try this, just after you create the table:
CREATE INDEX word_idx ON word (word);
(Note: I'm not sure if having the table and column both named word will cause syntax issues here. Try it and see!)
Aside from the obvious index you should look into using full text search with MATCH rather than like if this is a dictionary. Android should support FTS3.
Check out http://www.sqlite.org/fts3.html and some answers here on SO regarding fts3 on Android.
It seems that the words should start with the string.
Maybe this type of trick could help: SQLite FTS3 simulate LIKE somestring%
As a simple alternative, you can limit the suggestions in the arbitrary order with Limit as in this post: Using the LIMIT statement in a SQLite query
mDB.query("word", columns, "word LIKE ?", selectionArgs, null, null, null, "LIMIT 150" );
Since all the results are equally valid suggestions, the order will not matter.
Also you wonT be able to show crazy amount of suggestions anyway so you can simply use some fixed limit count depending on your UI. I gave 150 as an example.
Hope it helps..

Categories

Resources