I have my database class that is extending SQLiteOpenHelper which contains all the steps to create the database instance and executing queries.
DbAdapter.java
Creating database instance to be used throughtout my application------
public static DbAdapter getInstance(Context context) {
if (mInstance == null) {
DB_PATH = context.getFilesDir().getParent() + "/databases/";
mInstance = new IDDLDbAdapter(context);
try {
mInstance.createDataBase();
} catch (Exception e) {
e.printStackTrace();
}
}
return mInstance;
}
Cursor for rawQuery ----------
public synchronized Cursor rawQuery(String sql, String[] args) throws SQLException{
if(db == null || !db.isOpen())
this.open();
return db.rawQuery(sql, args);
}
However, there are times when the database adapter is no longer available although still unaware as it is happening at real time with customers using the application but not on application debug.
I have many classes where I am using this for connecting and executing queries just like that-
protected static DbAdapter dbAdapter;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try
{
dbAdapter = DbAdapter.getInstance(activity.getApplicationContext());
}
catch (ClassCastException e)
{
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
Button btn = (Button) view.findViewById(R.id.btnClick);
btn.setOnClickListener(new OnClickListener()
{
Cursor cur = dbAdapter.rawQuery("select * from blabla WHERE
Activities='"+ activity + "'", null);
cur.moveToFirst();
}
}
And then my work with the Cursor cur then goes on...
Is this code problematic ?
I have three doubts for the problem -
1) This line seems problematic --
dbAdapter = DbAdapter.getInstance(activity.getApplicationContext());
This is because it was advised in some posts to avoid using getApplicationContext()
wherever possible.
2) During application idle time database connector class's object got finalized(having no reference to database).
3) I am getting the database instance onAttach()
. Is it advisable ?
Can someone shed a light on the road of problems to move correctly ?