简体   繁体   中英

Android Studio: NullPointerException: Attempt to invoke virtual method '...' on a null object reference

Hello friends, I have been working on this all night and really don't understand what I am missing. I understand that the problem is in the addWord() method but I don't understand how. I tried removing the checkword() method from the addword() method and I also removed the.trim() from the string declarations for w1 and m1. I did not include the XML becuase of the character limit but i am sure the initializations are fine. Would really appreciate it if you can help a noob out. thank you

The Error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.login_signup_sqlite, PID: 18102
    java.lang.NullPointerException: Attempt to invoke virtual method 'long com.example.login_signup_sqlite.DatabaseHelper.addWord(java.lang.String, java.lang.String)' on a null object reference
        at com.example.login_signup_sqlite.AddWords$1.onClick(AddWords.java:51)
        at android.view.View.performClick(View.java:4780)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

java code for AddWords.class

package com.example.login_signup_sqlite;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddWords extends AppCompatActivity {
    EditText word1,word2,word3,word4,word5,word6,word7,word8,word9,word10,word11,word12,word13,word14,word15;
    EditText meaning1,meaning2,meaning3,meaning4,meaning5,meaning6,meaning7,meaning8,meaning9,meaning10,meaning11,meaning12,meaning13,meaning14,meaning15;
    Button addWordsButton;
    DatabaseHelper db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_words);

        //words initialization
        word1 = findViewById(R.id.word1);word2 = findViewById(R.id.word2); word3 = findViewById(R.id.word3);word4 = findViewById(R.id.word4);word5 = findViewById(R.id.word5);
        word6 = findViewById(R.id.word6);word7 = findViewById(R.id.word7); word8 = findViewById(R.id.word8);word9 = findViewById(R.id.word9);word10 = findViewById(R.id.word10);
        word11 = findViewById(R.id.word11);word12 = findViewById(R.id.word12); word13 = findViewById(R.id.word13);word14 = findViewById(R.id.word14);word15 = findViewById(R.id.word15);
        //Meanings initialization
        meaning1 = findViewById(R.id.meaning1);meaning2 = findViewById(R.id.meaning2);meaning3 = findViewById(R.id.meaning3);meaning4 = findViewById(R.id.meaning4);meaning5 = findViewById(R.id.meaning5);
        meaning6 = findViewById(R.id.meaning6);meaning7 = findViewById(R.id.meaning7);meaning8 = findViewById(R.id.meaning8);meaning9 = findViewById(R.id.meaning9);meaning10 = findViewById(R.id.meaning10);
        meaning11 = findViewById(R.id.meaning11);meaning12 = findViewById(R.id.meaning12);meaning13 = findViewById(R.id.meaning13);meaning14 = findViewById(R.id.meaning14);meaning15 = findViewById(R.id.meaning15);
        //Button
        addWordsButton = findViewById(R.id.addWordsBTN);




        addWordsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //getting the text from the words
                String w1 = word1.getText().toString().trim();String w2 = word2.getText().toString().trim();String w3 = word3.getText().toString().trim();String w4 = word4.getText().toString().trim();String w5 = word5.getText().toString().trim();
                String w6 = word6.getText().toString().trim();String w7 = word7.getText().toString().trim();String w8 = word8.getText().toString().trim();String w9 = word9.getText().toString().trim();String w10 = word10.getText().toString().trim();
                String w11 = word11.getText().toString().trim();String w12 = word12.getText().toString().trim();String w13 = word13.getText().toString().trim();String w14 = word14.getText().toString().trim();String w15 = word15.getText().toString().trim();

                //getting the text from the words
                String m1 = meaning1.getText().toString().trim();String m2 = meaning2.getText().toString().trim();String m3 = meaning3.getText().toString().trim();String m4 = meaning4.getText().toString().trim();String m5 = meaning5.getText().toString().trim();
                String m6 = meaning6.getText().toString().trim();String m7 = meaning7.getText().toString().trim();String m8 = meaning8.getText().toString().trim();String m9 = meaning9.getText().toString().trim();String m10 = meaning10.getText().toString().trim();
                String m11 = meaning11.getText().toString().trim();String m12 = meaning12.getText().toString().trim();String m13 = meaning13.getText().toString().trim();String m14 = meaning14.getText().toString().trim();String m15 = meaning15.getText().toString().trim();


                //adding the words
                db.addWord(w1,m1);
                db.addWord(w2,m2);db.addWord(w3,m3);db.addWord(w4,m4);db.addWord(w5,m5);
                db.addWord(w6,m6);db.addWord(w7,m7);db.addWord(w8,m8);db.addWord(w9,m9);db.addWord(w10,m10);
                db.addWord(w11,m11);db.addWord(w12,m12);db.addWord(w13,m13);db.addWord(w14,m14);
                long val = db.addWord(w15,m15);
                if (val>0){
                    Toast.makeText(AddWords.this,"Congratulations, the words were added to the student's box 1",Toast.LENGTH_SHORT).show();
                    Intent backToInstructorMainScreen = new Intent(AddWords.this,InstructorMainScreen.class);
                    startActivity(backToInstructorMainScreen);
                }


            }
        });


    }

}

Java code for the DatabaseHelper.class

package com.example.login_signup_sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME="register.db";
    //TABLES
    public static final String INSTRUCTORS_TABLE ="registeruser";
    public static final String STUDENTS_TABLE ="registerstudent";
    public static final String WORDS_TABLE = "words";

    //USERS COLUMNS
    public static final String COL_1_USERS="ID";
    public static final String COL_2_USERS ="username";
    public static final String COL_3_USERS ="email";
    public static final String COL_4_USERS ="password";

    //WORDS COLUMNS
    public static final String INDEX_WORDS ="ID";
    public static final String WORD ="word";
    public static final String MEANING ="meaning";
    public static final String BOX_NO ="box_no";
    public static final String LEARNT ="learnt";



    public DatabaseHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null,1);

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("CREATE TABLE registeruser (ID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT,email TEXT, password TEXT)");
        sqLiteDatabase.execSQL("CREATE TABLE registerstudent (ID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT,email TEXT, password TEXT)");
        sqLiteDatabase.execSQL("CREATE TABLE words (ID INTEGER PRIMARY KEY AUTOINCREMENT, word TEXT,meaning TEXT, box_no TEXT,learnt INTEGER )");

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        String query = INSTRUCTORS_TABLE +", "+STUDENTS_TABLE+", "+WORDS_TABLE;
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+ query);
        onCreate(sqLiteDatabase);

    }

    public long addWord(String word, String meaning){
        if(checkword(word)){
            return 0;
        }else{
            String i ="1";

            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            contentValues.put("word",word);
            contentValues.put("meaning",meaning);
            contentValues.put("box_no",i);
            long res = db.insert("words",null,contentValues);
            db.close();
            return res;
        }


    }

    //this function will enter the username and password in to the database
    public long addUser(String user, String password,String email){
        if(checkUser(user,password)){
            return 0;

        }else{

            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            contentValues.put("username",user);
            contentValues.put("email",email);
            contentValues.put("password",password);
            long res = db.insert("registeruser",null,contentValues);
            db.close();
            return res;
        }

    }
    public long addStudent(String user, String password,String email){
        if(checkStudent(user,password)){
            return 0;
        }else{

            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            contentValues.put("username",user);
            contentValues.put("email",email);
            contentValues.put("password",password);


            long res = db.insert("registerstudent",null,contentValues);
            db.close();
            return res;
        }

    }


    public boolean checkword(String word){
        String[] columns = {INDEX_WORDS};
        SQLiteDatabase db = getReadableDatabase();
        String selection = WORD;
        String[] selectionArgs = {word};//this will get the username and passwords from the database
        Cursor cursor = db.query(INSTRUCTORS_TABLE, columns,selection,selectionArgs,null,null, null);
        int count = cursor.getCount();
        cursor.close();
        db.close(); // to close the database

        if(count>0){ // if the data exists
            return true;// then return true
        }else { // if not
            return false;// return false
        }

    }


    //this function will check if the username and password is in the database
    public boolean checkUser(String username, String password){
        String[] columns = {COL_1_USERS};
        SQLiteDatabase db = getReadableDatabase();
        String selection = COL_2_USERS + "=?"+" and "+ COL_4_USERS +"=?";
        String[] selectionArgs = {username,password};//this will get the username and passwords from the database
        Cursor cursor = db.query(INSTRUCTORS_TABLE, columns,selection,selectionArgs,null,null, null); // this will select the whatever there is in the ID, Uername and password columns
        //we can change the null to queries but we do not want to, because we do not need any specific order here we just want to search everything
        int count = cursor.getCount(); // this will get the count of everything
        cursor.close(); //this will finish the query
        db.close(); // to close the database

        if(count>0){ // if the data exists
            return true;// then return true
        }else { // if not
            return false;// return false
        }

    }
    public boolean checkStudent(String username, String password){
        String[] columns = {COL_1_USERS};
        SQLiteDatabase db = getReadableDatabase();
        String selection = COL_2_USERS + "=?"+" and "+ COL_4_USERS +"=?";
        String[] selectionArgs = {username,password};//this will get the username and passwords from the database
        Cursor cursor = db.query(STUDENTS_TABLE, columns,selection,selectionArgs,null,null, null); // this will select the whatever there is in the ID, Uername and password columns
        //we can change the null to queries but we do not want to, because we do not need any specific order here we just want to search everything
        int count = cursor.getCount(); // this will get the count of everything
        cursor.close(); //this will finish the query
        db.close(); // to close the database

        if(count>0){ // if the data exists
            return true;// then return true
        }else { // if not
            return false;// return false
        }

    }

}

The problem isn't in the addWord method, but that db is null, and you can't call a method on null. Adding the line db = new DatabaseHelper(); in AddWords.onCreate might help.

you have created an object of your DatabaseHelper class but you did not initialize that, add this line in onCreate method

db=new DatabaseHelper(this);

after the setContentView

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