我是初學者到android。我做了以下應用程序,從用戶那裏花費時間和睡眠時間,並在睡眠期間顯示進度對話框。現在問題是它第一次正常工作,但它在第二次崩潰。再次啓動會出現同樣的問題。與Android中的AsyncTask相關的問題
下面是代碼:需要
package com.example.asynctask;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Main extends AppCompatActivity {
AsyncTaskExecutor executor;
EditText text;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
executor = new AsyncTaskExecutor();
text = (EditText)findViewById(R.id.editText);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
executor.execute(text.getText().toString());
}
}
);
}
class AsyncTaskExecutor extends AsyncTask<String, String, String> {
String res;
ProgressDialog pd;
@Override
protected void onPreExecute(){
pd = new ProgressDialog(Main.this);
pd.setMessage("Sleeping..");
pd.setCancelable(false);
pd.setTitle("Please wait");
pd.show();
}
@Override
protected String doInBackground(String... params){
int time = Integer.parseInt(params[0]);
try
{
Thread.sleep(time);
res = "successfull";
}catch (InterruptedException e){
e.printStackTrace();
res = e.getMessage();
}
publishProgress(res);
return res;
}
@Override
protected void onPostExecute(String result){
pd.dismiss();
}
@Override
protected void onProgressUpdate(String... a){
pd.setMessage(a[0]);
}
}
}
幫助。
@Override public void onClick(View view){ executor = new AsyncTaskExecutor(); executor.execute(text.getText()。toString()); } – xFighter
你可以發佈你的logcat嗎? – sasikumar
把這一行executor = new AsyncTaskExecutor();在按鈕點擊之前和executor.execute(text.getText()。toString())之前; – Nainal