android中的错误类型不匹配asynctask

时间:2014-06-03 13:44:24

标签: android android-asynctask

我正在尝试使用asynctask从mysql中检索数据。但我得到了这个

“类型不匹配:无法从AsyncTask转换      字符串“

虽然asynctask进程的返回已经是字符串

这是我的代码

     public void tampilkanPenyakit() {
                try {
                    String nama = URLEncoder.encode(username, "utf-8");
                    urltampil += "?" + "&nama=" + nama;
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                xResult = getRequestTampil(urltampil);
                try {
                    parse();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

    class ProsesTampil extends AsyncTask<String, Void, String>{

                @Override
                protected String doInBackground(String... params) {
                     String sret = "";
                    HttpClient client = new DefaultHttpClient();
                    HttpGet request = new HttpGet(params[0]);
                    try{
                  HttpResponse response = client.execute(request);
                      sret = EditPenyakit.request(response);

                    }catch(Exception ex){
                }

                    return sret;
                    // TODO Auto-generated method stub
                }

                @Override
                protected void onPostExecute(String result) {
                    // TODO Auto-generated method stub
                    super.onPostExecute(result);

                }

            } 

     public String getRequestTampil(String UrlTampil){

              String sret="";
              sret= new ProsesTampil().execute(UrlTampil);

                return sret;

        }

private void parse() throws Exception {
                //jObject = new JSONObject(xResult);

               jObject = new JSONObject(xResult);
               String sret = "";
                JSONArray menuitemArray = jObject.getJSONArray("food");
                cb_menu1 = (CheckBox) findViewById(R.id.cb_menu1);
                cb_menu2 = (CheckBox) findViewById(R.id.cb_menu2);
                cb_menu3 = (CheckBox) findViewById(R.id.cb_menu3);

                for (int i = 0; i < menuitemArray.length(); i++) {
                    sret =menuitemArray.getJSONObject(i).getString(
                    "penyakit").toString();
                    System.out.println(sret);

                    if (sret.equals("1")){
                        cb_menu1.setChecked(true);
                    }
                    else if (sret.equals("2")){
                        cb_menu2.setChecked(true);
                    }

                }
      }

任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:2)

AsyncTask execute()方法返回 Asyntask本身,不能将其转换为String。

您需要在 onPostExecute()方法中处理结果。

其他选项可以使用AsynTask get method

sret= new ProsesTampil().execute(UrlTampil).get();

考虑到文档: 等待(如有必要)以完成计算,然后检索其结果。