-1

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.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Devender Goyal
  • 1,450
  • 3
  • 18
  • 26

5 Answers5

6

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)
dipdipdip
  • 2,326
  • 1
  • 21
  • 31
4

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();
}
nstosic
  • 2,584
  • 1
  • 17
  • 21
2

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.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
2

While other answers are correct, there is a built-in way to achieve what you want: onCreate and onUpgrade methods of SqliteOpenHelper.

  1. 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.

Community
  • 1
  • 1
Marius Kaunietis
  • 674
  • 4
  • 17
1

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.

tomyslav
  • 28
  • 4