Possible to store time in SQLite database? - android

QUESTION: Im making a flashcard app and when the user clicks "easy" for example, I want to increase the time of the card, then that card won't appear until the time goes reaches 0.
e.g. "Card 1" has a time of 0 at default , user clicks "I know button" and the time on that card increases to 5 mins (5:00), then that card wont appear again for 5 minutes until timer is back to 0, is this possible to do?

is this possible to do?
I believe that if you consider what SQLite is capable of and what an Android App is capable of then Yes. However using SQLite alone then No.
Typically, to get your outcome, the time would remain constant in the database but you would extract and thus show only the rows that met the criteria e.g. the time stored is less than or equal to the current time.
Clicking I know would then update the respective row and set the value to the current time plus 5 minutes, thus an extract, which could be timer based would then not show the respective row as it's then greater than the current time.
As for the timer SQLite does not have a built in timer. It is a database manager whose job is to store and retrieve structured data.
As an example consider the following, which shows the principle:-
DROP TABLE IF EXISTS flashcard;
CREATE TABLE IF NOT EXISTS flashcard (cardtitle TEXT, cardtimer INTEGER);
INSERT INTO flashcard VALUES ('Card1',strftime('%s','now')),('Card2',strftime('%s','now','+1 minute')),
('Card3',strftime('%s','now','+2 minute'));
SELECT *,strftime('%s','now') FROM flashcard WHERE cardtimer <= strftime('%s','now');
UPDATE flashcard SET cardtimer = strftime('%s','now','+5 minutes') WHERE cardtitle = 'Card1';
SELECT *,strftime('%s','now') FROM flashcard WHERE cardtimer <= strftime('%s','now');
This:-
drops and creates a table with 2 columns,
a column named cardtitle that stores the title of the card
a column named cardtimer for the time when the card can be displayed on or after
adds 3 rows with unique titles the time fors the first being the current time, the time for the second 1 minute later,and for the third another minute later.
An extract (SELECT query) that displays only the rows where the timer is now or earlier (irrespective of when it is run).
this shows just the first of the 3 rows as the others are in the future
An Update that changes the time of the first row to be 5 minutes from now
Another Extract using the same query as per 3
this shows nothing because now all 3 rows are in the future
Running the above results in :-
i.e. just Card1 is extracted
Then :-
i.e. all of the cards are now in the future.
However if the same extract is then run a while later (but sooner then 5 minutes later), as can be seen some 139 seconds later, then :-
If then after 5 minutes and the same extract is run then :-

Related

Database table design for Restaurant Ordering System

I need help to design DB/table for Restaurant Ordering System.
1) Captain will take order on Android device and after Placing an order from Customer, he (captain) will Print Order.
2) Captain can alter/add order based on Customer's demand
3) Finally based on customer's demand captain will finalised bill and Print the bill
Some Cases for Placing Order
1) Place Order and not cancelled and finalised bill
2) Place Order - say 4 Burgers , after finish, again customer Place order - say 3 Burgers, not cancelled, and finalised bill
3) Place Order - say 4 Burgers , after finish , again Place order - say 3 Burgers, and Customer asks to Cancel 1 Burger, then finalised bill
4) Place Order - say 4 Burgers, then, Cancel 2 Burger, then after sometime, Place Order 4 Burgers then finalised bill
5) Place Order - 4 Burgers, after sometime, Cancel 2 Burgers, after sometime, Place Order 4 Burgers, after sometime Cancel 2 and then finalised bill
i have already created , menu_card (i.e item), table_info
Billing Table :
id
table_no
bill_no
item_name
quantity
repeat_quantity
print_status (Printed/Not Printed)
ongoing (Yes/No(if no -then finished) )
date_time
Which field should i add in case 3,4,5 for Placing an order
I am confused what if Customer ask for "Cancel Order" , after finish current Order, he asks for same Item.
New EDIT :
I am showing the List of Ordered Items, where captain can touch to update the order,
I m thinking to add cancelled_items_quantity in table and for every new order i will make new entry to database to add those order,
E.g. Customer has ordered 4 Burgers, then it will add to the DB, now after finishing it off, if he asks for 3 burgers, again new entry will be made rather to modify existing 4 to 7, and even if he cancels the order, suppose 2 from 3 Burgers, then update will be made on same entry i.e. it will update cancelled_items_quantity to 2 from default 0
Pls Help
I'd start with making a separate table for items, orders and bills. Since one bill can contain multiple orders and an order multiple items.
As for your example cases, only write finalised data to the database. Keep non-finalised orders in memory on the app. Once the user clicks 'Ok' or 'Finish' the order is finalised and you can write it to the DB.
If you would change the order every time in the database, you'd do way too much transactions which isn't good.
You probably will want separate tables.
1) billing_info
2) table_info
3) item_info
Then correlate to each other as your requirements. Add a 'status' field or similar in item_info so you can easily update its value whenever user request changes.
EDIT
How about for item_info table, for each individual item that customer has ordered, create an entry. Then any changes, update the status.
I visualize on the android tablet, i can see a whole list of every items that customer has ordered.
Eg.
1 steak
1 ice tea
1 steak
1 coffee
1 coffee
So for each item there can be 2 options.
1) to remove the entry before confirmation
2) to change the status after confirmation
Before confirmation, changes are just on the UI only. So we can use option1 to update the UI. I supposed the complications come after confirmation and customer wants to change the order. So we use option2.
2 steak ordered. Now customer wants to cancel 1. So waiter just change the status of 1 steak to 'cancel'.

Restricting displaycount of a row in sqlite table

I have two columns in a table. I am using this table in an android application. For ex., TAB1:
when I display One, the display_count of 1 should increment by 1. Like that, I have to display the names continuously through out my application. Mean while, the display_count is getting too big in long run. Is there any option in sqlite, to restrict the column data, such that, if I reach a certain value say display_count = 64 for a row, the display_count should should reset to 1 and again start from 1. To say clearly, display_count should not exceed 64.
Logically while updating, you can use (col=col+1)%65 instead of col=col+1. The thing is count will again start from 0 instead of 1

Get unique random word from pool each day

I've pool of words (around 200 now) that I want to display randomly each day without repetition.
In shared preference I store the date of last displayed word and if the date today is same, I display the same word that was displayed last time, it today is another day I need to get another random word from the pool and display it.
I've tried to achieve this via two methods:
Method 1: Using sqlite db
Pre fill a db in assets folder (db has a table with two columns, words and isUsed)
on onCreate(SQLiteDatabase database) copy pre filled db to /data
use sqlite to get a random entry from db and update its isUsed couter to true
shave this word in shared preference so that if user opens the app again in the same day then show this word
If I've to update the words in db then(by 150):
create another db in assets folder with new words
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) copy this db to /data
copy each words in the original db row by row keeping the isUsed column intact
Instead of using pre filled db I can insert 200 words using SQL statement in oncreate and later update the other 150 with sql statements in onUpgrade.
Method 2: Using shared preferences
use to save 200 words
Create a string with random numbers upto 200 and save it in shared preference
pop one random number each day and show word with that index. If it is the same day then don't pop but show the last word
If I've to update the words(by 150):
check by how much the words number increased and generate those increased numbers in random order and shuffle it back to the original random string array
So my question is I feel none of this algo is good enough. Is there any better way to achieve this and if not should I go with method 1, method 1 but without pre filled db or method 2?
Why not just load strings from simple text file in assets during onCreate/onUpgrade, shuffle them and insert into database? Then when you need to know which word to show, just calculate number of days from application installation (N) and show N-th word.
I feel the Method 1 WITH pre-filled table is the best bet. That will helps you in the sens e of expandability and randomness.
Any huge task in onCreate should be avoided, since it'll lag your application. And an SQLLite db will be helpful if you need to increase the number of words later.
The method kriomant suggested is good, but lags the freedom of randomness. We can predict the text after two complete cycles if one sits and tries for it :-)

Android content provider update certain columns

I am trying to make an android application that will identify how much time is left for a task to be completed. I have followed Vogella's tutorial, particularly this part http://www.vogella.com/articles/AndroidSQLite/article.html#todo to make a contentprovider and database. It populates a listview with two things, the name of the task and how many days are left (the latter is calculated when the user selects his end date in another activity). My app calcualtes the current date and subtracts it from the end date and stores how many days are left in the database. The problem is that this is only stored once. Three days from now it will still say 4 days left. I want the app to check for how many days are left every time the client starts it (check current date, subtract from end date and update that column in the database). The problem is I'm not sure how to do it. If somebody could give me some guidance I would appreciate it.
do the calculation then do getContentResolver().update(uri,values,selection,selectionArgs);
EDIT:
so just update with the values
ContentValues values = new ContentValues();
values.put(HabitTable.TIME); //whatever column you want to update, I dont know the name of it
...//any other values you want to update too
getContentResolver().update(HabitTable.CONTENT_URI,values,HabitTable.ID+"=?",new String[] {String.valueOf(id)}); //id is the id of the row you wan to update
obviously you will need to replace stuff with the correct column names

Android - easy/efficient way to maintain a "cumulative sum" for a SQLite column

What is the best way to maintain a "cumulative sum" of a particular data column in SQLite? I have found several examples online, but I am not 100% certain how I might integrate these approaches into my ContentProvider.
In previous applications, I have tried to maintain cumulative data myself, updating the data each time I insert new data into the table. For example, in the sample code below, every time I would add a new record with a value score, I would then manually update the value of cumulative_score based on its value in the previous row.
_id score cumulative_score
1 100 100
2 50 150
3 25 175
4 25 200
5 10 210
However, this is far from ideal and becomes very messy when handling tables with many columns. Is there a way to somehow automate the process of updating cumulative data each time I insert/update records in my table? How might I integrate this into my ContentProvider implementation?
I know there must be a way to do this... I just don't know how. Thanks!
Probably the easiest way is with a SQLite trigger. That is the closest I know
of to "automation". Just have an insert trigger that takes the previous
cumulative sum, adds the current score and stores it in the new row's cumulative
sum. Something like this (assuming _id is the column you are ordering on):
CREATE TRIGGER calc_cumulative_score AFTER INSERT ON tablename FOR EACH ROW
BEGIN
UPDATE tablename SET cumulative_score =
(SELECT cumulative_score
FROM tablename
WHERE _id = (SELECT MAX(_id) FROM tablename))
+ new.score
WHERE _id = new._id;
END
Making sure that the trigger and the original insert are in the same
transaction. For arbitrary updates of the score column, you would have to
have to implement a recursive trigger that somehow finds the next highest id (maybe by selecting by the min id
in the set of rows with an id greater than the current one) and updates its
cumulative sum.
If you are opposed to using triggers, you can do more or less the same thing in
the ContentProvider in the insert and update methods manually, though since
you're pretty much locked into SQLite on Android, I don't see much reason not to
use triggers.
I assume you are wanting to do this as an optimization, as otherwise you could just calculate the sum on demand (O(n) vs O(1), so you'd have to consider how big n might get, and how often you need the sums).

Categories

Resources