當這兩個Toast裏面的AsyncTask裏面導致崩潰的時候,當我刪除兩個Toast時,一切正常,沒有崩潰。爲什麼是這樣?以及如何在AsyncTask中使用Toast消息而不導致崩潰?Toast裏面的AsyncTask裏面的片段導致崩潰
Toast.makeText(activity, "onPostExecute", Toast.LENGTH_LONG).show();
Toast.makeText(activity,"onPreExecute", Toast.LENGTH_LONG).show();
Logcat顯示toast消息的nullPointerException。當我刪除兩個吐司中的第一個時,它會運行,然後再崩潰,當第一個吐司在那裏時,它將在開始時崩潰,當兩個吐司被移除時,它從不崩潰。
代碼
public class FragmentStaticFragment extends Fragment {
private Button buttonStartProgress;
private ProgressBar progressBar;
Activity activity = getActivity();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_static_fragment, container, false);
buttonStartProgress = (Button) view.findViewById(R.id.button1);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
buttonStartProgress.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new BackgroundAsyncTask().execute();
buttonStartProgress.setClickable(false);
}
});
return view;
}
public class BackgroundAsyncTask extends AsyncTask<Void, Integer, Void>{
int myProgress;
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// commented out this toast to avoid crashing
// Toast.makeText(activity, "onPostExecute", Toast.LENGTH_LONG).show();
buttonStartProgress.setClickable(true);
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
// commented out this toast to avoid crashing
// Toast.makeText(activity,"onPreExecute", Toast.LENGTH_LONG).show();
myProgress = 0;
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
while(myProgress<100){
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(100);
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}
} // end BackgroundAsyncTask
}
EDIT的其餘部分;
添加堆棧跟蹤信息,如果onAttach(Activity)
之前運行
07-13 09:23:01.383: E/AndroidRuntime(19489): FATAL EXCEPTION: main
07-13 09:23:01.383: E/AndroidRuntime(19489): java.lang.NullPointerException
07-13 09:23:01.383: E/AndroidRuntime(19489): at android.widget.Toast.<init>(Toast.java:92)
07-13 09:23:01.383: E/AndroidRuntime(19489): at Android.widget.Toast.makeText(Toast.java:233)
07-13 09:23:01.383: E/AndroidRuntime(19489): at com.example.asynctaskprogressbarexample.FragmentStaticFragment$BackgroundAsyncTask.onPreExecute(FragmentStaticFragment.java:62)
07-13 09:23:01.383: E/AndroidRuntime(19489): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
07-13 09:23:01.383: E/AndroidRuntime(19489): at android.os.AsyncTask.execute(AsyncTask.java:511)
07-13 09:23:01.383: E/AndroidRuntime(19489): at com.example.asynctaskprogressbarexample.FragmentStaticFragment$1.onClick(FragmentStaticFragment.java:36)
郵政logcat的痕跡。 –