简体   繁体   中英

AsyncTask returns null after calling it in another Activity

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) wich 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 dont know why, i was trying a lot of things but i cant reach the date value..

thanks

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM