I want sum values of the column, but I want to summarize the values by skipping the first value and starting to summarize the second in a row. My code
public int sumColum(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor result = db.rawQuery("select sum(PRICE) from wedding_table", null);
if(result.moveToNext())
return result.getInt(0);
return 0;
}
SQL tables represent unordered sets, so there is no first price, unless another column specifies the ordering.
If you mean the highest or lowest price, then it is pretty easy -- assuming there are no duplicates:
select sum(PRICE) - min(price)
from wedding_table;
Related
I am having a table named keywords in database.I want to retrieve data of alarm and location columns from this table and unable to retrieve them except for contact number.For now I am showing their values in a Toast but every time I run any query to show my alarm or location in Toast its empty.But my contact_number is always shown.Don't understand the cause of this problem .I have also checked my tables view and it is showing the values of alarm ,location in them.
Create Table keywords( contact_number text primary key , alarm text , location text )
and my insert function is
public boolean insertkeys (String alarm ,String location ,String contact){
SQLiteDatabase db = this.getWritableDatabase();
//ContentValues is a name value pair, used to insert or update values into database tables.
// ContentValues object will be passed to SQLiteDataBase objects insert() and update() functions.
// ContentValues contentValues = new ContentValues();
ContentValues contentValues = new ContentValues();
contentValues.put("alarm",alarm);
contentValues.put("location",location);
contentValues.put("contact_number",contact);
long ins = db.insert("keywords",null,contentValues);
long upd = db.update("keywords",contentValues,"contact_number = ?",new String[]{contact});
// db.close();
if(ins == -1 && upd == -1)
return false;
else
return true;
}
I am inserting plus updating my data every single time my save button is clicked.Can anyone here tell how can I write a query to retrieve data of these fields and set it to Toast or Edit text. I am new to Database and stuck here for about a week. Thanks in advance for help :)
You extract data via a SELECT query which is returned as a Cursor when using the Android SDK.
The Cursor is similar to a table in that it has a number of rows, each with a set number of columns as determined by what you select.
To get all rows the SELECT query would be along the lines of :-
`SELECT * FROM keywords`
To do this using the Android SDK you could use the SQLiteDatabase query convenience method e.g. for the above you could use :-
Cursor cursor = db.query("keywords",null,null,null,null,null,null);
check the links above for the values/parameters that can be passed and how they correlate with the SELECT statement.
You then traverse the returned cursor extracting the data, typically using the Cursor's move??? methods. Noting that most will return false if the move could not be made and also noting that the original position in the Cursor is before the first row
As such you could have a method that returns a Cursor as per :-
public Cursor getAllKeys(){
SQLiteDatabase db = this.getWritableDatabase();
return db.query("keywords",null,null,null,null,null,null);
}
You could then process all the rows using :-
Cursor csr = yourDBHelper.getAllKeys();
while (csr.moveToNext()) {
String current_contact_number = csr.getString(csr.getColumnIndex("contact_number");
String current_alarm = csr.getString(csr.getColumnIndex("alarm");
String current_location = csr.getString(csr.getColumnIndex("location"));
...... your code to Toast or use the retrieved values
}
csr.close(); //<<<<<<<<<< you should always close a Cursor when finished with it.
Additional
In regard to the comment :-
Cursor query which you have suggested I tried to make changes in it
like putting column and where clause but after that it returns me
nothing when I execute it.Could you tell me that query too.
The following could be a method to retrieve just the alarm according to a contact number.
public String getAlarmByContactNumber(String contactNumber){
String rv = "";
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(
"keywords", //<<<<<<<<<<<< the FROM clause (less the FROM keyword) typically the name of the table from which the data is to be extracted (but can include JOINS for example, for more complex queries)
new String[]{"alarm"}, //<<<<<<<<<< A String[] of the column names to be extracted (null equates to * which means all columns) (note can be more complex and include functions/sub queries)
"contact_number=?", //<<<<<<<<<< WHERE clause (less the WHERE keyword) note **?** are place holders for parameters passed as 4th argument
new String[]{contactNumber},
null, //<<<<<<<<<< GROUP BY clause (less the GROUP BY keywords)
null, //<<<<<<<<<< HAVING clause (less the HAVING keyword)
null //<<<<<<<<<< ORDER BY clause (less the ORDER BY keywords)
);
if (csr.moveToFirst()) {
rv = csr.getString(csr.getColumnIndex("alarm"));
}
csr.close();
return rv;
}
The above assumes that you would only have/want one alarm per contact number.
The above is in-principle code, it has not been run or tested and may therefore contain some minor errors.
I have a simple SQLite database with two columns.
Col 1 SimpleDateFormat("yyyyDDD") For example 2017001 (for jan 1st, 2017)
Col 2 int of hourly occurances
So each day has a unique code and each day has 24 rows of varying occurances.
How can I get the sum of occurrences for each day sent to an ArrayList(Float)? Eventually this ArrayList will populate an MPAndroidChart. I've successfully pulled the data (without the sum) with the following code. But getting the daily sum with help of my date code has eluded me for days. I've tried many variations of GROUP BY and SUM only to have each crash.
public ArrayList<Float> getOccChartData(){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Float> yNewData = new ArrayList<>();
String query = "SELECT OCC FROM user_table ORDER BY ID DESC LIMIT 96";
Cursor c = db.rawQuery(query, null);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
yNewData.add(c.getFloat(c.getColumnIndex("OCC")));
}
c.close();
return yNewData;
}
It's unclear whether or not you want the sums instead of or with the rows, so assuming that you just want the sums, then perhaps you could do:-
public ArrayList<Float> getOccChartData(){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Float> yNewData = new ArrayList<>();
String query = "SELECT SUM(OCC) AS OCC FROM user_table GROUP BY ID ORDER BY ID DESC"
Cursor c = db.rawQuery(query, null);
while(c.moveToNext) {
yNewData.add(c.getFloat(c.getColumnIndex("OCC")));
}
c.close();
return yNewData;
}
Example
For example assuming your table has (not 24 rows per table for brevity) :-
The the above would result in the cursor containing the following :-
Note! reversal due to ORDER BY DESC (so latest data first).
i.e. for 2017001, 15 + 20 + 30 + 40 = 105 the last row.
yNewData would have 3 elements accordingly:-
yNewData[0] would be 48,
yNewData[1] would be 50 and
yNewData[2] would be 105.
Alternative considerations
If you wanted a range of days then you change the SELECT to be something like :-
SELECT SUM(OCC) FROM user_table WHERE ID BETWEEN 2017001 AND 2017002 GROUP BY ID ORDER BY ID DESC
Where the values 2017001 and 2017002 would be generated according to the required logic and placed into the query string.
In which case the resultant returned data would be :-
yNewData[0] would be 50 and
yNewData[1] would be 105.
If you want all intermediate values as well as the sums then matters would be more complex as in effect you are returning two types of data in a single dimension array.
The above as an SQL Fiddle
Here's the above as a SQL Fiddle
I've stored an Integer as a string in my Sqlite Database on Android but now I need to find the max value of the data. I have the following code:
public String getMaxPageFromMainDB(){
String maxNoStr =null;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT MAX(donebottombar) FROM customers",null);
if(cursor.moveToFirst()) {
maxNoStr = cursor.getString(0);
cursor.moveToNext();
}
cursor.close();
return maxNoStr;
}
When it comes to sorting the max value of numbers stored, 9 is coming before 11.
Is there anything wrong with my code or a way to better sort this without changing the database schema?
As answered below with a little change in code:
Cursor cursor = db.rawQuery("SELECT MAX(CAST(donebottombar AS INTEGER)) FROM customers",null);
When the stored data type is different from how you want to compare the values, you have to convert them:
SELECT MAX(CAST(donebottombar AS INT )) FROM customers;
SELECT MAX(CAST(donebottombar AS TEXT)) FROM customers;
You're trying to do integer calculations on a string.
When using MAX with strings, the "MAX" string is the one at the top of the table.
Quote from "http://www.java2s.com/Tutorial/Oracle/0240__Aggregate-Functions/UseMAXwithstrings.htm":
When you use MAX() with strings, the strings are ordered alphabetically with the "maximum" string being at the bottom of a list and the "minimum" string being at the top of the list.
You need to save that value as an integer in your database and not as a string.
Okay, so I have a high score table. I have two columns, Player name and score..
Every time a new score is to be added to the table I delete the last row, put the new score and new player name in the last row and then sort the table according to the score.
I can't delete the row with minimum score because there might be multiple entries with the same score and I don't want to delete all of them.
You might want to rebuild your table and include an id column with integer primary key autoincrement. You can do quite a bit with that column in place (here's an SO question you can look into for that).
Anyway I don't know how your process goes and why you need to delete the last row but here's an example of using an ID column to get the last row ( which I assume would be the latest insert and is what usually happens if you declare an ID integer primary key autoincrement column):
public int LastInsert() {
SQLiteDatabase db = this.getReadableDatabase();
final String MY_QUERY = "SELECT MAX(" + colID + ") FROM " + myTable;
Cursor cur = db.rawQuery(MY_QUERY, null);
cur.moveToFirst();
int ID = cur.getInt(0);
cur.close();
return ID;
}
From here you can probably just get the result of LastInsert and use that to direct what your delete function should delete.
Imo you're better of maybe just updating the last row instead of deleting and reinserting in it's place though. Something like this :
public int UpdateAcc(Account acc) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(colName, acc.getName());
cv.put(colScore, acc.getScore());
return db.update(myTable, cv, colID + "=?", new String[]{params});
}
I don't remember rather android with sqlite supports multiple commands per statement, but if so this might work:
DELIMITER ;;
SET #LastId = (SELECT ROWID FROM yourTable ORDER BY ROWID DESC LIMIT 1);;
DELETE FROM yourTable WHERE ROWID=#LastId;;
Otherwise you can store this in a integer variable:
SELECT ROWID FROM yourtable ORDER BY ROWID DESC LIMIT 1;
Then use that variable to run the next line
DELETE FROM yourtable WHERE ROWID=#ThatIntegerHere;
Currently in my code i'm using a cursor to retrieve the entire database
My code is
public Cursor getAll() {
return (getReadableDatabase().rawQuery(
"SELECT _id, note, amt, dueDate FROM New", null));
}
The function of retrieving the contents is to populate the same in a listview.
Now I want to retrieve the contents of the first three rows of the same database using cursor to display in another listview.
Need Help, Thanks in Advance.
The correct way to do it is to limit the result number to three:
"SELECT _id, note, amt, dueDate FROM New ORDER BY _id LIMIT 3"
Then you just iterate over the cursor (as usual)
Since you've already obtained a Cursor, in order to get the first three rows of the result, you do this:
Cursor cursor = getAll();
cursor.moveToFirst();
int count = 0;
while(!cursor.isAfterLast() && count < 3)
{
// Grab your data here using cursor.getLong(0), cursor.getString(1) etc.
// and store it an array.
count++;
cursor.moveToNext();
}
cursor.close();
You may want to limit the query results to at most three by adding a LIMIT 0,3 statement to your SQL. Having obtained an array of at most three elements containing your records, you can then proceed to place them in the other ListView you are referring to. You do this by adding them to this ListView's source array. Then call the ListView adapter's notifyDataSetChanged method to have it update itself.
So you can do this in two ways:
Create a separate select:
SELECT * FROM Table_Name LIMIT 3;
Select three rows from cursor:
int n = 0;
cursor.moveToFirst();
while (!cur.isAfterLast() && n < 3) {
// Use the data
n++;
cur.moveToNext();
}
cur.close();