【发布时间】: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