【问题标题】:Failed in async task异步任务失败
【发布时间】:2014-05-06 10:23:38
【问题描述】:

我正在尝试实现异步任务来满足 android 中的 json 功能。 json 函数在 android 2.3.3 中工作得很好。所以现在我需要将它实现到android中。 4.3 糖豆平台。但它无法像我预期的那样显示任何结果。异步任务功能有问题。请帮忙....

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();
 }


}
}

【问题讨论】:

  • 在这里发布你的日志
  • 检查我更新的答案...确保它会帮助你

标签: android json android-asynctask


【解决方案1】:

您正试图在doInBackground(String... params) 中做某事,这是不可能的。使用 Assync 时,仅在 onPreExecuteonPostExecute 中更新 UI 中的任何内容。在这种情况下,您正在尝试敬酒并附加最终会崩溃的视图。如果您真的想从后台更新 UI,即使它不是解决问题的好方法,您也可以使用 runOnUiThread(action) 。在使用 Assync 任务时,请记住这一点。无法从后台更新 UI。

【讨论】:

    【解决方案2】:

    它正在崩溃,因为您在 doInBackGround() 捕获部分显示吐司。您不能从不同的线程更新 UI。

    【讨论】:

      【解决方案3】:

      用这个替换你的代码:

                  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();
                      }
                  }
              }
      
          }
      

      【讨论】:

      • 05-06 07:24:59.111:E/AndroidRuntime(2451):java.lang.NullPointerException 05-06 07:24:59.111:E/AndroidRuntime(2451):在 org.json。 JSONTokener.nextCleanInternal(JSONTokener.java:116) 05-06 07:24:59.111: E/AndroidRuntime(2451): 在 org.json.JSONTokener.nextValue(JSONTokener.java:94) 05-06 07:24:59.111: E/AndroidRuntime(2451): 在 org.json.JSONObject.(JSONObject.java:154) 它显示了这个错误。我有谷歌它,但没有运气。我想知道我该怎么办...
      • 你的 json 数组名是什么...存储所有 json 结果
      • 你能把你的json结果贴在这里吗?
      • 我得到的结果来自数据库。是的,当我在没有 AsyncTask 函数的情况下编译它时,它确实显示了记录和答案。但是当我尝试添加 asyncTask 功能时,它显示错误
      • 我添加了可行的代码,在 2.3.3 姜饼中运行良好。一旦我添加了 AsyncTask,并尝试在 4.3 果冻豆中运行。它停止工作
      【解决方案4】:

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

      您似乎一开始没有调用异步任务。为此添加以下内容:

      new LongOperation().execute();
      

      还至少将e.printStackTrace() 添加到您没有它的catch 块中以发现更多问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-14
        • 1970-01-01
        • 2017-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多