任何人都知道如何將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);
。但似乎無法解決問題。該對話框從未被創建過,並且總是得到空指針。任何人都知道?