Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Android – try with resources just for creating database tables

In Android I have this part of code:

   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

        if(!prefs.getBoolean("firstTime", false)) {
          
            new DatabaseHelper(this);
        } }

Lint is now saying 'DatabaseHelper' used without 'try'-with-resources statement

In DatabaseHelper class I have this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 2);
}

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NAME + "blabla");
    }

So why do I need try with resources? Is it really needed here and how to do it in my case?

I tried something like:

try (DatabaseHelper myDb = new DatabaseHelper(this)){

} catch(IOException e) {

}

But I don’t know what to put inside try statement as it is just creating the database tables and nothing else.

Strange is, if I define outside of onCreate DatabaseHelper myDb; and then inside onCreate I will have:

myDb = new DatabaseHelper(this);

then it is not complaining.

Why should I assign it to myDb variable, why it is complaining when I use the same without variable as new DatabaseHelper(this) ?

>Solution :

Is it really needed here…?

Yes, insofar as SQLiteOpenHelper extends AutoCloseable, and you seem to be hitting a Lint complaint about not closing it.

But I don’t know what to put inside try statement as it is just creating the database tables and nothing else.

First, it is not creating database tables. That will not occur until you do something with the DatabaseHelper, such as call getWriteableDatabase().

Second, an AutoCloseable will have a close() method that satisfies the concern.

If your objective purely is to get rid of the Lint complaint, use:

try (DatabaseHelper myDb = new DatabaseHelper(this)){
  myDb.close();
} catch(IOException e) {

}

You will need to do something else beyond close(), such as getReadableDatabase(), to get the tables to be created.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading