【发布时间】:2017-10-18 03:48:46
【问题描述】:
我尝试使用以下方法创建一个类并从 onCreate 之外的函数运行它,但是我尝试执行它时总是收到空指针异常错误。我用谷歌搜索并尝试了一整天没有结果。有人可以帮我理解如何从onCreate之外的方法执行以下类吗?如果我在 Create 中调用它,它运行得很好。谢谢。
runOnUiThread(new Runnable() {
@Override
public void run() {
Dialog x = new Dialog();
x.showDialog(this, act0, "restart0");
}
});
//Dialog class
package com.calmchess.game1;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.Button;
/**
* Created by bobsmithzero on 10/16/17.
*/
public class Dialog extends Activity{
public void showDialog(final Context context, final Activity act00, final String dialogId0) {
switch (dialogId0) {
case ("pause0"):
Button paBtn0 = (Button) act00.findViewById(R.id.pabtn0);
paBtn0.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//set up pause dialog
final android.app.Dialog dialog0 = new android.app.Dialog(context);
dialog0.setContentView(R.layout.activity_controls);
dialog0.setCancelable(true);
Globals.pause0 = true;
Button button = (Button) dialog0.findViewById(R.id.pasbtn0);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog0.cancel();
Globals.pause0 = false;
}
});
Button reBtn0 = (Button) dialog0.findViewById(R.id.rebtn0);
reBtn0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Restart restart0 = new Restart();
restart0.doRestart(context);
}
});
dialog0.show();
}
});
break;
case ("restart0"):
Log.e("error","this thAT");
//set up pause dialog
runOnUiThread(new Runnable() {
@Override
public void run() {
//set up pause dialog
android.app.Dialog dialog1 = new android.app.Dialog(context);
dialog1.setContentView(R.layout.activity_restart);
dialog1.setCancelable(true);
Globals.pause0 = true;
Button button = (Button) dialog1.findViewById(R.id.restart0);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Restart restart0 = new Restart();
restart0.doRestart(context);
}
});
dialog1.show();
}
});
break;
}
}
}
【问题讨论】:
-
如果您的
Dialog类没有被用作Activity,则它不应扩展Activity。您也可以考虑重命名它,以防止与 Android 的Dialog类混淆。 -
你会真正受益于用更合适的名称命名你的东西并使用有效的日志。