Home > Enterprise >  How to call a query when the app is run for the first time in Android Studio
How to call a query when the app is run for the first time in Android Studio

Time:10-20

I'm new to Android Studio and SQLite and wanted to run a query when the app is run for the very first time only, and when the app is run again it wont run the query again.

CodePudding user response:

This will depend upon how you are accessing the database.

The most common way is to utilise the SQLiteOpenHelper class. In which case the onCreate method is called when the database is created. The database only ever being created the once (unless it is deleted e.g. the App uninstalled).

When onCreate is called the database will have been created BUT will not have any components (tables, indexes, views, triggers) other than some system components. Typically this is where the components are created but meets the criteria of your question IF using a class that extends SQLiteOpenHelper. However, unless the query is to store data, it would probably be of little use as there would be no data to query.

However, using a class that extends SQLiteOpenHelper is not the only way in which an SQLite database can be accessed, nor would onCreate be called if you were utilising a pre-existing database copied from the assets folder of the package (e.g. using SQLiteAssetHelper).

In these latter cases, you could test to see if the database actually exists and set a flag/indicator. If it does not and then after opening the database you could then check the indicator and run the query.


Demonstration


Here's a demonstration of two methods.

  • The first using the more typical SQLiteOpenHelper and thus the onCreate method.
  • The second using an indicator.

The first method utilises a class that extends SQLiteOpenHelper called DBHelper :-

class DBHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "thedatabase.db";
    public static final int DATABASE_VERSION = 1;
    private static volatile DBHelper instance;

    private DBHelper(Context context) {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
        this.getWritableDatabase(); //Force database open
    }
    public static DBHelper getInstance(Context context) {
        if (instance==null) {
            instance = new DBHelper(context);
        }
        return instance;
    }


    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        // Run the query here AFTER creating the components
        Log.d("DBHELPER","First run detected");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}
  • Rather than run a query, data is written to the log from within the onCreate method.

The second method utilises the SQLiteDatabase openOrCreateDatabase (i.e. circumventing using the SQLiteOpenHelper). Thus it has to do some of the things that SQLiteOpenHelper conveniently does automatically:-

class OtherDBHelper {
   public static final String DATABASE_NAME = "otherdatabase.db";
   public static final int DATABASE_VERSION = 1;

   private static boolean databaseCreateIndicator = false;
   private static boolean databaseVersionChanged = false;
   private SQLiteDatabase database;
   private static OtherDBHelper instance;

   private OtherDBHelper(Context context) {
       if (!context.getDatabasePath(DATABASE_NAME).exists()) {
           databaseCreateIndicator = true;
           File database_dir = context.getDatabasePath(DATABASE_NAME).getParentFile();
           if (!database_dir.exists()) {
               database_dir.mkdirs();
           }
           // Copy database from assets
       }
       database = SQLiteDatabase.openOrCreateDatabase(context.getDatabasePath(DATABASE_NAME),null);
       //* Database now open */
       // If utilising Version number check and set the version number
       // If not copying pre-existing database create components (tables etc)
       if (databaseCreateIndicator) {
           //<<<<<<<<<< Query here >>>>>>>>>>
           Log.d("OTHERDBHELPER","First run detected");
       }
   }

   public SQLiteDatabase getSQLiteDatabase() {
       return database;
   }

   public static OtherDBHelper getInstance(Context context) {
       if (instance==null) {
           instance = new OtherDBHelper(context);
       }
       return instance;
   }
}
  • again the instead of running a query outputting to the log is used.

To test both in unison then some activity code:-

public class MainActivity extends AppCompatActivity {

    DBHelper dbHelper;
    OtherDBHelper otherDBHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d("PREDBMSG","Just prior to getting the databases.");
        dbHelper = DBHelper.getInstance(this);
        otherDBHelper = OtherDBHelper.getInstance(this);
        Log.d("POSTDBMSG","Just after getting the databases.");
    }
} 

Results

When run for the first time then the log includes:-

2022-10-20 07:09:27.633 D/PREDBMSG: Just prior to getting the databases.
2022-10-20 07:09:27.663 D/DBHELPER: First run detected
2022-10-20 07:09:27.697 D/OTHERDBHELPER: First run detected
2022-10-20 07:09:27.697 D/POSTDBMSG: Just after getting the databases.

When run again :-

2022-10-20 07:10:41.258 D/PREDBMSG: Just prior to getting the databases.
2022-10-20 07:10:41.266 D/POSTDBMSG: Just after getting the databases.
  • Related