异步任务失败

时间:2014-05-06 10:23:39

标签: android json android-asynctask

我正在尝试实现异步任务以满足android中的json函数。 json函数在android 2.3.3中完全正常工作。所以现在我需要将它实现到android中。 4.3果冻豆平台。但它无法像我预期的那样显示任何结果。 Async Task功能出了问题。请帮帮....

public class Update extends Activity{

JSONArray jArray = null;
String result = null;
StringBuilder sb = null;
InputStream is = null;
String ct_name;
LinearLayout l;
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_update);
    Toast.makeText(getBaseContext(), "Done layout",Toast.LENGTH_LONG).show();

class LongOperation extends AsyncTask<String, Void, String>{
        @Override
        protected String doInBackground(String... params) {
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            //http post
            try{
                 HttpClient httpclient = new DefaultHttpClient();

                 //Why to use 10.0.2.2
                 HttpPost httppost = new HttpPost("http://10.0.2.2/moodle/myFile.php");
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                 HttpResponse response = httpclient.execute(httppost);
                 HttpEntity entity = response.getEntity();
                 is = entity.getContent();
                 }catch(Exception e){
                     Log.e("log_tag", "Error in http connection"+e.toString());
                }
            //convert response to string 
            try{
                  BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                   sb = new StringBuilder();
                   sb.append(reader.readLine() + "\n");

                   String line="0";
                   while ((line = reader.readLine()) != null) {
                                  sb.append(line + "\n");
                    }
                    is.close();
                    result=sb.toString();
                    }catch(Exception e){
                          Log.e("log_tag", "Error converting result "+e.toString());
                    }



            try{
                  jArray = new JSONArray(result);
                  JSONObject json_data=null;

                    l = (LinearLayout) findViewById(R.id.container);
                  for(int i=0;i<jArray.length();i++){
                         json_data = jArray.getJSONObject(i);
                         ct_name=json_data.getString("name");//here "Name" is the column name in database

                     }

            }
                  catch(JSONException e1){
                   Toast.makeText(getBaseContext(), "No Data Found" ,Toast.LENGTH_LONG).show();
                  } catch (ParseException e1) {
               e1.printStackTrace();
             }
            return result;


            }



        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.txt_1);
            txt.setText("Executed"); 
            Toast.makeText(getBaseContext(), "this is post",Toast.LENGTH_LONG).show();

                         Toast.makeText(getBaseContext(), ct_name,
                                   Toast.LENGTH_LONG).show();
                         TextView textView = new TextView(null);
                         textView.setText(ct_name + " is out, please attempt it as soon as possible"+ "\n");
                         l.addView(textView);


        }
}
Toast.makeText(getBaseContext(), "lol",
       Toast.LENGTH_LONG).show();
}

}

/////////////////////////////////////////////// //////////////////////////////////////////// 可行的json代码

公共类MainActivity扩展了Activity {

JSONArray jArray = null;
String result = null;
StringBuilder sb = null;
InputStream is = null;
String ct_name;
LinearLayout l;
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
     HttpClient httpclient = new DefaultHttpClient();

     //Why to use 10.0.2.2
     HttpPost httppost = new HttpPost("http://10.0.2.2/moodle/myFile.php");
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     HttpResponse response = httpclient.execute(httppost);
     HttpEntity entity = response.getEntity();
     is = entity.getContent();
     }catch(Exception e){
         Log.e("log_tag", "Error in http connection"+e.toString());
    }
//convert response to string 
try{
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
       sb = new StringBuilder();
       sb.append(reader.readLine() + "\n");

       String line="0";
       while ((line = reader.readLine()) != null) {
                      sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();
        }catch(Exception e){
              Log.e("log_tag", "Error converting result "+e.toString());
        }



try{
      jArray = new JSONArray(result);
      JSONObject json_data=null;

        l = (LinearLayout) findViewById(R.id.container);
      for(int i=0;i<jArray.length();i++){
             json_data = jArray.getJSONObject(i);
             ct_name=json_data.getString("name");//here "Name" is the column name in database
             Toast.makeText(getBaseContext(), ct_name,
                       Toast.LENGTH_LONG).show();
             TextView textView = new TextView(this);
             textView.setText(ct_name + " is out, please attempt it as soon as possible"+ "\n");
             l.addView(textView);
         }

}
      catch(JSONException e1){
       Toast.makeText(getBaseContext(), "No Data Found" ,Toast.LENGTH_LONG).show();
      } catch (ParseException e1) {
   e1.printStackTrace();
 }


}
}

4 个答案:

答案 0 :(得分:0)

您正试图在doInBackground(String... params)中做一些无法做到的事情。使用Assync时,仅在onPreExecuteonPostExecute中更新UI中的任何内容。在这个你试图吐司并附上最终会崩溃的视图。如果你真的想要从后台更新UI,即使它不是一个很好的appoch来解决问题,你可以使用runOnUiThread(action)。使用Assync任务时请记住这一点。无法从后台更新UI。

答案 1 :(得分:0)

它正在崩溃,因为你在doInBackGround()catch部分中显示toast。您无法从不同的线程更新UI。

答案 2 :(得分:0)

用以下代码替换您的代码:

            public class Update extends Activity {

        JSONArray jArray = null;
        String result = null;
        StringBuilder sb = null;
        InputStream is = null;
        String ct_name;
        LinearLayout l;
        String responseString;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_update);
            Toast.makeText(getBaseContext(), "Done layout", Toast.LENGTH_LONG)
                    .show();

            new LongOperation().execute();
        }

        class LongOperation extends AsyncTask<String, String, String> {
            @Override
            protected String doInBackground(String... params) {

                // http post

                HttpClient httpclient = new DefaultHttpClient();

                // Why to use 10.0.2.2
                HttpPost httppost = new HttpPost(
                        "http://10.0.2.2/moodle/myFile.php");
                try {
                    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    response.getStatusLine().getStatusCode();
                    HttpEntity getResponseEntity = response.getEntity();
                    responseString = EntityUtils.toString(getResponseEntity);

                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                }
                return responseString;
            }

            protected void onPostExecute(String resultStr) {
                try {
                    JSONObject json = new JSONObject(responseString);
                    JSONArray jArray = json.getJSONArray("result");
                    l = (LinearLayout) findViewById(R.id.container);
                    for (int i = 0; i < jArray.length(); i++) {
                        JSONObject json_data = jArray.getJSONObject(i);
                        ct_name = json_data.getString("name");
                    }
                    TextView txt = (TextView) findViewById(R.id.txt_1);
                    txt.setText("Executed");
                    Toast.makeText(getBaseContext(), "this is post",
                            Toast.LENGTH_LONG).show();

                    Toast.makeText(getBaseContext(), ct_name, Toast.LENGTH_LONG)
                            .show();
                    TextView textView = new TextView(null);
                    textView.setText(ct_name
                            + " is out, please attempt it as soon as possible"
                            + "\n");
                    l.addView(textView);

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

答案 3 :(得分:0)

  

但它无法显示我预期的任何结果

您似乎不会首先调用异步任务。添加以下内容:

new LongOperation().execute();

同时至少将e.printStackTrace()添加到您的catch块中,以便发现更多问题。