I wonder if it is possible to create a SQLite database when the app got run the first time and already save some data in it.
I don't want to save it every time the app gets started. Just after Installation.
Is this possible?
Just override onCreate() method in class which extends from SQLiteOpenHelper and insert there some data.
Called when the database is created for the first time. This is where
the creation of tables and the initial population of the tables should
happen.
http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#onCreate(android.database.sqlite.SQLiteDatabase) .
For my apps I do the simple trick as in Splash check preference of available Data variable, first time its default is false. Then I read from Database and check is there any items If No then insert data and set preference available data variable to true.
and when you come next time splash it will check again and in your available data variable will get true so you don't need to do anything and continue your flow.
I hope this will help you too :)
SQLiteOpenHelper.onUpgrade should do the trick, simply compare oldVersion with newVersion
Related
I'm trying to use Realm to store a local database of objects. The app checks if the current session is first load and if so populates the local database with an api call. But, if the database is not empty, I would like to use the data already available. To do this, I need to know whether the database is empty or not.
I found this issue on github, but they dont provide a workaround:
https://github.com/realm/realm-java/issues/766
So how should this be done?
If you scroll down that issue page, you can see Realm.isEmpty() is added. :)
Add a realm.isEmpty() method that returns true if there is no objects
in the Realm. It is just a utility method, but fits nicely with the
Realm object store abstraction.
use realm.isEmpty()
I used
if(realmResults.isEmpty()) {action...}
or
if(realmResults.isNullOrEmpty()) {action...]
there's false but action..
What's wrong!? ...T0T
I have build an android application where I call the method insertSampleData()
from the onCreate() method of main activity.
The problem is that onCreate() method is called every-time the app is launched,
this results in filling my database with a lot of sample data.
I want to provide sample data only once when the application is installed. Can anyone please tell me how to do it ? Thanks a lot !
P.S: The method insertSampleData() is used to insert sample data into Sq-lite database.
2 ways of doing this:
Either save if the data was inserted once (e.g. to the SharedPreferences)
Or check if any sample data is already in your database before adding it (but may lead to problems if the user can erase the data)
You could create a check in your Application class, in its onCreate() similar to this one:
SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
boolean firstRun = preferences.getBoolean("firstRun", false);
if(firstRun) {
insertSampleData();
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstRun", true);
editor.commit();
}
While other answers are correct, there is a built-in way to achieve what you want: onCreate and onUpgrade methods of SqliteOpenHelper.
About onCreate() and onUpgrade()
onCreate(..) is called whenever the app is freshly installed.
onUpgrade is called whenever the app is upgraded and launched and the
database version is not the same.
As written here: https://stackoverflow.com/a/8133640/5349594
I would add that if you are using some orm library, most of them support something similar to this.
In your insertSampleData() method, before inserting the data, check the row count in yout table.
If it's 0, execute the INSERTs.
No else statement is needed: proceed to exit.
Note: The sample data will be re-inserted on next run, if not found.
Because insertSampleData() is called in onCreate().
And it will insert the sample data, if no data is found.
Therefore, the table will never be empty on start.
As Hrundi said in comments, you can use if statement, but probably better choice would be to use custom DatabaseHelper class wihic extends SQLiteOpenHelper.
Inside SQLiteOpenHelper you have onCreate method which is called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.
You can google this and you will find a lot of examples.
How do I find the last time when any application was used in Android. Which means last >access time for any app?
Perhaps you could use the Calendar class to save an instance when the onCreate or onDestroy executes for your app. You could then save the time into a private app file using a OutputStreamWriter and just read it's contents using an InputStreamWriter whenever you need it.
As i know there are no instances which records this. You can easily make it yourself by adding a Database and Record every Start with timestamp or calender instances. Then you COUNT(*) it and there you go.
I found the answer my self:
IUsageStats mUsageStatsService = IUsageStats.Stub.asInterface(ServiceManager.getService("usagestats"));
PkgUsageStats[] stats = mUsageStatsService.getAllPkgUsageStats();
Pull out the map from the desired array index. This map contains the last time the app was accessed.
I have an app that depends on SQLite for data which is populated by xmls shipped with the app in the assets folder.
When you run the app the first time it sets a shared preference config_run = false.
then i check if config_run = false then parse the xml and dump the data into db
set config_run = true
Now i realize that when i have to push an update on Google Play and add more content into the XML. Even though i change the database version from 1 to 2. The import script wont run because shared preference config_run value will be set to true.
Any pointers on how to handle this situation ?
Scenarios
First Instal - Ver = 1, DB V = 1 (Data is parsed and dumped into the database)
Bugs Fixed and push and update but no data has changed - ver = 1.1, DB V = 1 (It should just replace the code and not upgrade or re-create the database)
Upgraded the DATA and pushed a new update - ver 1.2, DB = 2 ( No new code but data has to be re-created)
The Flow of My App
The App Starts Splash Activity. If Shared Pref - config_run is equal to false then it starts a Progress Dialog and parses and dumps the data into the database.
Upon Parsing and Creating DB and dumping data it goes to MainActivity.
Second Case
SplashActivity Runs and config_run = true so directly goes to MAin Activity.
As Suggested by few people below if i try to dumb the data into the database in onUpgrade of the SQLiteHelper it will happen only in MAinActivity as i dont open a Db connection in the SplashActivity and the Dialog Progress wont be displayed also.
Add a shared pref of the version number you last ran the script for.
On app start, check the current apk version, and if newer, run the script again and update the pref
Why dont you want use built in sqlite versioning system. DB version is independed from app version. And it does exactly what you want. SQLiteOpenHelper? Every time tou change your db version an onUpgrate callback will be called and you can refill your db. There are a lot of examples.
Instead of setting your shared pref (config_run) to false and making it true, just set the database version into it. When you update your app, check whether you have the same version number in your shared pref. You can do this as shown below:
configRun = settings.getInt("database_version", 0);
if ((DBAdapter.DATABASE_VERSION) == configRun)
{
//skip xml parsing
}
else
{
//first time configRun will be "0" and DBAdapter.DATABASE_VERSION will be 1
// so you need to parse your xml here and set configRun =1
//on update, change your DB version to 2. now again your configRun and DBAdapter.DATABASE_VERSION will mismatch and you can parse your xml.
}
Have your xmlfiles end with the date of the update, and store the last updated date in sharedpref.
On launch you can check search for updates ( in an optimized way ) and if you find a new file with a new date when compared to the last time you know you need to dump the file.
Total hack job :D
Two things you can do:
The right way: Override database provider's onUpdate() to import the file. (as suggested above)
The one line changer: Instead of check for key="config_run", you check and set for key=("config_run"+DB_VERSION) to see if import is needed, and of course, if the key does not exist, you should return false.
This way every time you update the DB number, import job will run again.
This is agnostic to your app version.
I need to recognize first launch of my application or activity.
At this time I need to get some information from server create local database and save info to it. What is the best way to do this?
Create any preferences for example FirstLaunch and set true \ false to it.
Check whether my database exists or not.
Something else?
PS. All server calls must be into one transaction. Ormlite supports transactions?
Thanks.
For the "create database at first run"-purpose, you should use an SQLiteOpenHelper, which offers you the onCreate()-method that is called when:
[...] the database is created for the first time.
The Database-file itself will be created for you (you don't have to do this manually). In this method, you can then perform actions like populating your database with standard entry's.
If you want to populate the database with informations you get from your server, there might be a problem when there is no Internet-connection available.
In this case, I would check if there is a connection available:
If there is, get your informations.
If not, show a Toast or some other notification to inform the user.
To determine if your Database has be populated with the standard entry's, you can use the database-version which is also provided by the SQLiteDatabase-class:
When you first create your Database-object, you call
SQLiteOpenHelpers constructor and pass it 0 as the Database
version.
If you successfully populated your database, you use
setVersion()-method to alter it to 1.
Later in the onOpen()-method, which is called when the
database is opened, you can check if the database was populated by
using the getVersion()-method.
If it is populated, call the super-method to open it.
If not, try populating it.
Further more, the getReadableDatabase() / getWritableDatabase()-methods should be called off the main-thread anyways because:
Database upgrade may take a long time, you should not call this method
from the application main thread, including from
ContentProvider.onCreate().
So getting the informations from the Internet can take place in the onCreate() and in the onOpen()-method (if it wasn't successful at the first try). You can (for example) use a Service to do this.
If you want to solve this problem with database:
Create database with MyDatabasaVersion table and store your version in a single row, for example db_version default value is 0. First time when the application starts you check the db_version if 0 you need to start the syncronisation, after it is finishing set the db_version to 1.
The easiest way should be sharedpreferences. you can call it everywhere form the application context and you can put boolean values in it.
Here are all Android storages.
you should try first option Create any preferences for example FirstLaunch and set true \ false to it.