SQlite Database: Unable to find context

妖精的绣舞 提交于 2019-12-05 14:38:46

You should declare your DBHelper as a static instance (singleton) to ensure that only one DBHelper exist at any given time.

 public class DBHelper extends SQLiteOpenHelper { 

    private static DBHelper mInstance = null;

    public static DBHelper getInstance(Context activityContext) {

    // Get the application context from the activityContext to prevent leak
    if (mInstance == null) {
      mInstance = new DBHelper (activityContext.getApplicationContext());
    }
    return mInstance;
  }

  /**
   * Private, use the static method "DBHelper.getInstance(Context)" instead.
   */
  private DBHelper (Context applicationContext) {
    super(applicationContext, DATABASE_NAME, null, DATABASE_VERSION);
  }
}

To open the SQLiteDatabase use:

SQLiteDatabase mDataBase = DBHelper.getInstance(context).getWritableDatabase();

and to close it

mDataBase.close();

Try this

db = new DbHelper(this.getContext());

It should work.

use constructor for this... While calling the DB class pass context as the parameter. like below.

    public class MyDB {

   private Context context;
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public MyDB(Context ctx) 
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }
}

Hope this will help you.

Sahil Mahajan Mj

You are using, DBHelper dbHelper = new DBHelper(this.getApplicationContext());

Instead you should use,

DBHelper dbHelper = new DBHelper(getApplicationContext());

Edit-

Try using

MyDb = getApplicationContext().getWritableDatabase();

instead of

DBHelper dbHelper = new DBHelper(this.getApplicationContext());

MyDb = dbHelper.getWritableDatabase();

Also try removing the finally() block as suggested by this answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!