簡體   English   中英

Android:AsyncThread迫使我關閉我的應用

[英]Android: AsyncThread forces me to close my app

我是Android的新手。 我正在嘗試使用AsyncTask,但是在執行線程之后,我的應用程序迫使我關閉它。 在我的異步線程內部,我在服務器端執行php,以保存來自Android傳感器的數據。 任何幫助將不勝感激。 謝謝

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);        
 .....
 final FuncionsActivity functions = new FuncionsActivity();
 if(something)
    functions.execute(nameValuePairs); 
 .....
  }

 private class FuncionsActivity extends 
       AsyncTask<ArrayList<NameValuePair>, Integer, Integer > {
    @Override
    protected Integer doInBackground(ArrayList<NameValuePair>... data) {
         // 1) Connect via HTTP. 2) Encode data. 3) Send data.
        try
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new     

                  HttpPost("http://.../saveCoordinates.php");                           
            //HttpPost httppost = new 
            httppost.setEntity(new UrlEncodedFormEntity(data[0]));
            HttpResponse response = httpclient.execute(httppost);
            Log.i("postData", response.getStatusLine().toString());
            this.onPostExecute(null);
                //Could do something better with response.
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error1:  " + e.toString());
        }
      return 0;     
      }

      protected void onProgressUpdate(Integer... item){
            Log.d("TestP", item[0] + " item has been processed");
      }

      protected void onPostExecute(Integer result){
            Log.d("TestP", "AsyncTask returned : " + result);
      }
 }

@Override
protected void onDestroy() {            
    super.onDestroy(); // Move to bottom
    //System.runFinalizersOnExit(true);
}
}

您不必自己調用onPostExecute() ,系統將使用您在doInBackground()返回的內容進行doInBackground()

我猜想像其他答案一樣更改行以return null可以解決此問題,但這可能不是您想要的。 您可能想要返回一個從響應中提取的整數或其他內容。

您代碼中的另一個奇怪的事情是data[0] ,數據是一個ArrayList,可以編譯嗎? 您也不能定義新的變量數據,因為這會產生重復的變量編譯器錯誤。

嘗試更改此:

this.onPostExecute(null);

對此:

return null;

為什么要嘗試在Background方法內調用post Execute方法。 它被自動調用。 刪除並嘗試

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM