开发者

problem in understanding how to use database SQLite

I have an app where I store some data in a SQLIte database. And what I'm trying to do is to get my DB opened only once at the start of my app and then use the same instance of my DB.

The idea is not to open my DB in every activity I need it.

One of the solutions I got was this-create a class that extends Application and then open the DB there:

This is how the code looks like:

public class MyApplication extends Application{

private static DBAdapter db;

public void onCreate()
{

    db=new DBAdapter(getApplicationContext());
    db.createDatabase();
    db.openDataBase();
}

public static DBAdapter getDatabaseAdapter()
{
    return db;
}

}

So in every activity of my app where I need to connect with my DB I do something like:

MyApplication myApplication = (MyApplication) this.getApplication();
DBAdapter db= myApplication.getDatabaseAdapter();

But I'm not very sure if my DB gets opened only at the beginning of my app...or it ge开发者_StackOverflowts opened everytime I do this:

  MyApplication myApplication = (MyApplication) this.getApplication();

?

Or if anyone has a better solution please tell me:).Thank u


It will be opened only once because you are calling it in onCreate method of Application class which will be called when the application is starting, before any other application objects have been created. You can look at one of my project here is link.

Hope this help.

EDIT: About Application Class : Android will automatically create an instance of that class and make it available for your entire application. You can access it from any context using the Context.getApplicationContext(). So there will be only one instance of Application which will be shared.


An alternative to your approach can be making one SingleTon Class where you can keep the reference to your open dbconnection so that it could be reused.

Since for any android application there's only single instance for applcation class spread across all the activities so your db gets open only at the start of android application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜