Обращаюсь из класса Timer.java к MainActivity
public Timer(long millisInFuture, final long countDownInterval, final ITimerCallback callback, final Context context) {
currentTimer = new CountDownTimer(millisInFuture, countDownInterval) {
@Override
public void onTick(long millisUntilFinished) {
long time = millisUntilFinished / 1000;
callback.ontTimerNewValue(String.valueOf(time));
}
@Override
public void onFinish() {
callback.ontTimerNewValue("ОК");
MainActivity mActivity= new MainActivity();
mActivity.soobshenie(); // тут обращение
}
}.start();
}
Сама функция в MainActivity
public void soobshenie()
{
builder2 = new AlertDialog.Builder(MainActivity.this); // Тут ошибка
builder2.setTitle("Важное сообщение!")
.setMessage("Сообщение")
.setCancelable(false)
.setNegativeButton("ОК",
new DialogInterface.OnClickListener() {
@SuppressLint("RestrictedApi")
public void onClick(DialogInterface dialog, int id) {
click_ok();
dialog.cancel();
}
});
AlertDialog alert = builder2.create();
alert.show();
}
Ошибка на builder2 = new AlertDialog.Builder(MainActivity.this);
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.project33, PID: 28150
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at androidx.appcompat.app.AlertDialog.resolveDialogTheme(AlertDialog.java:115)
at androidx.appcompat.app.AlertDialog$Builder.<init>(AlertDialog.java:313)
at com.example.project33.MainActivity.soobshenie(MainActivity.java:221)
at com.example.project33.Timer$1.onFinish(Timer.java:48)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
К самому таймеру обращаюсь из MainActivity следующим образом:
public void timer_pusk()
{
int min = 15000;
int max = 27000;
int diff = max - min;
Random random = new Random();
int timer_ot_do = random.nextInt(diff);
timer_ot_do += min;
new Timer(timer_ot_do, 1000, new Timer.ITimerCallback() {
@Override
public void ontTimerNewValue(String value) {
timer_vivod.setText(value);
}
}, MainActivity.this);
}
Почему возникает ошибка и как исправить?
new
.new MainActivity()
. Так нельзя.