Object null, I don’t understand why

Asked

Viewed 76 times

-3

I have this myDB object which is an object of the Databasehelper class, but when I try to invoke a method of that class it says that that object is null.

Class where this object:

    public class Caldroid_fragment extends Fragment{

private DataBaseHelper myDB;
private CaldroidFragment caldroidFragment;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.caldroid_calendar, container, false);
    return rootView;
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {



    myDB = new DataBaseHelper(getActivity());




    ColorDrawable blue = new ColorDrawable(Color.BLUE);


    caldroidFragment = new CaldroidFragment();



    Bundle args = new Bundle();
    args.putInt(CaldroidFragment.START_DAY_OF_WEEK, CaldroidFragment.MONDAY);
    caldroidFragment.setArguments(args);
    java.util.Calendar cal = Calendar.getInstance();
    args.putInt(CaldroidFragment.MONTH, cal.get(Calendar.MONTH) + 1);
    args.putInt(CaldroidFragment.YEAR, cal.get(Calendar.YEAR));
    caldroidFragment.setArguments(args);
    FragmentTransaction t = getChildFragmentManager().beginTransaction();
    t.replace(R.id.caldroidCal, caldroidFragment);
    t.commit();
}

public void addToCalendar(){
    ColorDrawable blue = new ColorDrawable(Color.BLUE);
    for(int i=0;i==myDB.getLastId();i++){
        String dt = myDB.getDates(i);
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MM-yyyy");
        Date teste = null;
        try {
            teste = sdf.parse(dt);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        caldroidFragment.setBackgroundDrawableForDate(blue,teste);
    }
}

}

Class where I am trying to import methods:

     public class DataBaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "Exames.db";
public static final String TABLE_NAME = "Exames_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "DISCIPLINA";
public static final String COL_3 = "SALA";
public static final String COL_4 = "DIA";
public static final String COL_5 = "HORA";




public DataBaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL(" create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT , DISCIPLINA TEXT , SALA TEXT,DIA TEXT, HORA TEXT)" );
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(sqLiteDatabase);

}

public boolean insertData(String disciplina,String sala,String dia,String hora){
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COL_2,disciplina);
    values.put(COL_3,sala);
    values.put(COL_4,dia);
    values.put(COL_5,hora);
    long result = sqLiteDatabase.insert(TABLE_NAME,null,values);
        if(result==-1){
            return false;
        }else
            return true;


}

public int getLastId() {
    SQLiteDatabase sqLiteDatabase = getWritableDatabase();
    String query = "SELECT MAX(id) AS max_id FROM " + TABLE_NAME;
    Cursor cursor = sqLiteDatabase.rawQuery(query, null);
    int id = 0;
    if (cursor.moveToFirst())
    {
        do
        {
            id = cursor.getInt(0);
        } while(cursor.moveToNext());
    }
    return id;

}

public String getDates(int id){
    SQLiteDatabase db = this.getWritableDatabase();
    String date = "";
    String last_query = "SELECT " + COL_4  + " FROM " + TABLE_NAME  + " WHERE " + COL_1 + " = '" + id + "'";
    Cursor c = db.rawQuery(last_query, null);
    if (c != null && c.moveToFirst())
    {
        date = c.getString(0); // Return Value
    }
    db.close();
    return date;
}

}

Class where the button is cleaved:

    public class Tab1tests extends Fragment {


private ViewPager mViewPager;
private TimePickerDialog.OnTimeSetListener hourSetListener;
private DatePickerDialog.OnDateSetListener dateSetListener;
private Button date_button;
private Button hora_button;
private TextView date_text;
private TextView hora_text;
private EditText sala_text;
private Button add_test;
private String dt;
private DataBaseHelper myDB;
private Caldroid_fragment myCF;
public static String hora2;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.tab1tests, container, false);

    add_test = (Button) rootView.findViewById(R.id.add_test);
    date_button = (Button) rootView.findViewById(R.id.date_button);
    hora_text = (TextView) rootView.findViewById(R.id.hora_text);
    hora_button = (Button) rootView.findViewById(R.id.hora_button);
    date_text = (TextView) rootView.findViewById(R.id.date_text);
    sala_text = (EditText) rootView.findViewById(R.id.sala_text);
    myCF = new Caldroid_fragment();
    myDB = new DataBaseHelper(getContext());


            date_button.setOnClickListener(
                    new View.OnClickListener() {
                        public void onClick(View v) {
                            Calendar cal = Calendar.getInstance();
                            int year = cal.get(Calendar.YEAR);
                            int month = cal.get(Calendar.MONTH);
                            int day = cal.get(Calendar.DAY_OF_MONTH);
                            DatePickerDialog date_dialog = new DatePickerDialog(
                                    getActivity(),
                                    android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                                    dateSetListener,
                                    year, month, day);
                            date_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                            date_dialog.show();


                        }

                        ;
                    }

            );

    dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month = month + 1;
            date_button.setVisibility(View.GONE);
            date_text = (TextView) rootView.findViewById(R.id.date_text);
            date_text.setVisibility(View.VISIBLE);
            dt = day + "-" + month + "-" + year;
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            try {
                sdf.parse(dt);
                date_text.setText(dt);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
    };




    hora_button = (Button) rootView.findViewById(R.id.hora_button);

    hora_button.setOnClickListener(
            new Button.OnClickListener() {
                public void onClick(View v) {

                    Calendar cal = Calendar.getInstance();
                    int hora = cal.get(Calendar.HOUR);
                    int minutos = cal.get(Calendar.MINUTE);
                    TimePickerDialog mTimePicker = new TimePickerDialog(getActivity(), TimePickerDialog.THEME_HOLO_LIGHT, hourSetListener, hora, minutos, true);
                    mTimePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    mTimePicker.show();
                }
            }
    );

    hourSetListener = new TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker timePicker, int hora, int minutos) {
            hora_button.setVisibility(View.INVISIBLE);
            hora_text.setVisibility(View.VISIBLE);
            hora2 = (hora + ":" + minutos);
            hora_text.setText(hora2);
        }
    };

    hora_text.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Calendar cal = Calendar.getInstance();
            int hora = cal.get(Calendar.HOUR);
            int minutos = cal.get(Calendar.MINUTE);
            TimePickerDialog mTimePicker = new TimePickerDialog(getActivity(),TimePickerDialog.THEME_HOLO_LIGHT,hourSetListener,hora,minutos,true);
            mTimePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            mTimePicker.show();
        }

    });

    date_text.setOnClickListener(new View.OnClickListener(){


        @Override
        public void onClick(View v){
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);
            int day = cal.get(Calendar.DAY_OF_MONTH);
            DatePickerDialog date_dialog = new DatePickerDialog(
                    getActivity(),
                    android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                    dateSetListener,
                    year, month, day);
            date_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            date_dialog.show();
        }
    });

    addData();
    return rootView;
}



public void addData(){
    add_test.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            boolean isInserted = myDB.insertData("Portugues", sala_text.getText().toString(), dt, hora2);
                if (isInserted){
                    Toast.makeText(getContext(),"Teste inserido ao calendario",Toast.LENGTH_LONG).show();
                    date_button.setVisibility(View.VISIBLE);
                    hora_button.setVisibility(View.VISIBLE);
                    date_text.setVisibility(View.INVISIBLE);
                    sala_text.setText("");
                }
                else{
                    Toast.makeText(getContext(),"Preencha todos os espaços",Toast.LENGTH_LONG).show();
                }
            myCF.addToCalendar();
        }
        });

    }

}

Logcat error:

     Process: com.pedrogouveia.averagemaker, PID: 24860
                                                                           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
  • 3

    java and android is not my area not, but at what moment exactly occurs the error ? so I saw the object is only instantiated in the event 'onviewcreated'. the event is being triggered ?

  • Now that’s okay, thank you very much for your time.It happens when I click the button, that is when the addToCalendar method is called, I think yes this one.

  • @Pedrogouveia You need to ensure that the event onViewCreated is being fired.

  • Does not start automatically ?

  • How can I guarantee it?

  • Debugging the code, putting some message there to check...

  • Is being executed

  • Is it possible to show the exact line error?

  • place the button click code as well as where the addToCalendar method is called

  • Thanks for your time

  • Put the complete error caught in the logcat. (where this red and this written "null", do not need to copy the rest).

  • OK I’ll post it now

Show 7 more comments

1 answer

0

Try to replace this guy of yours:

myDB = new DataBaseHelper(getContext());

For:

myDB = new DataBaseHelper(rootView.getContext());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.