0

我对 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);
}
}
4

3 回答 3

1

You don't have to call onPostExecute() yourself, the system will do it with whatever you return in doInBackground().

I guess changing the line to return null like the other answer says, could fix the issue, but it's probably not what you want. You probably want to return an integer, extracted from the response, or something else.

Another strange thing in your code is data[0], data is an ArrayList, does that compile? You also can't be defining a new variable data since this would produce duplicate variable compiler error.

于 2012-08-03T20:07:33.853 回答
0

尝试改变这个:

this.onPostExecute(null);

对此:

return null;
于 2012-08-03T20:00:24.707 回答
0

为什么您尝试在后台方法中调用 post Execute 方法。它是自动调用的。删除它并尝试

希望能帮助到你

于 2012-08-03T20:03:38.243 回答