执行AsyncTask不起作用

时间:2014-04-18 20:28:37

标签: android android-asynctask

我正在尝试执行AsyncTask,以便在用户点击按钮时从活动更新textView。按钮操作是' openVotar'并且要更新的textView是' textvaloracionempresa'。点击按钮时不会显示异常,但会发生任何事情。显示的URL来自带有JSON编码功能的PHP文件,输出是此类型的数组[" 8"]。

public void openVotar(View view)
    {
        new MyAsyncTask().execute();
    }
    private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

        @Override
        protected Double doInBackground(String... params) {
            // TODO Auto-generated method stub
            postData(params[0]);
            return null;
        }

        protected void onPostExecute(Double result){
            pb.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
        }
        protected void onProgressUpdate(Integer... progress){
            pb.setProgress(progress[0]);
        }

        public void postData(String valueIWantToSend) {
            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://xxxxxx/cambiarvaloracionempresa.php?id="+idEmpresa
                    );

            try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                TextView txtvaloracionempresa = (TextView) findViewById(R.id.valoracionEmpresa);
                txtvaloracionempresa.setText((CharSequence) response);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }
        }

    }

我需要您的帮助来更新我的代码。谢谢。

更新的问题

抛出异常:

04-18 23:32:47.021: E/AndroidRuntime(1391): FATAL EXCEPTION: AsyncTask #3
04-18 23:32:47.021: E/AndroidRuntime(1391): java.lang.RuntimeException: An error occured while executing doInBackground()
04-18 23:32:47.021: E/AndroidRuntime(1391):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-18 23:32:47.021: E/AndroidRuntime(1391):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-18 23:32:47.021: E/AndroidRuntime(1391):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-18 23:32:47.021: E/AndroidRuntime(1391):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-18 23:32:47.021: E/AndroidRuntime(1391):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-18 23:32:47.021: E/AndroidRuntime(1391):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-18 23:32:47.021: E/AndroidRuntime(1391):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-18 23:32:47.021: E/AndroidRuntime(1391):     at java.lang.Thread.run(Thread.java:856)
04-18 23:32:47.021: E/AndroidRuntime(1391): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
04-18 23:32:47.021: E/AndroidRuntime(1391):     at com.solinpromex.vivegrancanaria.Empresas_SingleItemView$MyAsyncTask.doInBackground(Empresas_SingleItemView.java:151)
04-18 23:32:47.021: E/AndroidRuntime(1391):     at com.solinpromex.vivegrancanaria.Empresas_SingleItemView$MyAsyncTask.doInBackground(Empresas_SingleItemView.java:1)
04-18 23:32:47.021: E/AndroidRuntime(1391):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-18 23:32:47.021: E/AndroidRuntime(1391):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-18 23:32:47.021: E/AndroidRuntime(1391):     ... 4 more

当前代码:

public void openVotar(View view)
{
    Log.i("Response", "Hemos entrado en openVotar: ");
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR1)
          new MyAsyncTask().execute();
        else
          new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

@Override
protected Double doInBackground(String... params) {
    // TODO Auto-generated method stub
    Log.i("Response", "Hemos entrado en asynctask: ");

    return null;
}

protected void onPostExecute(Double result){
    }
protected void onProgressUpdate(Integer... progress){
    pb.setProgress(progress[0]);
}

public void postData(String valueIWantToSend) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://xxxx/cambiarvaloracionempresa.php?id="+idEmpresa
            );

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        TextView txtvaloracionempresa = (TextView) findViewById(R.id.valoracionEmpresa);
        InputStream ips  = response.getEntity().getContent();
        BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8"));

        StringBuilder sb = new StringBuilder();
        String s;
        while (true) {
          s = buf.readLine();
          if ((s == null) || (s.length() == 0))
            break;
          sb.append(s);
        }

        buf.close();
        ips.close();
        Log.i("Response", "My response is: " + sb.toString());
        txtvaloracionempresa.setText(sb.toString());
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}

}

1 个答案:

答案 0 :(得分:2)

您已将HTTP POST请求发送到远程服务器,但您没有处理它返回的内容。 response确实不是它返回的文本,而是HttpResponse

您需要添加以下内容:

InputStream ips  = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8"));

StringBuilder sb = new StringBuilder();
String s;
while (true) {
  s = buf.readLine();
  if ((s == null) || (s.length() == 0))
    break;
  sb.append(s);
}

buf.close();
ips.close();
Log.i("Response", "My response is: " + sb.toString());

----编辑----

AsyncTask执行语句更改为:

if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR1)
  new MyAsyncTask().execute();
else
  new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);