0

I want to move my AsyncTask String value to another class with my constructor, my asynctask class is this

GetTiempoGoogle.class

public class GetTiempoGoogle extends AsyncTask<Void, Void, Void> {

    private Context context;
     String dateStr;

    @Override
    protected Void doInBackground(Void... voids) {
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(new HttpGet("https://google.com/"));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
                dateStr = response.getFirstHeader("Date").getValue();
                Date startDate = df.parse(dateStr);
                dateStr = String.valueOf(startDate.getTime()/1000);
                //Here I do something with the Date String

            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        }catch (ClientProtocolException e) {
            Log.d("Response", e.getMessage());
        }catch (IOException e) {
            Log.d("Response", e.getMessage());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
    // can use UI thread here
    protected void onPostExecute(final Void unused) {



    }

    public String getDateStr() {
        return dateStr;
    }
}

I have my getter there (getDateStr) which will return a google time date, so I need to access this value in my other class, what I did is this

MyActivity.class

GetTiempoGoogle Uconexion = new GetTiempoGoogle();
        Uconexion.execute();
        String Uconexionapp = Uconexion.getDateStr();
        Log.e("UconexionApp",""+Uconexionapp);

it seems that when I try to get the value is null... and I don't know why, I was trying a lot of things but I can't reach the date value.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • 1
    you need callback mechanism for this (from `onPostExecute`), it takes time to execute the background task , won't return result instantly – Pavneet_Singh Nov 23 '17 at 15:06
  • That is because you're setting the string asynchronously. So when you access it, it's null because the connection hasn't returned a result yet. Anyways, the approach you have is wrong, as mentioned above you should use the onPostExecute. check https://stackoverflow.com/questions/9963691/android-asynctask-sending-callbacks-to-ui – riadrifai Nov 23 '17 at 15:13

1 Answers1

1

When you are trying to get value it's still being computed. You need to wait until http request finishes, return result from the doInBackground method and consume in the onPostExecute method.

Here is the simplified sample tailored for your code:

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

    interface Callback {

        void onTaskFinished(String result);

        void onTaskFailed(Throwable error);
    }

    private final Callback callback;
    private final HttpClient httpClient;

    private MyTask(Callback callback, HttpClient httpClient) {
        this.callback = callback;
        this.httpClient = httpClient;
    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            HttpResponse response = httpClient.execute(new HttpGet("https://google.com/"));
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
                Date startDate = df.parse(response.getFirstHeader("Date").getValue());
                return String.valueOf(startDate.getTime() / 1000);
            } else {
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (Throwable error) {
            callback.onTaskFailed(error);
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
            callback.onTaskFinished(result);
        }
    }
}

And how it can be used in an Activity:

public class MainActivity extends AppCompatActivity implements MyTask.Callback {

    private MyTask mTask;
    private HttpClient mClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mClient = new DefaultHttpClient();
        mTask = new MyTask(this, mClient);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTask.cancel(true);
    }

    @Override
    public void onTaskFinished(String result) {
        // do whatever you want in activity with the result
    }

    @Override
    public void onTaskFailed(Throwable error) {
        // warn user about the error
    }

}

Or you can do the same stuff using an embedded class:

public class MainActivity extends AppCompatActivity {

    private MyTask mTask;
    private HttpClient mClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mClient = new DefaultHttpClient();
        mTask = new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... voids) {
                try {
                    HttpResponse response = httpClient.execute(new HttpGet("https://google.com/"));
                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
                        Date startDate = df.parse(response.getFirstHeader("Date").getValue());
                        return String.valueOf(startDate.getTime() / 1000);
                    } else {
                        response.getEntity().getContent().close();
                        throw new IOException(statusLine.getReasonPhrase());
                    }
                } catch (Throwable error) {
                    return null;
                }
            }

            @Override
            protected void onPostExecute(String result) {
                // handle the result here
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTask.cancel(true);
    }

}
The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49