• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps How to start Chronometer using DialogFragment

Chang Broot

Lurker
How to start a Chronometer when a DialogFragment is clicked (its OK button)? I have something like the following, but it gives null object reference error. I want the timer to start only after the user clicks the ok button in the dialogFragment.
Java:
public class A extends AppCompatActivity {
private Chronometer mChronometer;
@Override
   protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
       setContentView(R.layout.activity);
       mChronometer = findViewById(R.id.chronometer);
       mChronometer.setBase(SystemClock.elapsedRealtime());
}
public void startTimer(){
  // This method is start using Fragment.
   mChronometer.start();
}
}
 
Where is your dialogFragment code ?
Code:
public class MyDialog extends AppCompatDialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("A Message")
                .setTitle("Instructions")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        A al = new A();
                        al.startTimer();
                        //al.mChronometer.start();;
                    }
                });
        // Create the AlertDialog object and return it
        return builder.create();
    }
}
 
Code:
                    public void onClick(DialogInterface dialog, int id) {
                        A al = new A();
                        al.startTimer();
                        //al.mChronometer.start();;
                    }
I'm not sure you can directly invoke an activity that way. (A al = new A())

How do you get to the "A" activity? Where is your dialog invoked from?

The approach I would take in this case is to pass the calling activity into the dialog, have the timer invocation in that activity, and call it by referencing the calling activity i.e.
Code:
public class MyDialog extends AppCompatDialogFragment {
    private Activity callingActivity;
    public MyDialog(Activity a) {
        callingActivity = a;
    }

// other code
                    public void onClick(DialogInterface dialog, int id) {
                        callingActivity.startTimer();
                    }

Not sure that would work as written but that's the general approach I would take.
 
I'm not sure you can directly invoke an activity that way. (A al = new A())

Not recommended, and the OP is getting NPE because mChronometer variable was never initialised, as onCreate() method hasn't been called.
 
Back
Top Bottom