JLFerrari
JLFerrari

Reputation: 155

Is it possible to turn a SQLiteDatabase into a Global Variable?

The idea is to use just one connection all over the APP, since it'll be used almost everytime. Is it possible to get the SQLiteDatabase and turn it to a global variable to be used all over the app?

Which way should i follow to make this?

Thx in advance.

Upvotes: 2

Views: 1420

Answers (3)

Plastic Sturgeon
Plastic Sturgeon

Reputation: 12527

The two current answers say the same thing, and they are 100% right, but maybe don't explain the whole thing. In the android framework, the Application class is where you would put any variables and data you want globally accessible. http://developer.android.com/reference/android/app/Application.html

From any activity you can call getApplication() and it will return the application instance you created.

So then you can make the database available by adding a public method to your application.

In the end you'd do something like:

SQLiteDatabase myDatabase = getApplication().getDatabase();

Then in your Application class you would fill out the getDatabase() method.

A slightly better approach might be to create a class that manages the database, and make that class a member of the application. This would let you encapsulate all the open cloase and business with the database in one class. Then you could use methods of the application class to pass back Cursors from queries, etc.

Upvotes: 2

Dan S
Dan S

Reputation: 9189

There are two ways to do this, create a custom Application class or use a Singleton.

Upvotes: 0

Ashterothi
Ashterothi

Reputation: 3282

You could place the connection and access of the DB into the Application class. That would allow you to create a DB connection singleton that would be available throughout your program.

Upvotes: 0

Related Questions