Reputation: 39
How can i open a database in a class that is not a subclass of Activity
?
In a subclass of Activity
, i can use openOrCreateDatabase()
but can i open a database in a different class?
I tried making the database instance a static one and open it in an Activity
and get the static instance in the other class, but it throws an exception stating the database is closed.
Upvotes: 0
Views: 2270
Reputation: 3573
Check out this tutorial.
I went through it and it's a really good tutorial on how to use SQLite in Android.
Essentially you need to create a database helper class that will do the table creation. Then you can use this helper class in your Activity
to create your database and or tables.
Upvotes: 2
Reputation: 233
It's common practice to use a SQLite Database Adapter and sometimes a helper class that is separate from the activity that is utilizing the database. Here is a link to a example that uses the code. THe vogella tutorial is also good but the use of a ContentProvider makes it a bit tough to understand what things need to be in there for a SQLite DB only.
Essentially, the helper class is responsible for creating, updating and deleting the DB while the adapter class handles the methods for changing values, deleting rows, and actually calling the helper to open the database.
Upvotes: 1