1

I'm having trouble opening my database inside fragment java file. I've used this answer which pretty much similar to my problem, though It's not working

public class fragmentBmi extends Fragment {
    DatabaseHandler db = new DatabaseHandler(getActivity()); //DATABASE

    public fragmentBmi() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_bmi, container, false);
        TextView bmi = (TextView) v.findViewById(R.id.BMI);
        if(db.checkDetails()){ // Check if db is empty, if not print on screen bmi,bmr,rmr. if does print message.
            Details d = db.getDetails();
            bmi.setText(String.format("BMI: %.2f", d.getBmi()));
        }
        else{
            bmi.setText(R.string.noneInfo);
        }
        return v;
    }


}

error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference

I've also tried Context variable, also giving me the same error. Is there any solution to open database inside fragment java file?

Community
  • 1
  • 1
Yotam Dahan
  • 689
  • 1
  • 9
  • 33

3 Answers3

3

You cannot use the method getActivity() whit an instance variable because at that time, the Activity has not been created yet and the method returns null. To fix this issue, you have to move this line DatabaseHandler db = new DatabaseHandler(getActivity()); to onActivityCreated method:

@Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        DatabaseHandler db = new DatabaseHandler(getActivity());
    }
Luiz Fernando Salvaterra
  • 4,192
  • 2
  • 24
  • 42
2

The error say that your db object is null when you try to use it.

Try to change

DatabaseHandler db = new DatabaseHandler(getActivity()); //DATABASE

For

DatabaseHandler db;

And in onCreateView, add this line after View v =...

db = new DatabaseHandler(getContext());
1

Your DB is initialized in a variable initialization block, which means it's being executed prior to your constructor (more here: Java - Method executed prior to Default Constructor). getActivity() returns null at this point in a Fragment's lifecycle (more about fragment lifecycle here: https://developer.android.com/guide/components/fragments.html).

You need to initiate the db after the Fragment itself was initialized.

Community
  • 1
  • 1
Vaiden
  • 15,728
  • 7
  • 61
  • 91