求解,模拟进度条问题。
public class ProgressBars extends Activity{ private ProgressBar bar; private myAsyncTask asyncTask; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.progerssbar); bar=(ProgressBar) findViewById(R.id.pro); asyncTask.execute(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); if(asyncTask!=null&&asyncTask.getStatus()==asyncTask.getStatus().RUNNING){ asyncTask.cancel(true); } } class myAsyncTask extends AsyncTask<Void, Integer, Void>{ @Override protected Void doInBackground(Void... arg0) { // TODO Auto-generated method stub for (int i = 0; i < 100; i++) { if(isCancelled()){ break; } publishProgress(i); try { Thread.sleep(300); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } @Override protected void onProgressUpdate(Integer... values) { // TODO Auto-generated method stub super.onProgressUpdate(values); if(isCancelled()){ return; } bar.setProgress(values[0]); } } }
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.astest/com.example.astest.ProgressBars}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.AsyncTask com.example.astest.ProgressBars$myAsyncTask.execute(java.lang.Object[])' on a null object reference
主界面activity中设置了按钮的点击事件,也声明了activity,不知道为什么还会报空指针异常