任何人都知道如何将AlertDialog
放入AsyncTask
?我有使用WebService的应用程序。所以我已经把IP地址,以启动应用程序。目前我必须把默认的IP地址,然后我改变它使用AlertDialog
,所以喜欢设置 - >插入IP。现在我想每次应用程序启动时,首先创建AlertDialog
。我认为对于该解决方案,我必须使用AsyncTask
。但是在我执行的方式,我有使用AsyncTask
使用AsyncTask进行AlertDialog
下图显示的时候没有的AsyncTask应用FORR IP
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set the ip address
ip = "124.23.204.135";
//asyncTask for updating gamer's information
new GamerWorker().execute(ip);
//refreshing GUI
intent = new Intent(this, BroadcastService.class);
我使用AsyncTask
GamerWorker()
以更新从WebService的信息对于一些问题。我还声明了刷新GUI的意图。下图显示,当我实现AsyncTask
为AlertDialog
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set the ip address
LayoutInflater inflater = getLayoutInflater();
final View dialoglayout = inflater.inflate(
R.layout.alertdialog_add_gamer, null);
// start creating the dialog message
Builder builder = new AlertDialog.Builder(this);
builder.setView(dialoglayout);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// get the editText from the dialog's view
EditText text = (EditText) dialoglayout
.findViewById(R.id.et_gamerIpOrWebAdress);
// disable all input views
ip = text.getText().toString();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// cancels the dialog
dialog.dismiss();
}
});
new MyTask(builder).execute();
//refreshing GUI
intent = new Intent(this, BroadcastService.class);
}
而对于AsyncTask
,我是用我宣布:
public class MyTask extends AsyncTask<Void, Void, Void> {
private Builder builder;
public MyTask(Builder builder) {
this.builder = builder;
}
public void onPreExecute() {
AlertDialog dialog = builder.create();
dialog.show();
}
public Void doInBackground(Void... unused) {
return null;
}
public void onPostExecute(Void unUsed) {
new GamerWorker().execute(ip);
}
}
其实从AlertDialog
,我下面这样的回答:How to display progress dialog before starting an activity in Android? 我的问题是,当我把:
//refreshing GUI
intent = new Intent(this, BroadcastService.class);
在preExecute不工作,但如果我把onC reate,它会得到空指针。任何人都知道如何解决这个问题,使启动应用程序
编辑时,我可以用AlertDialog
:我可以把意图在preExecute,只是改变意图intent = new Intent(MainActivity.this, BroadcastService.class);
。但似乎无法解决问题。该对话框从未被创建过,并且总是得到空指针。任何人都知道?