Making calculation from SQLite - java

I am trying to do two SQLite tables, one to enter data and another one to retrieve the calculated data.
First I want to let the client enter some REAL data and then calculate in the background and put the new data to the textview.
For now, I tried to retrieve it from one table.
#Override
public void onCreate(SQLiteDatabase db) {
String sSQL;
sSQL = "CREATE TABLE " + DataContract.TABLE_NAME +
"(" +
DataContract.Columns._ID + " INTEGER PRIMARY KEY NOT NULL, " +
DataContract.Columns.PRODUCT_NAME + " TEXT, " +
DataContract.Columns.PRODUCT_WIDTH + " REAL, " +
DataContract.Columns.PRODUCT_LENGHT+ " REAL, " +
DataContract.Columns.PRODUCT_PRICE+ " REAL, " +
//This is the data I want to calculate and put to a textview in a
//new intent
DataContract.Columns.PRODUCT_TOTAL_PRICE + " REAL)";
Log.d(TAG,sSQL);
db.execSQL(sSQL);
}
I have a Serializable class and I tried to calculate the data in this class.
private final String ProductName;
private final double ProductLenght;
private final double ProductWidth;
private final double ProductPrice;
private final double ProductTotalPrice;
Then I tried to calculate the data in getter method.
public double getProductTotalPrice() {
return (getProductWidth() * getProductLenght() * getProductPrice())/1000;
}
However, I dont know how to put retrieve the calculated data back to the textview.
Should I create two tables or one table is enough for this operation ?
And also what is the easiest way to calculate data inside Java code and put it back to a column ?
Thank you !

And also what is the easiest way to calculate data inside Java code
and put it back to a column ?
To do nothing (i.e. calculate the value when extracting the data and reduce the amount of data stored in the database)
To add another column for the calculated value would be a waste as you can calculate the value when extracting the data (into the cursor) e.g. :-
Assuming the table (called myproducts) is populated as follows (note no PRODUCT_TOTAL_PRICE column as it's not needed) :-
Then extracting it using the query :-
SELECT
_ID,
PRODUCT_NAME,
PRODUCT_WIDTH,
PRODUCT_LENGTH,
PRODUCT_PRICE,
(PRODUCT_WIDTH * PRODUCT_LENGTH * PRODUCT_PRICE)/1000 AS CALCULATED_TOTAL_PRICE
FROM myproducts;
Will result in :-
You could have a method in your Database Helper such as :-
public double Cursor getTotalpriceBtId(long id) {
double rv = 0;
String column_name = "totalprice";
String calculation = "(" +
DataContract.Columns.PRODUCT_WIDTH + " * " +
DataContract.Columns.PRODUCT_LENGHT + " * " +
DataContract.Columns.PRODUCT_PRICE + ")/1000";
String[] columns = new String[]{calculation + " AS " + column_name};
String whereclause = DataContract.Columns._ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = this.getWritableDatabase().query(
DataContract.TABLE_NAME,
columns,
whereclause,
whereargs,
null,null,null
);
if (csr.moveToFirst) {
rv = csr.getDouble(csr.getColumnIndex(column_name));
}
csr.close();
return rv;
}
The underlying SQL is similar to the example above. However, just the one column is needed.
However, I dont know how to put retrieve the calculated data back to
the textview.
Something along the lines of :-
yourTextView.setText(String.valueOf(yourDBHelperInstance.getTotalpriceBtId(ID_OF_THE PRODUCT)));
or perhaps :-
yourTextView.setText(String.valueOf(yourproduct.getProductTotalPrice()));

No need to create two tables
after inserting the value into table you just create a function by below query
select sum(your column name) from yourtablename where condition on which basis you filter the data.

Related

Android : Calculate sum and group by month (SQLite)

Is there are any option to select amount, group them by month and calculate sum. I tried to get total sum of each month and pass it to ArrayList.
Example of data:
Amount Date
230 04/03/19
500 05/03/19
400 04/04/19
600 06/04/19
100 04/03/19
... ...
My code structure
private String CREATE_BILLS_TABLE = "CREATE TABLE " + TABLE_BILLS + "("
+ COLUMN_BILL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_BILL_USER_ID + " INTEGER,"
+ COLUMN_DESCRIPTION + " TEXT,"
+ COLUMN_AMOUNT + " INTEGER,"
+ COLUMN_DATE_STRING + " TEXT,"
+ COLUMN_COMPANY_NAME + " TEXT,"
+ COLUMN_CATEGORY + " TEXT,"
+ " FOREIGN KEY ("+COLUMN_BILL_USER_ID+") REFERENCES "+TABLE_USER+"("+COLUMN_USER_ID+"));";
public ArrayList<Bills> getDateByUserID(int userID){
SQLiteDatabase db = this.getReadableDatabase();
// sorting orders
ArrayList<Bills> listBillsDates = new ArrayList<Bills>();
Cursor cursor = db.query(TABLE_BILLS, new String[] { COLUMN_BILL_ID,
COLUMN_BILL_USER_ID, COLUMN_DESCRIPTION, COLUMN_AMOUNT, COLUMN_DATE_STRING, COLUMN_COMPANY_NAME, COLUMN_CATEGORY}, COLUMN_BILL_USER_ID + "=?",
new String[] { String.valueOf(userID) }, COLUMN_DATE_STRING, null, null, null);
if (cursor.moveToFirst()) {
do {
Bills bills = new Bills();
bills.setAmount(cursor.getInt(cursor.getColumnIndex(COLUMN_AMOUNT)));
bills.setDateString(cursor.getString(cursor.getColumnIndex(COLUMN_DATE_STRING)));
// Adding record to list
listBillsDates.add(bills);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return category list
return listBillsDates;
}
I believe that a query based upon :-
SELECT sum(COLUMN_AMOUNT) AS Monthly_Total,substr(COLUMN_DATE_STRING,4) AS Month_and_Year
FROM TABLE_BILLS
WHERE COLUMN_BILL_USER_ID = 1
GROUP BY substr(COLUMN_DATE_STRING,4)
ORDER BY substr(COLUMN_DATE_STRING,7,2)||substr(COLUMN_DATE_STRING,4,2)
;
Note that other columns values would be arbritary results and as such cannot really be relied upon (fine if the data is always the same). Hence they have not been included.
Will produce the results that you want :-
e.g.
Using the following, to test the SQL :-
DROP TABLE IF EXISTS TABLE_BILLS;
CREATE TABLE IF NOT EXISTS TABLE_BILLS (
COLUMN_BILL_ID INTEGER PRIMARY KEY AUTOINCREMENT,
COLUMN_BILL_USER_ID INTEGER,
COLUMN_DESCRIPTION TEXT,
COLUMN_AMOUNT INTEGER,
COLUMN_DATE_STRING TEXT,
COLUMN_COMPANY_NAME TEXT,
COLUMN_CATEGORY TEXT)
;
-- Add the Testing data
INSERT INTO TABLE_BILLS (
COLUMN_BILL_USER_ID, COLUMN_DESCRIPTION, COLUMN_AMOUNT, COLUMN_DATE_STRING, COLUMN_COMPANY_NAME,COLUMN_CATEGORY)
VALUES
(1,'blah',230,'04/03/19','cmpny','category')
,(1,'blah',500,'05/03/19','cmpny','category')
,(1,'blah',400,'04/04/19','cmpny','category')
,(1,'blah',600,'06/04/19','cmpny','category')
,(1,'blah',100,'04/03/19','cmpny','category')
-- Extra data for another id to check exclusion
,(2,'blah',230,'04/03/19','cmpny','category')
,(2,'blah',500,'05/03/19','cmpny','category')
,(2,'blah',400,'04/04/19','cmpny','category')
,(2,'blah',600,'06/04/19','cmpny','category')
,(2,'blah',100,'04/03/19','cmpny','category')
;
SELECT sum(COLUMN_AMOUNT) AS Monthly_Total,substr(COLUMN_DATE_STRING,4) AS Month_and_Year
FROM TABLE_BILLS
WHERE COLUMN_BILL_USER_ID = 1
GROUP BY substr(COLUMN_DATE_STRING,4)
ORDER BY substr(COLUMN_DATE_STRING,7,2)||substr(COLUMN_DATE_STRING,4,2)
;
Results id :-
The above can then be converted for use by the SQLiteDatabase query method. So your method could be something like :-
public ArrayList<Bills> getDateByUserID(int userID) {
SQLiteDatabase db = this.getReadableDatabase();
String tmpcol_monthly_total = "Monthly_Total";
String tmpcol_month_year = "Month_and_Year";
String[] columns = new String[]{
"sum(" + COLUMN_AMOUNT + ") AS " + tmpcol_monthly_total,
"substr(" + COLUMN_DATE_STRING + ",4) AS " + tmpcol_month_year
};
String whereclause = COLUMN_BILL_USER_ID + "=?";
String[] whereargs = new String[]{String.valueOf(userID)};
String groupbyclause = "substr(" + COLUMN_DATE_STRING + ",4)";
String orderbyclause = "substr(" + COLUMN_DATE_STRING + ",7,2)||substr(" + COLUMN_DATE_STRING + ",4,2)";
ArrayList<Bills> listBillsDates = new ArrayList<Bills>();
Cursor cursor = db.query(TABLE_BILLS, columns, whereclause,
whereargs, groupbyclause, null, orderbyclause, null);
if (cursor.moveToFirst()) {
do {
Bills bills = new Bills();
bills.setAmount(cursor.getInt(cursor.getColumnIndex(tmpcol_monthly_total)));
bills.setDateString(cursor.getString(cursor.getColumnIndex(tmpcol_month_year))); //<<<<<<<<<< NOTE data is MM/YY (otherwise which date to use? considering result will be arbrirtaryy)
// Adding record to list
listBillsDates.add(bills);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return category list
return listBillsDates;
}
The above has been tested and run and using the following code :-
ArrayList<Bills> myMonthlyTotals = mDBHelper.getDateByUserID(1);
Log.d("BILLSCOUNT","The number of bills extracted was " + String.valueOf(myMonthlyTotals.size()));
for (Bills b: myMonthlyTotals) {
Log.d("MONTHYLTOTAL","Monthly total for " + b.getDateString() + " was " + String.valueOf(b.getAmount()));
}
In an activity, resulted in the following in the log
:-
04-14 11:58:25.876 16653-16653/? D/BILLSCOUNT: The number of bills extracted was 2
04-14 11:58:25.877 16653-16653/? D/MONTHYLTOTAL: Monthly total for 03/19 was 830
04-14 11:58:25.877 16653-16653/? D/MONTHYLTOTAL: Monthly total for 04/19 was 1000
Please consider the comments in regard to values from non-aggreagted columns be arbitrary values. As per :-
Each non-aggregate expression in the result-set is evaluated once for an arbitrarily selected row of the dataset. The same arbitrarily selected row is used for each non-aggregate expression. Or, if the dataset contains zero rows, then each non-aggregate expression is evaluated against a row consisting entirely of NULL values. SELECT - 3. Generation of the set of result rows.
As per the comments, using recognised date formats can make the underlying SQL simpler and likely more efficient.

How to create dynamic sql string according to unknown column count

I think the title is clearly. There is a sqlite app in android. The app is when starts, it's creates a database and tables. But the tables, columns, types, column count absolutely not specific. So, I need to create a perfect dynamic structure. I will take columns, tables, types and anything of about database from a xml. That is the point, the xml...
String query = "CREATE TABLE IF NOT EXISTS a(" + col_parameter1 +" " type_paramater1+","+ ... col_paramaterN + " " + type_parameterN +")" ;
I dont know how many creates table, how many colunms. I do try too way but all of them not perfect.
Try this. I think it will help you
class Column {
String name;
String type;
}
public class Main{
//Fill colums with data read from xml
public String createTableQuery(List<Column> colums){
StringBuffer query = new StringBuffer();
query.append("CREATE TABLE IF NOT EXISTS a(") ;
for(int i = 0; i < colums.size(); i++){
Column col = colums.get(i);
query.append(" " + col.name + " " +col.type + ", ");
}
query.append(")");
return query.toString();
}
}

Sqlite insert and update values of other columns

I have two tables; a 'parent' and a 'child' table. (not SQLite defitinions, just something i call them)
Everytime a child-object is created, it is assigned the value 0 in one of its columns.
When a new parent-object is created, every unassigned child-object, has to update the value mentioned before, to the parent-object's ID. My code looks like this:
public long createWorkout(String workoutName){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, workoutName);
//Creates a new parent-object (a workout - the childs are exercises)
//the generated ID is returned as a long (workout_pk_id)
long workout_pk_id = db.insert(TABLE_WORKOUT, null, values);
//Selects all objects in the child-table with KEY_WORKOUT_ID = 0 (the column mentioned before)
String selectQuery = "SELECT * FROM " + TABLE_EXERCISE + " WHERE " + KEY_WORKOUT_ID + " == " + 0;
Cursor cursor = db.rawQuery(selectQuery, null);
//Takes each found object with value 0, and updates the value to the returned parent-ID from before.
if (cursor.moveToFirst()) {
do {
String k = "UPDATE " + TABLE_EXERCISE + " SET " + KEY_WORKOUT_ID + " == " + workout_pk_id;
db.execSQL(k);
} while (cursor.moveToNext());
}
return workout_pk_id;
}
But for some reason this doesn't work. The ID the childs/exercises remains 0. Can you help me?
I don't know if the error is somewhere in the setup of my tables, in that case i could provide some more information.
Thanks in advance. /Jeppe
EDIT: This is used in android, and I have debugged and verified that the workout_pk_id is returned, 45 objects are found in the selectQuery and yet it doesn't work. I also tried ContentValues to update the values, didn't work.
Edited the " == " to " = ", but the value is still not updated.
This is from eclipse - I've created a workout called "test", with the ID 160.
The exercise "test1" has the ID 430 (unique) but the workout_id is still 0.
It's been awhile since I did any Android stuff but I believe the "==" operator is incorrect:
String k = "UPDATE " + TABLE_EXERCISE + " SET " + KEY_WORKOUT_ID + " == " + workout_pk_id;
The operator you're using is a comparative operator, "=" is the assignment operator.
I also believe there is a better way to do what you are trying to do, currently refreshing my memory on Android so I'll get back to you. In the meantime tell me if replacing the operator works
Yeah so another way you can do this is by using subqueries. So it would look something like:
UPDATE TABLE_EXCERCISE SET KEY_WORKOUT_ID = WORKOUT_PK_ID WHERE KEY_WORKOUT_ID =
(
*subquery here to select parent object ids*
)
Here's a link to help:
http://www.tutorialspoint.com/sqlite/sqlite_sub_queries.htm
Let me know how this works for you.
I think you have to look to your update query.
It has to be:
String k = "UPDATE " + TABLE_EXERCISE + " SET " + KEY_WORKOUT_ID + " = " + workout_pk_id;
Look at the "=" between KEY_WORKOUT_ID and workout_pk_id.

Android: Retrieve data from sqlite Database

I currently I have my database set up like the following:
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LOCKERNUMBER
+ " TEXT NOT NULL, " + KEY_STATUS + " INTEGER, " + KEY_PIN
+ " INTEGER);");
And I am trying to write a method to get the pin code from the column for a specific locker number. Any ideas? I am very new I would like think I would need to use the query function and a cursor. I just one to get the integer value and store it into an int variable so I can compare the pin codes from what the user types in to the one in the database.
Queries to database returns in a Cursor object. You should use the db.query() method to get a row(s). Pass the table name, an array of columns you want to get (or null if you want all of them), pass a selection string that should be like "id = ?" or "key > ?", etc, then pass a String array containing the value for those ? inside the previous string,
and finally pass null for having, groupBy and orderBy unless you want to use them.
Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ROWID }, "id = ?", new String[] { Integer.toString(id) }, null, null, null);
After you get the Cursor, do cursor.moveToFirst() or cursor.moveToPosition(0) (can't remember the exact method, but the point is to move the cursor to the first retrieved row)
then you're going to iterate through the cursor with
while(cursor.moveToNext()) {
int keyRowIdColumnIndex = cursor.getColumnIndex(KEY_ROWID);
int yourValue = cursor.getInt(keyRowIdColumnIndex);
int keyLockNumberColumnIndex = cursor.getColumnIndex(KEY_LOCKNUMBER);
int pin = cursor.getInt(keyLockNumberColumnIndex);
}
This is a pretty straight forward task and there is a bunch of tutorials, examples, similar questions on SO:
How to perform an SQLite query within an Android application?
In general - you need to query the database passing your search arguments. See the documentation.
It will return you a Cursor with the matching results, which you can then iterate over and manipulate as you wish.
Fyi - storing password in a database table is a bad idea. On Android databases can be accessed and easily read. You either need to encrypt your data or think of another way to store it if it's important.
//Try This code
public String getLabeId(String LockNo)
{
ArrayList<String> Key_Pin_array = new ArrayList<String>();
Cursor cur = db.rawQuery("SELECT * FROM DATABASE_TABLE where KEY_LOCKERNUMBER = '" + LockNo + "'", null);
try {
while (cur.moveToNext())
{
System.out.println("Key_Pin" + cur.getString(3));
Key_Pin_array.add(cur.getString(3));
}
}
catch (Exception e)
{
System.out.println("error in getLabelID in DB() :" + e);
}
finally
{
cur.close();
}
return id;
}

sqlite how to add value on conflict

I have a database with product name,product price and product counter.
Product name is unique,product price gets replaced everytime a new value is entered and the problem is the product counter.
Its default value is 1,when a new product is entered his value is set to 1.I need it to increment whenever there is a conflict for the product name.So if Cheese is entered twice,the counter will say 2 and so on.
What i need it to do is when there is a conflict,add 1 to its value. I want to do it this way because i'll need this later.I'll need to add the inputed value to the table value on some other thing i plan to implement in my app.
How can i achieve this ? I'd like to keep doing it the way i'm doing it now,with the contentvalues method of inserting and not with the sqlite syntax(INSERT,SELECT,etc).Is that even possible ? Cuz i'm an absolute 0 at sqlite syntax.And also,i need it to have a method that i can call in other activities to insert into the database (like insertCountry(Japan,10))
public class SQLiteCountryAssistant extends SQLiteOpenHelper {
private static final String DB_NAME = "usingsqlite.db";
private static final int DB_VERSION_NUMBER = 1;
private static final String DB_TABLE_NAME = "countries";
private static final String DB_COLUMN_1_NAME = "country_name";
private static final String DB_COLUMN_2_NAME = "country_price";
private static final String DB_COLUMN_3_NAME = "country_counter";
private static final String DB_CREATE_SCRIPT = "create table "
+ DB_TABLE_NAME
+ " (_id integer primary key autoincrement, country_name text UNIQUE ON CONFLICT REPLACE,country_price text,country_counter integer default '1' );)";
And this is how i insert :
public void insertCountry(String countryName, String countryPrice) {
sqliteDBInstance.execSQL("INSERT INTO " + DB_TABLE_NAME
+ "(country_name, country_price) VALUES('" + countryName
+ "', '" + countryPrice + "')");
}
Incrementing a value to a specific cell is not available in sqlite. You have to read the current value of cell and add your needed value to it and replace it with the old one. You can use update method.
public void update(String countryName, String price, long id) {
ContentValues cv = new ContentValues();
cv.put(dbHelper.COLUMN_1, countryName); // These Fields should be your
// String values of actual column
// names
cv.put(dbHelper.COLUMN_2, price);
database.update(dbHelper.TABLE_NAME, cv, "_id " + "=" + id, null);
}
every time you're going to add a row to your table you have to read all it and check if the row exists.here is a method to retrieve all rows:
public List<TableRow> getAllRows() {
List<TableRow> rows= new ArrayList<TableRow>();
Cursor cursor = database.query(Helper.TABLE_SITUPS, allColumns,
null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
TableRow row = cursorToRow(cursor);
comments.add(row);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return rows;
}
TableRow is a class for database table rows and contains fields stands for actual table columns.
with iterating this list and get "country" value of each one you can understand if that row exists or not.
These are basic concepts of sqlite databases programming. I recommend you to research a bit in this matter.
I don't know your database class, but check this method:
return this.sqliteDBInstance.insertWithOnConflict(DB_TABLE_NAME, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
If you are creating your column correctly, if there is a conflict, the new entry will replace the old one.
EDIT: after your last comment, all you need is an update: first query your database with the name of your item (check carefully if parameters are ok):
return this.sqliteDBInstance.query(DB_TABLE_NAME, null, DB_COLUMN_1_NAME + "=?", new String[] {productName}, null, null, null);
This will return a Cursor with 0 or 1 row. If there aren't row, you can proceed inserting data normally (don't forget to add your counter: is 1 on first insert):
public void insertCountry(String countryName, String countryPrice) {
sqliteDBInstance.execSQL("INSERT INTO " + DB_TABLE_NAME
+ "(country_name, country_price) VALUES('" + countryName
+ "', '" + countryPrice + "', '" + countryCounter + "')");
}
if there is 1 row, your product is already on your database, so just iterate the Cursor, take the value on counter, add +1 on it and update your database with this method:
public int update (String table, ContentValues values, String whereClause, String[] whereArgs)

Categories