This question already has an answer here:
I want to run a piece of code only once in my application and is when i run it for the first time (newly installed app). How could i do this, can anyone explain giving a piece of code.
Actually, in my android project i want to create database and insert some values on the first run only. After that, that particular piece of code should not run again. How can i achieve this mechanism through SharedPreferences or Preferences.
Sample code will be more helpful.
Wherever you need to run this code in your app:
firstTime
is True in shared preferencesIf not
firstTime
as true in shared preferencesSomething like this:
here's what I do in those situations :
hope this helps
You could try :
Write this in your first activity on create. Then after the code will not execute again.
Before all you can use SQLiteOpenHelper. It is preferred way to do things with database. This class have a
onCreate(SQLiteDatabase)
method, that called when first creating database. I think it suits you well.If you want more flexibility and your first time logic is not tied only with database, you can use sample provided earlier. You just need to put it in startup spot.
There are 2 startup spots. If you have only single activity, you can put your code in
onCreate
method, so it will be like this:Don't forget to put activity declaration in manifest, as well as it's intentfilters (action =
MAIN
, category =LAUNCHER
).If you have more than one activity and you don't want to duplicate your startup logic you can just put your initialization logic in Application instance, that is created before all activities (and other components, such as services, broadcast recievers, content providers).
Just create class like that:
All you need for this to work, is put in
application
tag in AndroidManifest.xml attribute android:name=".App".