destroy the database- android life cycle - android

Hello I am trying to figure out a way to destroy my database every time the application starts either by returning from the background or reopen after it was closed. The issue is that when I am trying to run my application for the first time I get a null and my application crushes.
My application:
The user is prompt with a login screen and I create the db, move to another activity to perform a query. From this activity the user cannot go back to login, and will be only able to go to the phone home screen. When I will go to the home screen and re open the application I want to wipe out the db and start like it is my first time the user uses the application.
I know that this is not actually practical for an application, but this is just for learning.
I tried to do db.close() and context.deleteDatabase(db.getPath()); in onResume and onRestart, but this always crushes my application. I also tried to check that 'db.getPath()!=null' , but this did not help either.
thank you

Since you are aware that is not the most practical way to use databases I guess I won't bug you for that.
What you want to do is not to call the method to delete the database content during on Resume() or on Restart(), you actually want to call that via on Stop().
The method you want to use is
db.delete(String table, string whereClause, String [] whereArgs);
Passing the name of the table you want to delete, i.e "user_food_database", a whereclause which would be null in your case since you want to delete ALL rows, and null for whereArgs.
Here's the official doc:
"Convenience method for deleting rows in the database.
Parameters
table the table to delete from
whereClause the optional WHERE clause to apply when deleting. Passing null will delete all rows.
Returns
the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause. "
You can also call:
deleteDatabase(File pathToDatabase)
in case you have more than one table in your database, but recreating the database itself everytime is expensive, and deleting only the content may result better.

I suggest that you simply wipe the database, i.e., delete all data (or even drop the tables). This is not a direct answer to your question, but has the same effect.

Just drop all tables in the open() method of your SQLiteDatabaseHelper and recreate the tables by calling onCreate(db). Works of course only when you are opening the db only once per app start.

Related

How to execute java code when an SQLite trigger is fired in Android app

In my database I have three tables (A,B,C) in which table A has foreign keys into both B and C. When I delete from either B or C, I want to also delete the row in A if BOTH foreign keys are null, and I have a constraint placed on the foreign keys that sets them to null if the B or C table deletes that key. I have two triggers on tables B and C to delete a row from A when appropriate and this seems to be working okay.
The trouble I'm having is there is a file name stored in table A that I want to delete but I can't if I set up triggers to handle my situation. So is there any way to know when a trigger is fired? Do I have to manually execute the logic for my trigger so I can delete the file too?
tl;dr: How can I execute some java code when a trigger is fired in my applications sqlite database?
SQLite itself has user-defined functions, but the Android database API does not allow you to access them.
You have to do the checks in your code whenever you have issued such a DELETE statement.
Best way to do this I found is to return the rowID.
long newRowId;
newRowId = db.insert(tableName,primaryKey,values); (insert or delete or whatever)
If that trigger fires you will get a row id of -1. Then just show your message or run your query where you delete something else when you get a row id of -1

Last object not saved after table was truncated in ActiveAndroid

I use ActiveAndroid to save my objects to the database, it works mostly well. In my application, I use the following scenario:
I save a new object to a table in my database
I select some objects from that table
I add them to a List<>
I delete everything from that table
I use foreach on my List and call 'save' on each object
And here comes the problem. In my table the objects are saved except the aforementioned most recently saved one. I created a counter to check, how many 'save' was called: the counter is 1 more than the count of the objects in the table. I debugged it, no exception was raised, the save was called. I use the latest version of ActiveAndroid (3.0.99)
Any ideas what I should check?
Well, the problem can be seen in the scenario if your read it through.
I copy an existing object to the memory and try to reinsert it. The ORM checks only the mID of the object and if it is not null, it calls an update. As my object had an id, it was tried to be updated though the table was truncated so nothing was updated.
I don't know if it is intentional that the model never checks the table just its own id but it can lead to issues like this.

Android SQLite - Update table only if different

I currently successfully use a SQLite database which is populated with data from the web. I create an array of values and add these as a row to the database.
Currently to update the database, on starting the activity I clear the database and repopulate it using the data from the web.
Is there an easy method to do one of the following?
A: Only update a row in the table if data has changed (I'm not sure how I could do this unless there was a consistent primary key - what would happen is a new row would be added with the changed data, however there would be no way to know which of the old rows to remove)
B: get all of the rows of data from the web, then empty and fill the database in one go rather than after getting each row
I hope this makes sense. I can provide my code but I don't think it's especially useful for this example.
Context:
On starting the activity, the database is scanned to retrieve values for a different task. However, this takes longer than it needs to because the database is emptied and refilled slowly. Therefore the task can only complete when the database is fully repopulated.
In an ideal world, the database would be scanned and values used for the task, and that database would only be replaced when the complete set of updated data is available.
Your main concern with approach (b) - clearing out all data and slowly repopulating - seems to be that any query between the empty and completion of the refill would need to be refused.
You could simply put the empty/repopulate process in a transaction. Thereby the database will always have data to offer for reading.
Alternatively, if that's not a viable solution, how about appending newer results to the existing ones, but inserted as with an 'active' key set to 0. Then, once the process of adding entries is complete, use a transaction to find and remove currently active entries, and (in the same transaction) update the inactive entries to active.

Using sqlite to dynamically create tables in android

So my fundamentals of creating and manipulating databases are a bit messed up. My aim here is that whenever the app is launched, the user is allowed to specify a table name, and whatever data is then collected is put into that table.
However, I'm confused as to how to do this. Do I simply pass the value of a user entered variable as the table name in my contentprovider class and execute sqlite statements to create it?
I've read/reading the documentation already, so if anyone has any insight or clarity, or even better, code snippets, it would be great.
Why not simply use one table, and create a value that stands for the current app-session, and insert that value with each row. This would make your code simpler, and would still allow you to segregate/filter out the values from a particular app-session. If you want to give the user the ability to enter the value (as you are giving them the ability to choose the table name) you'd just want to check to see if that value had already been used, just as you would have to see if the table-name had already been used.

Android Widgets: Where would the 'insert' step for a database occur?

I have a widget that currently takes a random string from an array and sets it to text view on update. The issue here is that the same item can be re-used multiple times in a row due to the string being 'random'
In order to solve this I was going to create a table that held String text, and int viewednum and increment the viewed number each time 'get text' was called. (on update in the widget).
My Question: If I put the insert statements in the widget, won't the data be inserted every time 'on update' is called?
Would it be better for it to go in the DBadapter class somewhere? I'm just unsure about the best way to make sure I don't enter duplicate data. If there is a better alternative like saving a csv file somewhere and using that I'm open to it, it seemed like a sqlite database was the way to go.
Thank you for your time.
That depends on what your onUpdate method does. If each time onUpdate is called it gets a random String from the database, then that would be the place to put it. However, if you are not getting the String during onUpdate, then you should put it in the method where you are accessing your database. I think your confusion is about the purpose of onUpdate. onUpdate doesn't get called every time the user scrolls by the homepage and sees your widget; it gets called regularly on a timescale you specify, and the whole purpose of it is, in a case like yours, to get a new String from the database.
As for your second question, yes, SQlite databases are the way to do it :) I haven't tried saving a csv file or something like that, but I imagine that would be a lot more complex than just using a database.
Declare your database with a UNIQUE constraint on the columns you want to keep unique, then set the desired behaviour via ON CONFLICT in the INSERT statement. ON CONFLICT REPLACE... means the most recent INSERT overwrites. ON CONFLICT IGNORE... keeps the older version.

Categories

Resources