I am relatively new to Android programming. So please, forgive me for writing or asking anything stupid. I am working on an Android application in which I am using SQLite database to store data. I need to access this database from more Activities and after some research I have concluded that the best way to do so is using an Application class. But this is where my program stops working.
I have my Application class:
import android.app.Application;
public class MyApplication extends Application {
public CONTACT_DB = new CONTACT_DB(this);
}
where CONTACT_DB class is where I have defined my database and has this constructor:
private final Context context;
private DatabaseHelper DBHelper;
public CONTACT_DB(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
Now in my Activity, where I need to access this database
public class Add_contact extends Activity {
CONTACT_DB db;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_contact_layout);
MyApplication appState = ((MyApplication)getApplicationContext());
db = appState.db;
}
}
My program works fine, but when it gets to line
MyApplication appState = ((MyApplication)getApplicationContext());
then it crashes. I tried to use just a simple int instead of my CONTACT_DB class and it still srashes. Any ideas?
Have you declared your custom application class in the manifest?
For example: