有人知道怎么放AlertDialog
吗AsyncTask
?我有使用 WebService 的应用程序。所以我已经输入了IP地址以启动应用程序。目前我必须输入默认 IP 地址,然后使用 更改它AlertDialog
,比如设置->插入 ip。现在我想每次应用程序启动时,AlertDialog
都会先创建。我认为对于该解决方案,我必须使用AsyncTask
. 但是在我实现它的方式上,我遇到了一些关于使用的问题AsyncTask
下面显示当应用程序没有 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 started an Activity in Android?
我的问题是当我输入:
//refreshing GUI
intent = new Intent(this, BroadcastService.class);
在 preExecute 中不起作用,但如果我放入 onCreate,它将获得空指针。有人知道如何解决这个问题吗?这样我可以AlertDialog
在启动应用程序时使用
编辑:我可以将意图放在 preExecute 中,只需将意图更改为intent = new Intent(MainActivity.this, BroadcastService.class);
. 但似乎解决不了问题。该对话框从未被创建并且总是有空指针。有人知道吗?