我正在尝试设置进度条的Max值,并将setProgress设置为它,但是捕获了NullPointerException。我使用AsyncTask更新值和带有自定义布局的Dialog,其中包含ProgressBar。所以这是我的代码。请指出我的错误。感谢
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()。
答案 0 :(得分:0)
为什么每次onProgressUpdate()都设置最大值?如果你在onPreExecute()中设置一次并不容易? 你有没有设定初步进度?
请粘贴您的AsyncTask类以便更好地理解。