Home > Net >  Getting null pointer exception while clicking on the button in android studio
Getting null pointer exception while clicking on the button in android studio

Time:02-10

I have made the database and taking the values from checkboxes to the database. But when the activity open the app crashes, stating the null pointer exception.

I have provided the code where the error is coming from and the error message from the logcat Anyone have the answer for it. I do not want to redo the codes now please suggest the edits in this.

The code:

   public void statusCheck(){
    savebtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sqLiteDatabase = feedDB.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            if(morning.isChecked()){
                contentValues.put(COLUMN_FEED_1,"Feeding in morning");
            }
            if(lunch.isChecked()){
                contentValues.put(COLUMN_FEED_2,"Feeding on Lunch time");
            }
            if(evening.isChecked()){
                contentValues.put(COLUMN_FEED_3,"Feeding in evening");
            }
            if(dinner.isChecked()){
                contentValues.put(COLUMN_FEED_4,"Feeding in dinner");
            }

            Long rec = sqLiteDatabase.insert("Feed",null,contentValues);

            if(rec != null){

                Toast.makeText(Feedone.this, "Data is saved", Toast.LENGTH_SHORT).show();
            }
        }
    });
}

The error from Logcat:

          Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void 
          android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null 
          object reference
         at com.kidcave.pediacare.Feedone.statusCheck(Feedone.java:59)

CodePudding user response:

You should call this function after. Also check did you initialized it or not before on create.

 Button saveButton;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bmet_card);
        saveButton = findViewById(R.id.save_button);
        //here you can call the function

Hope by initializing after setContentView and calling it from onCreate after initializing view. It will be solved.

Also check are you inflating the right layout or not.

  •  Tags:  
  • Related