2012-12-09 28 views
12

在我的一項活動中,我使用的是AsyncTask。在doInBackground()我打電話給各種方法。在其中一個方法中,我收到一個異常,所以在catch塊中,我想在Toast中顯示錯誤。 我知道我可以用Log,但我仍然比較喜歡吐司。 那麼,如何在doInBackground()中的AsyncTask中使用Toast?如何在doInBackground的AsyncTask中顯示吐司

+0

你爲什麼不從doInBackground(重新調整誤差onPostExecute),然後使這個錯誤來自onPostExecute –

+0

舉杯您不能修改從UI doInBackground()方法嘗試返回一些結果,並在onPostExecute()方法中測試該結果,如果是,則顯示Toast – Houcine

+1

@Sam:簡單的人!我沒有投票失敗,我剛剛添加了我的評論,我知道你可以在'doInBackground()'中授予訪問權限,但不建議這樣做,如果是這樣,那麼爲什麼有方法'onProgressUpdate )'和'onPostExecute()'? – Houcine

回答

10

您可以將烤麪包包裹在runOnUIThread()中,但這不是最佳解決方案。
當發生錯誤時,您應該在catch塊中設置一個布爾標誌,然後在onProgressUpdate()onPostExecute()或任何其他具有UI訪問權限的方法中,在標誌爲true時顯示相應的Toast。

+0

我不明白,要麼...... +1了 – Ahmad

+1

@Ahmad我回來了,因爲我們畢竟是對的。 – Sam

+0

應將哪個上下文傳遞給toast ** getBaseContext()**或** getApplication()**上下文? – hrishikesh

3

你可以在一個方法,能夠訪問像onPreExecute()onProgressUpdate()從doInBackground onPostExecute()

17

回報

protected String doInBackground(String... params){ 
    //some code 
    try{ 
     //some code 
    }catch(Exception e){ 
     return "Exception Caught"; 
    } 
    return someValidResult; 
} 

protected void onPostExecute(String result){ 
    if(result.equalsIgnoreCase("Exception Caught")){ 
     //Display Toast 
    }else{ 
     // // whatever you wana do with valid result 
    } 
} 
6

編寫下面的代碼,你必須表明敬酒UI線程顯示它在doInBackground()方法

runOnUiThread(new Runnable() { 

public void run() { 

    Toast.makeText(getApplicationContext(), "Example for Toast", Toast.LENGTH_SHORT).show(); 

    } 
}); 
  • BTW:如果你正在使用Fragments,你需要通過你的活動來調用runOnUiThread(...)

getActivity().runOnUiThread(...)

1
runOnUiThread(new Runnable() { 

public void run() { 

    Toast.makeText(getApplicationContext(), "Example for Toast", Toast.LENGTH_SHORT).show(); 

    } 
}); 

工作完全正常,以顯示doInBackground吐司()方法

4

創建處理程序對象並使用它執行所有的Toast消息。

@Override 
protected Void doInBackground(Void... params) { 

    Handler handler=new handler(); 
    handler= new Handler(context.getMainLooper()); 
    handler.post(new Runnable(){ 
     public void run(){ 
      Toast.makeText(context, "Created a server socket",Toast.LENGTH_LONG).show(); 
     } 
    }); 
    } 
0
activity.runOnUiThread(new Runnable() { 
public void run() 
{ 
    Toast.makeText(activity, "Toast teaxt", Toast.LENGTH_SHORT).show(); 
} 
}); 
0

試試這個代碼

void showError(final String err) { 
    runOnUiThread(new Runnable() { 
     public void run() { 
      Toast.makeText(downloadprogress.this, err + "error in download", Toast.LENGTH_LONG) 
        .show(); 
     } 
    }); 
    }