0

Im working on android studio and I am using fragments so I've added an OnClick listener to a button in the fragment but when I click the button the app crashes and gives the error attempt to invoke virtual method. I am creating a SQLite database where the button is used to add data to the database.

Error

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.streetsafe, PID: 10345
    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.streetsafe.DatabaseHelper.insertData(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
        at com.example.streetsafe.ui.report.ReportFragment.onClick(ReportFragment.java:57)
        at android.view.View.performClick(View.java:7448)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
        at android.view.View.performClickInternal(View.java:7425)
        at android.view.View.access$3600(View.java:810)
        at android.view.View$PerformClick.run(View.java:28305)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

ReportFragment

public class ReportFragment extends Fragment implements View.OnClickListener {

EditText editLocation,editType,editDescription,editDate,editTime,editRating;
Button btnAdd;
    private ReportViewModel reportViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        reportViewModel =
                new ViewModelProvider(this).get(ReportViewModel.class);
        View root = inflater.inflate(R.layout.fragment_report, container, false);

        editLocation = (EditText)root.findViewById(R.id.editText_location);
        editType = (EditText)root.findViewById(R.id.editText_type);
        editDescription = (EditText)root.findViewById(R.id.editText_description);
        editDate = (EditText)root.findViewById(R.id.editText_date);
        editTime = (EditText)root.findViewById(R.id.editText_time);
        editRating = (EditText)root.findViewById(R.id.editText_rating);
        btnAdd = (Button)root.findViewById(R.id.button_add);

        btnAdd.setOnClickListener(this);

        return root;
    }

OnClick

@Override
        public void onClick(View v){
            boolean isInserted = MainActivity.DB_CRIME.insertData(editLocation.getText().toString(),
                    editType.getText().toString(),
                    editDescription.getText().toString(),
                    editDate.getText().toString(),
                    editTime.getText().toString(),
                    editRating.getText().toString());
            if(isInserted ==true)
                Toast.makeText(getActivity(), "Data Inserted",Toast.LENGTH_LONG).show();
            else
                Toast.makeText(getActivity(), "Data Inserted",Toast.LENGTH_LONG).show();
        }
    
    }

Main Actvitiy

public class MainActivity extends AppCompatActivity {
    private static DatabaseHelper myDB;
    public static final DatabaseHelper DB_CRIME = myDB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_report)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);


        FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
        fragmentTransaction.commit();

        myDB = new DatabaseHelper(this);

    }

}

Database helper class

public class DatabaseHelper extends SQLiteOpenHelper {
    //Assigning variables for database
    public static final String DATABASE_NAME = "crimes.db";
    public static final String TABLE_NAME = "crimes_table";
    public static final String ID = "ID";
    public static final String LOCATION = "LOCATION";
    public static final String TYPE = "TYPE";
    public static final String DESCRIPTION = "DESCRIPTION";
    public static final String DATE = "DATE";
    public static final String TIME = "TIME";
    public static final String RATING = "RATING";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
        SQLiteDatabase db = this.getWritableDatabase();
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,LOCATION TEXT,TYPE TEXT,DESCRIPTION TEXT,DATE TEXT,TIME TEXT,RATING TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
        onCreate(db);

    }

    public boolean insertData(String location,String type,String description,String date,String time,String rating){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(LOCATION,location);
        contentValues.put(TYPE,type);
        contentValues.put(DESCRIPTION,description);
        contentValues.put(DATE,date);
        contentValues.put(TIME,time);
        contentValues.put(RATING,rating);
        long result = db.insert(TABLE_NAME,null,contentValues);
        if(result == -1)
            return false;
        else
            return true;
    }
}
  • `Attempt to invoke virtual method 'boolean com.example.streetsafe.DatabaseHelper.insertData...on a null object reference` – a_local_nobody Jan 17 '21 at 19:27
  • user2525009 I suggest to put some breakpoints in onclick method and run in debug mode. on each line check if which line has the null value. I also suggest you to add your complete error log to answer so others can see better what is wrong and may help you my friend – Reza Jan 17 '21 at 19:35
  • `MainActivity.DB_CRIME.insertData()` This is whats causing the problem. Can you share your `Activity` class file as well. Thank you! – Karan Dhillon Jan 17 '21 at 20:40
  • I have just shared the main activity class – user2525009 Jan 17 '21 at 21:20
  • I've managed to get it working when i move this line `DB_CRIME = new DatabaseHelper(getActivity());` from the main activity to the report fragment but if i wanted to keep it in the main activity how would i call that line from the fragment – user2525009 Jan 17 '21 at 21:38

0 Answers0