2015-08-18 13 views
0

我在Android中,我有做一個REST API多個AsyncTask(一個用於HTTPGet,一個用於HTTPPost),我沒有任何問題與他們,但是當我試圖執行我AsyncTask,我使用HTTPDelete ,它不執行doInBackground()方法。我應該在我的APP上使用.executeOnExecutor嗎?

在SO中搜索我找到了這個解決方案:Android SDK AsyncTask doInBackground not running (subclass)但是我對使用.executeOnExecutor還是不安全,因爲我在官方文檔中搜索:executeOnExecutor,它說它可能是問題。

例如,如果這些任務用於修改任何共同的狀態(如寫入文件由於按鈕點擊),有修改的順序沒有保證。

而且我用我的GETPOSTDELETE方法來修改我的database(我知道這是不是一個file但我想,這可能給我同樣的問題)。

據此,我不確定我能做些什麼來執行這個.doInBackground()方法,因爲我不想在將來遇到任何問題。

我應該使用什麼?

這是我AsyncTask

class DeleteCar extends AsyncTask<Integer, Integer, Void> { 

    protected void onPreExecute(){ 
    } 

    protected Void doInBackground(Integer... id) { 

     try{ 
      String url = "http://IP of my computer/project/cars/" + id[0].intValue(); 

      HttpClient httpClient = new DefaultHttpClient(); 
      HttpDelete method= new HttpDelete(url); 
      method.setHeader("content-type", "application/json"); 
      HttpResponse response = httpClient.execute(method); 

      HttpEntity httpEntity = response.getEntity(); 

     }catch(Exception ex){ 
      Log.e("ServicioRest",ex.toString()); 
     } 

     return null; 
    } 

    protected void onProgressUpdate(){ 
    } 

    protected void onPostExecute(){ 
    } 
} 

我執行它是這樣的:

new DeleteCar().execute(idCar); 

其中idCarInteger idCar = new Integer(id);id這是一個int

注意:它進入onPreExecute()方法,但不在doInBackground() method

+0

idCar是你的execute方法的一個整型對象嗎? –

+0

@MdOmarFaroqueAnik是的。它是一個'int idCar = 5;' –

+0

int是原始的。整數是一個對象。請嘗試像這樣使用新的整數(5),如果它有效。 –

回答

-1

這裏是一個僞代碼,您:

public class DeleteCar extends AsyncTask<Integer,Integer,Void> { 
@Override 
protected Void doInBackground(Integer... params) { 

    //logging to show that it is working 
    Log.d("result:", String.valueOf(params[0].intValue())); 


    return null; 
} 

}

我已經創建了不同的類對我的AsyncTask。然後我從我這樣的活動中調用它:

new DeleteCar().execute(new Integer(10)); 

它完美地工作/執行doInBackground方法。

我的建議是使用改造。下面是幾個鏈接瞭解改造: 1. http://square.github.io/retrofit/ 2.下面是一個比較:https://androidtutorialmagic.wordpress.com/android-asynctask-and-its-dark-side/comparison-among-asynctaskvolley-and-retrofit/ 3.這裏是一個基礎教程:https://androidtutorialmagic.wordpress.com/android-asynctask-and-its-dark-side/retrofit-networking-in-android-tutorial-replacement-of-asynctask-and-volley/

我一直在用改造

。我的反應速度非常快。如果您需要更多幫助來使用改造,請告訴我。謝謝

+0

爲什麼要爲這個問題投票? –