AsyncTask在另一个Activity中调用后返回null

时间:2017-11-23 15:02:59

标签: java android string android-asynctask

我想用我的构造函数将我的AsyncTask String值移动到另一个类,我的asynctask类是这个

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;
    }
}

我有我的getter(getDateStr)将返回谷歌时间日期,所以我需要在我的其他课程中访问此值,我做的是这个

MyActivity.class

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

似乎当我试图获得该值为空时...我不知道为什么,我尝试了很多东西,但我无法达到日期值..

感谢

1 个答案:

答案 0 :(得分:1)

当你想要获得价值时,它仍在计算中。您需要等到http请求完成,返回doInBackground方法的结果并使用onPostExecute方法。

以下是为您的代码量身定制的简化示例:

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);
        }
    }
}

如何在活动中使用它:

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
    }

}

或者你可以使用嵌入式类做同样的事情:

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);
    }

}