NullPointerException on getReadableDatabase()

前端 未结 5 1084
自闭症患者
自闭症患者 2021-01-17 04:49

I have this method in a class (non-activity) -

public boolean usernameChk(String usrname) {

    String usrnmQuery = \"SELECT * FROM \" + TABLE_ACCOUNTS + \"         


        
5条回答
  •  一向
    一向 (楼主)
    2021-01-17 05:03

    As your class which is not an Activity this.getReadableDatabase(); is firing NullPointerException as it is not getting context to open database.

    Use context to open database. try with following :

    DatabaseHandler dbz = new DatabaseHandler(Activity.this);
    
    public Context context;
    
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // assigning context Change your constructor
        this.context = context;
    }
    
    // Open database using context object
    SQLiteDatabase db = this.getReadableDatabase();
    

提交回复
热议问题