我想setMax進度條的值,並setProgress它,但抓到NullPointerException。我使用AsyncTask更新值和包含ProgressBar的自定義佈局的對話框。所以這是我的代碼。請指出我的錯誤。由於ProgressBar setMax()拋出NullPointerException
public class ActivityMain extends Activity implements View.OnClickListener {
final int PROGRESS_DLG_ID = 505;
ProgressBar pb = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
Button button_db = (Button) findViewById(R.id.button_db);
Button button_settings = (Button) findViewById(R.id.button_settings);
Button button_exit = (Button) findViewById(R.id.button_exit);
pb = (ProgressBar) findViewById(R.id.db_download_pb);
new DBLoad().execute("cards_en.db");
@Override
protected Dialog onCreateDialog(int dialogId) {
Dialog progress = null;
switch (dialogId) {
case PROGRESS_DLG_ID:
progress = new Dialog(this);
progress.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
progress.setContentView(R.layout.db_download_dialog);
break;
}
return progress;
}
這是onProgressUpdate方法在那裏我有例外
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
showDialog(PROGRESS_DLG_ID);
pb.setMax(values[1]); //here throws exception
pb.setProgress(values[0]);
}
解決 在
@Override
protected Dialog onCreateDialog(int dialogId) {
Dialog progress = null;
switch (dialogId) {
case PROGRESS_DLG_ID:
progress = new Dialog(this);
progress.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
progress.setContentView(R.layout.db_download_dialog);
pb = (ProgressBar) progress.findViewById(R.id.cards_download_bar);
break;
}
return progress;
}
也搬到方法SETMAX到preExecute添加進度條的正確的init() 。
也許在佈局'activity_main.xml'中,您沒有帶有@ @ id @ db_download_pb的ProgressBar或值爲空。發佈您的堆棧跟蹤 –
是的,我沒有在佈局activity_main.xml中的ProgressBar。 ProgressBar在定製的對話框中的db_download_dialog.xml中定義,它在onProgressUpdate調用時顯示。 –
這就是發生這種情況的原因。你需要使用正確的pb。 –