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:
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)
?
CodePudding user response:
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.