Reputation: 19
Accessing the SQlite DB from activity works fine eg.
public class MainActivity extends Activity {
DatabaseHelper db;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new DatabaseHelper(getApplicationContext());
// Creating tags
Tag tag1 = new Tag("Shopping");
Tag tag2 = new Tag("Important");
Tag tag3 = new Tag("Watchlist");
Tag tag4 = new Tag("Androidhive");
// Inserting tags in db
long tag1_id = db.createTag(tag1);
long tag2_id = db.createTag(tag2);
long tag3_id = db.createTag(tag3);
long tag4_id = db.createTag(tag4);
Log.d("Tag Count", "Tag Count: " + db.getAllTags().size());
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
but as soon as I take the DB code in Activity and call this in Application Constructor, I get null pointer. eg
public class MainClass extends Application {
// Database Helper
private DatabaseHelper db;
private static final String LOG = MainClass.class.getName();
public MainClass() {
Log.d(LOG, "MainClass Init");
db = new DatabaseHelper(getApplicationContext());
What am I missing ?
Upvotes: 0
Views: 41
Reputation: 152827
Application classes don't need an explicit constructor.
At object instantiation phase when the constructor is called, the Application
is not set up as a Context
yet. getApplicationContext()
won't work.
You can use the Application
as a Context
only in onCreate()
or later.
Upvotes: 3