1

編輯:我把這個pB = (ProgressBar) findViewById(R.id.progressBar);放在onPreExecute()中。它工作,一切正常。但這是一個很好的解決方案嗎?我知道在我的主線程中進度條是空的。但在這個findViewById之前,我的asynctask無法找到我想要的進度條,儘管我認爲我是通過.execute()傳遞它的。onProgressUpdate中的NullPointerException()

這是我第一次使用asynctask。我有一個進度條,我想要計數,但我一直在收到一個NullPointerException。

日誌讀取「進度更新:1」,但隨後VM關閉。所以我知道一個整數正在越過,但我無法弄清楚爲什麼它找不到進度條(pB)。我試圖在onPreExecute()的主線程中設置進度(0),但機器討厭它。

它運行doInBackground()中for循環的其餘部分,並記錄「百分比進度:」和「睡眠」,但不會再記錄「進度更新:」。

NullPointerException在第31行,即pB.setProgress(progress [0]);

@Override 
protected void onProgressUpdate(Integer...progress){ 
    Log.d(LOG_TAG, "Progress Update: "+progress[0].toString()); 

    super.onProgressUpdate(progress); 
    if(progress[0]!=null){ 
    pB.setProgress(progress[0]); 
    } 
} 

@Override 
protected Boolean doInBackground(Integer...numSeconds){ 
    Log.d(LOG_TAG, "doInBackground: "+numSeconds[0]); 

    try { 
     int totalSecs = numSeconds[0].intValue(); 
     Log.d(LOG_TAG, "Total SECS: "+totalSecs); 

     for(int i = 1; i <= totalSecs; i++){ 
      Log.d(LOG_TAG, "Sleeping "+i); 
      Thread.sleep(1000); 

      float percentage = ((float)i/(float)totalSecs)*100; 
      Log.d(LOG_TAG, "Percentage Progress: "+ percentage); 

      Float progress = Float.valueOf(percentage); 
      publishProgress(new Float(progress).intValue()); 
     } 
    } catch (InterruptedException e){ 
     e.printStackTrace(); 
     return false; 
    } 
    return true; 
} 
@Override 
protected void onPostExecute(Boolean result){ 
    Log.d(LOG_TAG, "Post Execute "+ result); 

    super.onPostExecute(result); 

    pB.setProgress(0); 
} 

下面是一些從我的主線程:

要初始化進度條: 計時器=(進度)findViewById(R.id.progressBar); timer.setProgress(0);

要執行的AsyncTask:

OnClickListener startBubbles = new OnClickListener(){ 

    @Override 
    public void onClick(View arg0) { 
     new ProgBar(timer).execute(100); 
     setAll(); 
    }  
}; 

構造:當您正在訪問的值,這是尚未發生initaialized

public ProgBar(ProgressBar pB){ 
    Log.d(LOG_TAG, "Constructor"); 

} 
+7

狂猜。 pB爲空! – Blackbelt

+0

我認爲你可能會做些什麼。但是,我怎樣才能使它不爲空?我必須在我的asyncTask中再次找到ViewById嗎?它應該從主線程傳遞,對吧? – user3067903

+0

@ user3067903檢查你是否已經在任何地方初始化了'pB'。 「它應該從主線程傳遞過來,對吧?」你把它傳遞給asynctask還是你asynctask是一個內部類的活動類? – Raghunandan

回答

0

空指針異常。

因此,例如。 char a [10];

System.out.println(a [3]);

因此,您的代碼中必須存在可變的內容,而且您無需初始化即可訪問。我的事情numSecond,但我不知道。

對不起,我只知道

相關問題