【问题标题】:AsyncTask returns null after calling it in another ActivityAsyncTask 在另一个 Activity 中调用后返回 null
【发布时间】:2018-05-07 14:13:21
【问题描述】:

我想用我的构造函数将我的 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);

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

【问题讨论】:

  • 这个需要回调机制(来自onPostExecute),执行后台任务需要时间,不会立即返回结果
  • 那是因为你正在异步设置字符串。所以当你访问它时,它是空的,因为连接还没有返回结果。无论如何,您的方法是错误的,如上所述,您应该使用 onPostExecute。检查stackoverflow.com/questions/9963691/…

标签: java android string android-asynctask


【解决方案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);
        }
    }
}

以及如何在 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
    }

}

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

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

}

【讨论】:

  • 你能解释一下 onPostExecute 方法该怎么做吗?谢谢
  • 我需要解决方案而不是建议
  • @ArmandoBarreda,我添加了几个样本。抱歉回复晚了
猜你喜欢
  • 1970-01-01
  • 2019-10-23
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
  • 2017-12-22
  • 1970-01-01
  • 2016-08-07
  • 1970-01-01
相关资源
最近更新 更多