简体   繁体   中英

Sqlite Database context android

I have created a Database class file to use SQLite db in Android app. Since I am beginner and I am having problem understanding what should i put in context when I instantiate Database class to another class The database code is as follows:

public Database(@Nullable Context context) {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
        database=getWritableDatabase();

How can I instantiate it to an another class. When doing instantiation Database db = new Database(); what should be put under context

If you instantiate it to RandomActivity class, you should put:

Database db = new Database(this);

or

Database db = new Database(RandomActivity.this);

Use the application context, which will ensure that you don't accidentally leak an Activity's context. See this article for more information: https://android-developers.googleblog.com/2009/01/avoiding-memory-leaks.html

Make your SqliteDB class a singleton as -

private static Database sInstance;

public static synchronized Database getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new Database(context.getApplicationContext());
        }
        return sInstance;
    }

    private ChatSQliteDB(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        Log.v("SQLTVer", "ver "+DATABASE_VERSION);
    }

Android docs on Context.

Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

So when you create a View you need to pass Context to it, but why? What your View will loose if it is not passed Context . Your View will loose the ability to access system resources. For eg suppose there is a Drawable that is to be set as background of your View , without context your View cannot access that Drawable .

public class MyView extends View {

public MyView(Context context) {
    super(context);
    Drawable d = context.getDrawable(R.drawable.ic_launcher_background);
    getDrawable(R.drawable.ic_launcher_background);  //without context IDE will give error cannot resolve getDrawable(int).
    }
}

So when you create a View you pass Activity Context to it, because your View is tied to your Activity . It should not outlive Activity .

MyView myView = new MyView(this);

You can use this as Context because your Activity extends from ContextThemeWrapper , which extends from ContextWrapper which extends from Context .

Now if you want to create a Database , and if your app has multiple Activities which need access to DB , then your DB should outlive the Activity which created DB instance, so in this case you should use Application Context to create DB .

Even if you have a single Activity app, then also your DB should outlive your Activity , because your Activity will be restarted on every Rotation . But your Application is not. So here also you should pass Application Context .

As a general rule, think of Context as the lifetime for your newly created object, For DB you generally want Application lifetime.

To make it clear consider an example: Your app starts with Activity A , which download large Bitmap form network, creates a DB instance on its Context and saves Bitmap to the DB . After that your Activity A starts Activity B and A is finished. Now your Activity A is no longer required and should be garbage collected. But your DB is still alive on its Context so A will not be gc'ed and will result in Memory Leak.

Finally as Naresh as already pointed in his answer you should make your DB a Singleton .

First you declare context globally in your Activity:

Context context = this

then make a method/function in your nonactivity class that require a parameter context.

class YOUR_CLASS{

    public void YOUR_METHOD(Context context){       //method with require context parameter

         Database db = new Database(context);  //supplied the context from your activity
    }
}

then call YOUR_METHOD from YOUR_CLASS in your Activity with supplied context.

new YOUR_CLASS().YOUR_METHOD(context); //supply context on your method

I have created a new Class

import android.app.Application;
import android.content.Context;

public class MySuperApplication extends Application {
    private static Application instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static Context getContext() {
        return instance.getApplicationContext();
    }
}

It will generate the context automatically. So wherever its asked we can write Database db= new Database(MySuperApplication.getContext());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM