NullPointerException on getReadableDatabase()

前端 未结 5 1130
自闭症患者
自闭症患者 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:07

    You have not passed proper context of your activity that is why its throwing nullpointer error.

    Just change your method as below.

    public boolean usernameChk(String usrname){
    
        String usrnmQuery = "SELECT  * FROM " + TABLE_ACCOUNTS  + " WHERE username = '" + usrname + "'";
        SQLiteDatabase db = this.getReadableDatabase();
    

    Declare one common Context in your DatabaseHelper and assign the value of constructor in your while creating instance of your helper class as below:

    public Context m_context;
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        m_context = context;
    }
    

提交回复
热议问题