0

I am doing HTTP connection in AsyncTask. I am returning the string result of the query back to the calling code. There I am setting the value of EditText "HTTPResult" to the returned resultant string. But the HTTPResult is empty. This means nothing is returned to the calling code. However, I am getting the result string within the AsyncTask and can set HTTPResult inside protected void onPostExecute(String bitmap) method of AsyncTask. Then I used interface and delegates but did not get the result.

CODE:

public class RegisterActivity extends AppCompatActivity implements AsyncResponse {
    Button btn_Connect;
    EditText busNumber;
    EditText text;
    EditText HTTPResult;
    String myServer="http://swulj.atwebpages.com/hi.php";
    String myResult, token;
    HTTPConnection1 conn = new HTTPConnection1();
    RegisterActivity obj = this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        btn_Connect = (Button) findViewById(R.id.button_Connect);
        busNumber = (EditText) findViewById(R.id.Bus_number);
        text = (EditText) findViewById(R.id.text);
        HTTPResult = (EditText) findViewById(R.id.HTTPResult);

        btn_Connect.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // it was the 1st button

                Toast.makeText(getApplicationContext(),"You download is resumed2",Toast.LENGTH_LONG).show();
                conn.delegate =  obj;

                conn.execute(myServer, (String) busNumber.getText().toString());
                //sleep(50000);
                HTTPResult.setText(myResult);
                /*StringTokenizer st = new StringTokenizer(myResult);
                token = st.nextToken("<br>");
                text.setText(token);
                while (st.hasMoreTokens()) {
                    token = st.nextToken("<br>");
                    busNumber.setText(token);
                }*/
            }
        });
    }

    @Override
    public void processFinish(String output){
        //Here you will receive the result fired from async class
        //of onPostExecute(result) method.
        myResult = output;
    }





    class HTTPConnection1 extends AsyncTask<String, Void, String> {
        String result;
        String url;
        String busNumber;
        public AsyncResponse delegate = null;
        
        @Override
        protected String doInBackground(String... params) {
            url = params[0];
            busNumber = params[1];
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("id", busNumber));
                nameValuePairs.add(new BasicNameValuePair("message", "msg"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse httpResponse = httpclient.execute(httppost);
                InputStream inputStream = httpResponse.getEntity().getContent();
                //HTTPResult.setText("result3");
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                //HTTPResult.setText("result4");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                //HTTPResult.setText("result5");
                StringBuilder stringBuilder = new StringBuilder();
                //HTTPResult.setText("result6");
                String bufferedStrChunk = null;

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


                result = stringBuilder.toString();
                //result= "Sandeep";

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

        @Override
        protected void onPostExecute(String bitmap) {
            super.onPostExecute(bitmap);
            //HTTPResult.setText(result);
            delegate.processFinish(bitmap);

        }

    }
}
    public interface AsyncResponse  {
        void processFinish(String output);
    }

  

my motive is not to set text into HTTPResult, but to set the string myResult; I am testing values with HTTPResult

pintu
  • 11
  • 4
  • `HTTPResult.setText(myResult);` That is too early. The asynctask in not ready yet. Put that statement in onPostExecute. – blackapps Jan 09 '21 at 20:43

1 Answers1

0

This problem is because AsyncTask do the task in background thread, so when you try to set the result in your EditText the AsyncTask may not be finished yet, so your myResult will have the default value to fix that you can update your EditText in onPostExecute method and that the reason why this line work fine in onPostExecute

HTTPResult.setText(bitmap);

Edit: You can update myResult in onPostExecute but the problem is to know when the AsyncTask finished so you can solve this problem by using interface as Callback

Check this question to find example how to use interface as callback with AsyncTask

android asynctask sending callbacks to ui

And this a good tutorial about how to create callback with interface

https://www.tutorialspoint.com/Callback-using-Interfaces-in-Java

Edit 2: : move setText from onCreate to your processFinish function or you can check with log or toast to update ui when asynctask finished and push the value to your callback

@Override
public void processFinish(String output){
    myResult = output;
    HTTPResult.setText(myResult);
}
AmrDeveloper
  • 3,826
  • 1
  • 21
  • 30
  • my motive is not to set text into HTTPResult, but to set the string myResult; I am testing values with HTTPResult – pintu Jan 09 '21 at 20:03
  • you can set it in onPostExecute but the problem is to know when AsyncTask finished to start using myResult, you can use interface and create Callback to run when the AsyncTask is finished and inside it use your result – AmrDeveloper Jan 09 '21 at 20:06
  • I could not understand, can you show example? – pintu Jan 09 '21 at 20:08
  • `but the problem is to know when AsyncTask finished to start using myResult` That is no problem at all as it is finished when onPostExecute is called. No need for an interface. – blackapps Jan 09 '21 at 20:45
  • @blackapps yup it finishes when onPostExecute is called but I mean use interface to know from the onCreate that onPostExecute is called or not to start using myResult – AmrDeveloper Jan 09 '21 at 20:56
  • onCreate has long finished then. – blackapps Jan 09 '21 at 21:01
  • after adding interface and callback; incompatible type compiler error; see the original post; i have edited – pintu Jan 09 '21 at 21:34
  • You dont need to extends View.OnClickListener and you need to set it in AsyncTask constructor – AmrDeveloper Jan 09 '21 at 21:55
  • with interface and callback also, I am not getting the value;see the post; I have edited. – pintu Jan 10 '21 at 07:45
  • I edited the answer you need to move the set text to your callback function or use toast or log to check if the value is updated or not – AmrDeveloper Jan 10 '21 at 12:22