【问题标题】:How can I pass Strings from doInBackground to onPostExecute如何将字符串从 doInBackground 传递到 onPostExecute
【发布时间】:2016-03-11 06:27:02
【问题描述】:

我想将 3 个字符串从 doInBackground 发送到 onPostExecute。

我设法获取了数据,并且可以在日志中看到它们。现在如何在 doInBackground 完成执行后使用存储在 Strings 中的数据。

这是我的代码。

public class MainActivity extends AppCompatActivity {

    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "http://example.com/test.php";

    // JSON Node names
    private static final String tag_info = "info";
    private static final String tag_success = "Success";
    private static final String tag_message = "message";
    private static final String tag_output = "output";

    // contacts JSONArray
    JSONArray info = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Calling async task to get json
        new fetchInfo().execute();
    }


    /**
     * Async task class to get json by making HTTP call
     * */
    private class fetchInfo extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    info = jsonObj.getJSONArray(tag_info);
                    JSONObject c = info.getJSONObject(0);

                    // I want to use these 3 strings in onPostExecute
                        String success = c.getString(tag_success);
                        String message = c.getString(tag_message);
                        String output = c.getString(tag_output);



                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

            TextView successView = (TextView) findViewById(R.id.success_field);
            successView.setText(success + " " + message + " " + output); // I want to print them here   


        }

    }


}

【问题讨论】:

  • 制作模型类并通过
  • 你能把代码改成在这里贴出来

标签: android json xml


【解决方案1】:

使用字符串数组

protected String[] doInBackground(String[]... passing) {
    String[] result = new String[3];
     result[0]= c.getString(tag_success);
     result[1] = c.getString(tag_message);
     result[2] = c.getString(tag_output);
    return result; //return result
}

 protected void onPostExecute(String result[]) {

String a  = result[0];
}

【讨论】:

    【解决方案2】:

    豆类

    public class BeanClass{
     String message,success,output;
    
    public BeanClass(String message,String success,String output){
      this.message = message;
      this.success = success;
      this.output = output;
    }
    
    public String getMessage(){ return message;}
    
    public String getSuccess(){ return success;}
    
    public String getOutput(){ return output;}
    }
    

    将您的异步任务更改为

    private class fetchInfo extends AsyncTask<Void, Void, BeanClass> {
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Showing progress dialog
                pDialog = new ProgressDialog(MainActivity.this);
                pDialog.setMessage("Please wait...");
                pDialog.setCancelable(false);
                pDialog.show();
    
            }
    
            @Override
            protected Bean doInBackground(Void... arg0) {
                // Creating service handler class instance
               Bean result=null;
    
                ServiceHandler sh = new ServiceHandler();
    
                // Making a request to url and getting response
                String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
    
                Log.d("Response: ", "> " + jsonStr);
    
                if (jsonStr != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);
    
                        // Getting JSON Array node
                        info = jsonObj.getJSONArray(tag_info);
                        JSONObject c = info.getJSONObject(0);
    
                        // I want to use these 3 strings in onPostExecute
                            String success = c.getString(tag_success);
                            String message = c.getString(tag_message);
                            String output = c.getString(tag_output);
    
                           result = new Bean(sucess,message,output);
    
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }
    
                return result;
            }
    
            @Override
            protected void onPostExecute(Bean result) {
                super.onPostExecute(result);
                // Dismiss the progress dialog
                if (pDialog.isShowing())
                    pDialog.dismiss();
    
               if(result!=null){
                TextView successView = (TextView) findViewById(R.id.success_field);
                successView.setText(result.getSuccess() + " " + result.getMessage() + " " + result.getOutput()); // I want to print them here   
    }
    
            }
    
        }
    

    【讨论】:

      【解决方案3】:

      试试这个.......不需要通过

      public class MainActivity extends AppCompatActivity {
      
          private ProgressDialog pDialog;
      
          // URL to get contacts JSON
          private static String url = "http://example.com/test.php";
      
          // JSON Node names
          private static final String tag_info = "info";
          private static final String tag_success = "Success";
          private static final String tag_message = "message";
          private static final String tag_output = "output";
      
          // contacts JSONArray
          JSONArray info = null;
      
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
      
              // Calling async task to get json
              new fetchInfo().execute();
          }
      
      
          /**
           * Async task class to get json by making HTTP call
           * */
          private class fetchInfo extends AsyncTask<Void, Void, Void> {
      
            String success = "";
            String message = "";
            String output = "";
      
              @Override
              protected void onPreExecute() {
                  super.onPreExecute();
                  // Showing progress dialog
                  pDialog = new ProgressDialog(MainActivity.this);
                  pDialog.setMessage("Please wait...");
                  pDialog.setCancelable(false);
                  pDialog.show();
      
              }
      
              @Override
              protected Void doInBackground(Void... arg0) {
                  // Creating service handler class instance
                  ServiceHandler sh = new ServiceHandler();
      
                  // Making a request to url and getting response
                  String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
      
                  Log.d("Response: ", "> " + jsonStr);
      
                  if (jsonStr != null) {
                      try {
                          JSONObject jsonObj = new JSONObject(jsonStr);
      
                          // Getting JSON Array node
                          info = jsonObj.getJSONArray(tag_info);
                          JSONObject c = info.getJSONObject(0);
      
                          // I want to use these 3 strings in onPostExecute
                               success = c.getString(tag_success);
                               message = c.getString(tag_message);
                               output = c.getString(tag_output);
      
      
      
                      } catch (JSONException e) {
                          e.printStackTrace();
                      }
                  } else {
                      Log.e("ServiceHandler", "Couldn't get any data from the url");
                  }
      
                  return null;
              }
      
              @Override
              protected void onPostExecute(Void result) {
                  super.onPostExecute(result);
                  // Dismiss the progress dialog
                  if (pDialog.isShowing())
                      pDialog.dismiss();
      
                  TextView successView = (TextView) findViewById(R.id.success_field);
                  successView.setText(success + " " + message + " " + output); // I want to print them here   
                  Log.e("First Value", success);
                  Log.e("Second Value", message);
                  Log.e("Third Value", output);
      
              }
      
          }
      
      
      }
      

      【讨论】:

      • 你应该使用返回值而不是全局变量。
      【解决方案4】:
      public class fetchInfo extends AsyncTask<Void, Void, String> {
      
      
      
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
              // Showing progress dialog
              pDialog = new ProgressDialog(MainActivity.this);
              pDialog.setMessage("Please wait...");
              pDialog.setCancelable(false);
              pDialog.show();
      
          }
          @Override
          protected String doInBackground(Void... params) {
      
              ServiceHandler sh = new ServiceHandler();
      
              // Making a request to url and getting response
              String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
      
              Log.d("Response: ", "> " + jsonStr);
      
              if (jsonStr != null) {
                  try {
                      JSONObject jsonObj = new JSONObject(jsonStr);
      
                      // Getting JSON Array node
                      info = jsonObj.getJSONArray(tag_info);
                      JSONObject c = info.getJSONObject(0);
      
                      // I want to use these 3 strings in onPostExecute
                      String success = c.getString(tag_success);
                      String message = c.getString(tag_message);
                      String output = c.getString(tag_output);
      
      
      
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
              } else {
                  Log.e("ServiceHandler", "Couldn't get any data from the url");
              }
      
              return output;
      
          }
      
          @Override
          protected void onPostExecute(String s) {
              super.onPostExecute(s);
      
              if (pDialog.isShowing())
                  pDialog.dismiss();
      
              TextView successView = (TextView) findViewById(R.id.success_field);
              successView.setText(s); // I want to print them here 
          }
      
      
      }
      

      【讨论】:

        【解决方案5】:

        在声明时这样做

        Public class Do Task extends AsyncTask<Void, Void, String>{    
        

        然后在doInBackground方法中

        protected String[] doInBackground(String[]... passing) {
        return result; //change it to a string from null
            }
        

        然后在 onPostExecute 结果是你想要的字符串

               @Override
              protected void onPostExecute(Void result) {
                super.onPostExecute(result);
        
        
            }
        

        如果您仍然遇到问题,请告诉我。如果有帮助,请标记。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-05
          相关资源
          最近更新 更多