假设我有文本输入和输出以及要发布的按钮。因此,我将一些json(nameValuePairs)发布到给定的API。我知道如何通过严格模式线程策略技巧来制作这些东西,但是,我需要AsyncTask才能使用ProgressBar。

public class MainActivity extends Activity  {
//Toast.makeText(getBaseContext(), str_text_input, Toast.LENGTH_LONG).show();
public String URL = "someurl";
EditText text_input;
EditText output;
ProgressBar progressbar;


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


    text_input = (EditText) findViewById(R.id.text_input);
    output = (EditText) findViewById(R.id.text_output);


    progressbar = (ProgressBar) findViewById(R.id.progressBar);
    progressbar.setVisibility(View.GONE);

}

public void button_called(View view) {
     progressbar.setVisibility(View.VISIBLE);
     String txt = text_input.getText().toString();

     sendPostRequest(txt, "somecheckcode", Integer.toString(int1), Integer.toString(int2));
     // Here I want result of posting http request = Response


     output.setText(Response);

}

 String sendPostRequest(String txt, String Code, String dir, String topic ) {

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

        @Override
        protected String doInBackground(String... params) {

            String text = params[0];
            String code = params[1];
            String direction = params[2];
            String topics = params[3];
            String finalResult = "";

            //System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword);

            HttpClient httpClient = new DefaultHttpClient();

            // In a POST request, we don't pass the values in the URL.
            //Therefore we use only the web page URL as the parameter of the HttpPost argument
            HttpPost httpPost = new HttpPost(URL);

            // Because we are not passing values over the URL, we should have a mechanism to pass the values that can be
            //uniquely separate by the other end.
            //To achieve that we use BasicNameValuePair
            //Things we need to pass with the POST request
            BasicNameValuePair srctxt = new BasicNameValuePair("param1", text);
            BasicNameValuePair chkcode = new BasicNameValuePair("param2", code);
            BasicNameValuePair direct = new BasicNameValuePair("param3", direction);
            BasicNameValuePair sbjbs = new BasicNameValuePair("param4", topics);

            // We add the content that we want to pass with the POST request to as name-value pairs
            //Now we put those sending details to an ArrayList with type safe of NameValuePair
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
            nameValuePairList.add(srctxt);
            nameValuePairList.add(chkcode);
            nameValuePairList.add(direct);
            nameValuePairList.add(sbjbs);

            try {
                // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs.
                //This is typically useful while sending an HTTP POST request.
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList, HTTP.UTF_8);

                // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
                httpPost.setEntity(urlEncodedFormEntity);

                try {
                    // HttpResponse is an interface just like HttpPost.
                    //Therefore we can't initialize them
                    HttpResponse httpResponse = httpClient.execute(httpPost);

                    // According to the JAVA API, InputStream constructor do nothing.
                    //So we can't initialize InputStream although it is not an interface
                    InputStream inputStream = httpResponse.getEntity().getContent();

                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                    StringBuilder stringBuilder = new StringBuilder();

                    String bufferedStrChunk = null;

                    while((bufferedStrChunk = bufferedReader.readLine()) != null){
                        stringBuilder.append(bufferedStrChunk);
                    }
                    finalResult = stringBuilder.toString();
                    return stringBuilder.toString();

                } catch (ClientProtocolException cpe) {
                    System.out.println("First Exception of HttpResponese :" + cpe);
                    cpe.printStackTrace();
                } catch (IOException ioe) {
                    System.out.println("Second Exception of HttpResponse :" + ioe);
                    ioe.printStackTrace();
                }

            } catch (UnsupportedEncodingException uee) {
                System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
                uee.printStackTrace();
            }

            return finalResult;
        }

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


        }
    }

    SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();

    sendPostReqAsyncTask.execute(txt, Code, dir, topic);
           return "RESULT_I_WANTED";
}

最佳答案

在活动中创建另一个方法来设置输出文本,并采用如下所示的输入字符串参数。

public void setOutputText(String outputText) {

   output.setText(outputText);

 }


然后在AsyncTask的onPostExecute方法中调用此方法,如下所示。

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        setOutputText(result);

    }

关于android - 如何从AsyncTask http发布获取结果?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23948033/

10-13 04:17