I’m using a custom Database class in my code to manage my database and handle transactions. Whenever I instantiate it, I pass the application context to it’s constructor. Reading up on the articles at the Android developer site makes me wonder if I’m doing something that could cause a huge memory leak in my application. Simplified, my code looks like this, first off an activity:
public class MyActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.somelayout);
Database db = new Database(getApplicationContext());
}
}
And my database class (in a seperate file) looks like this:
public class Database
{
Context context;
public Database(Context context)
{
this.context = context;
}
public DatabaseHelper extends SQLiteOpenHelper
{
// Pass the context to the constructor etc etc.
}
}
The code might have bugs, I wrote it quickly in notepad. Anyway, this got me worried that the db object keeps the context when the user navigates away from the activity, thus uneccesarily spending a huge amount of resources. If this is indeed the case, how can I avoid this? Is there a way to destroy and object when it is no longer needed?
The object referenced by
dbis eligible for garbage collection as soon asonCreatefinishes. So there is no problem here.If you made
dborDatabase.contextinto astaticfield, that’s when you should start to worry.