如何将字符串从doInBackground传递给onPostExecute

时间:2016-03-11 06:27:02

标签: android json xml

我想从doInBackground发送3个字符串到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   


        }

    }


}

5 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分:0)

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 
    }


}

答案 2 :(得分:0)

Bean类

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 :(得分:0)

在声明

时执行此操作
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);


    }

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

答案 4 :(得分:0)

试试这个.......不需要传递

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

        }

    }


}