-1

I have a database that gets created when application starts. It is intended to download a file and create the database from the file. The problem is that it downloads the file and create the database every time I reopen the app. The MainActivity checks for the existance of the database using this snippet

dbHelper = new DatabaseHelper(this);
    if(!dbHelper.checkDataBase()) {
        android.os.Debug.waitForDebugger();
        dlPortTask = new DownloadTask(MainActivity.this);
        dlPortTask.execute();
    }

so the problem is that when I reopen the main activity the database gets created all over again. Because I'm creating a new instance every time activity main opens. then I check for the existence of database. how can I check for database first and then if doesn't exist created it. how can I get or check if there's an instance of an existing database. my database constructor and checkDatabase method

public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        DB_PATH = context.getDatabasePath(DB_NAME).getPath();
        this.context = context;
    }
public boolean checkDataBase() {
        File DbFile = new File(DB_PATH + DB_NAME);
        String databasePath = context.getDatabasePath(DB_NAME).getPath();
        return DbFile.exists();
    }

again I can call checkDatabase(), but only after instantiating the database in mainactivity. how can I check before creating a new instance. I guess this is more a question of software design principles... any help

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
miatech
  • 2,150
  • 8
  • 41
  • 78
  • 2
    Your `checkDataBase()` method is a little off. You just need to do `context.getDatabasePath(DB_NAME).exists()`, and you can do that at any time. You don't necessarily need to do that in a `DatabaseHelper` instance, but merely instantiating that does not create a database. That won't happen until you actually use it for something – e.g., a query, insert, etc. – and only if it doesn't already exist. – Mike M. Apr 13 '19 at 19:48

1 Answers1

0

here's the proper code for checking existance of database

if(!getDatabasePath(DatabaseHelper.DB_NAME).exists()) {
    //then create databse
  }

where DB_NAME is the name of the database and DatabaseHelper is the database class

miatech
  • 2,150
  • 8
  • 41
  • 78