Search code examples
javaandroidsqliteandroid-studiosqliteopenhelper

android studio :Attempt to invoke virtual method on a null object reference


can someone help me? whenever i click on the dialoginterface.onclicklistener button the app just crashes can anyone check for me my codes . ALso when i want the same dialoginterface button to retrieve the inserted data from database to be viewed as a list view ill provide with database and page codes

public class mainscreen extends AppCompatActivity {
    private static final String TAG = "ListDataActivity";
    ImageButton add;
    DatabaseHelper db;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainscreen);

        listView = (ListView)findViewById(R.id.listview);

        add = (ImageButton) findViewById(R.id.addbtn);
        //populateListView();

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(mainscreen.this);
                View mView = getLayoutInflater().inflate(R.layout.promptexercise,null);
                final EditText addexerText = (EditText)mView.findViewById(R.id.editText2);
                Button cancel = (Button) mView.findViewById(R.id.button4);
                Button ok = (Button) mView.findViewById(R.id.button3);
                ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String newEntry = addexerText.getText().toString();
                        if (addexerText.length() != 0) {
                            AddExerData(newEntry);
                            addexerText.setText("");
                        }else{
                            toastMessage("You must enter an exercise name in the field!");
                        }
                        Toast.makeText(mainscreen.this, newEntry, Toast.LENGTH_SHORT).show();

                    }
                });



                builder.setView(mView);
                AlertDialog dialog = builder.create();
                dialog.show();
                dialog.create();




            }
        });




        }
    //----- method to add data into database
    public void AddExerData(String newEntry){
        boolean insertData = db.addexerData(newEntry);
        if(insertData){
            toastMessage("Data Successfully Inserted");
        }else{
            toastMessage("Something went wrong");
        }

    }


   // private void populateListView(){
       // Log.d(TAG,"populateListView:Displaying data in the ListView");
        //get the data and append to a list
       // Cursor data = db.getData();
      //  //ArrayList<String>listData = new ArrayList<>();
       // while(data.moveToNext()){
            //get the value from the database from col 1 -id
            //then add it into arraylist
       // listData.add(data.getString(1));
       // }
      //  ListAdapter adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,listData);
       // listView.setAdapter(adapter);
   // }


    //method to make the msg pop
    private void toastMessage(String message){
        Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
    }

}

 LOGCAT
 
 Process: com.example.hibatulhadi.trackerapp2, PID: 643
    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.hibatulhadi.trackerapp2.DatabaseHelper.addexerData(java.lang.String)' on a null object reference
        at com.example.hibatulhadi.trackerapp2.mainscreen.AddExerData(mainscreen.java:79)
        at com.example.hibatulhadi.trackerapp2.mainscreen$1$1.onClick(mainscreen.java:50)
        at android.view.View.performClick(View.java:6294)
        at android.view.View$PerformClick.run(View.java:24770)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)


Solution

  • In you button's clickListener you are Inflating a second layout to show up in the dialogbox which seems to have an edit text in it which is being registered after the loading dialog creation which can be the simple cause here as you are using findviewbyid generically you should specify the inflated view's name and its findViewbyid! simply put your clicklistener code should look like this!

           add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LayoutInflater layoutInflater = LayoutInflater.from(mainscreen.this);
                    View promptView = layoutInflater.inflate(R.layout.promptexercise, null);
                    AlertDialog.Builder alertdialog = new AlertDialog.Builder(mainscreen.this);
                    alertdialog.setView(promptView);
    // here use findviewby id from your inflated view like this!
                    final EditText e1 = (EditText) promptView.findViewById(R.id.editText);
                    alertdialog.setCancelable(false)
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
    
                                        String newEntry9 = e1.getText().toString();
                                        if (e1.length() != 0) {
                                            AddExerData(newEntry9);
                                            e1.setText("");
                                        } else {
                                            toastMessage("You must enter an exercise name in the field!");
                                        }
                                        Toast.makeText(mainscreen.this), newEntry9, Toast.LENGTH_SHORT).show();
    
    
                                    }
    
                            })
                            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            });
                    alertdialog.create();
                    alertdialog.show();
    
                }
            });
    

    2nd Missing thing

    In your write data method the db is not initialised ! that is the error causing the crash! you have to initialise it before using it!

         //----- method to add data into database
            public void AddExerData(String newEntry){
    // this db variable you are using! is not initialised!
                boolean insertData = db.addexerData(newEntry);
                if(insertData){
                    toastMessage("Data Successfully Inserted");
                }else{
                    toastMessage("Something went wrong");
                }
    
            }
    

    Maybe this could SOLVE it like this if this is SQLITE database

    //----- SOLUTION method to add data into database
        public void AddExerData(String newEntry){
    //      if you have a field (class level variable)  SqliteDatabase db;
            db = new YourDBHelperClass().getWriteabledatabase();
            boolean insertData = db.addexerData(newEntry);
            if(insertData){
                toastMessage("Data Successfully Inserted");
            }else{
                toastMessage("Something went wrong");
            }
    
        }