-1

I want to return a specific string using ksoap2 web service in my android app.

Web service is returning the correct value but the set text is not getting updated once the task is complete. I need to do something (like trying to open the navigation drawer) then its getting updated. Any ideas??

My code is as follows

// Calling the async class

protected void onResume() {
            try {
                super.onResume();
                new RetrieveTimeWS().execute();
            }
            catch (Exception e)
            {
                Log.e("Current Time", e.getMessage());
            }
        }

Following is the Async Task

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

        protected String doInBackground(Void... params) {
            String datetime = "";
            try {

                TextView TVcurrentTime = (TextView) findViewById(R.id.DateTimeNow);

                TVcurrentTime.setText("Loading...");
                datetime = getDateTimeClass.getDateTime();
                TVcurrentTime.setText(datetime);

            } catch (Exception e) {
                Log.e("Async Task - GetDateTime ", e.getMessage());
            }
            return datetime;
        }
    }

The text field shows "Loading..." only till I touch any component on the screen. How can i change the textview to the required string after the web service returns the text.

Thanks in advance.

Laks.

2 Answers2

5

You can't interact with UI not from UI thread. AsyncTask has onPreExecute and PostExecute methods which called from UI thread and you can change UI in it.

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

    TextView TVcurrentTime = (TextView) findViewById(R.id.DateTimeNow);

    Exception e;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();        
        TVcurrentTime.setText("Loading...");
    }

    protected String doInBackground(Void... params) {
        String datetime = "";
        try {           
            datetime = getDateTimeClass.getDateTime();
        } catch (Exception e) {
            this.e = e;
            Log.e("Async Task - GetDateTime ", e.getMessage());
        }
        return datetime;
    }

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

        if (e != null) {
            TVcurrentTime.setText(s);
        }
    }
}
Bracadabra
  • 3,609
  • 3
  • 26
  • 46
0

You can not do any UI work in background thread. Do it in onPostExecute() method. This method runs on main thread. So, you can set text in this method.

Sayem
  • 4,891
  • 3
  • 28
  • 43