NullPointerException on getReadableDatabase()

前端 未结 5 1085
自闭症患者
自闭症患者 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 04:56

    The Context you pass to your DatabaseHandler constructor is null.

    That's the explanation for the NPE in getDatabaseLocked(). To get help fixing that, post code where you initialize the context.

    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2021-01-17 05:10

    I was getting the same error since 3 days. But it is solved now. I created a new object of the database whenever i want to connect to the database. If i have 10 functions in database, i will call them with 10 different objects hence not giving me the error

    0 讨论(0)
  • 2021-01-17 05:17

    According to your code the context is not defined.

    use this instead of context when creating a new instance of your helper

    DatabaseHandler dbz = new DatabaseHandler(this);
    boolean z = dbz.usernameChk(username.getText().toString());
    
    0 讨论(0)
提交回复
热议问题