这里,Toast显示来自API的正确天气响应,但是当我将此响应返回给调用函数时,它给出null。实际上,来自API的响应需要一些时间,并且在从API获得实际响应之前返回null。
public String weatherStatus(String city) {
weatherMap.getCityWeather(city, new WeatherCallback() {
@Override
public void success(WeatherResponseModel weatherResponseModel) {
Weather weather[] = weatherResponseModel.getWeather();
weatherMain = weather[0].getMain();
Toast.makeText(this,weatherMain,Toast.LENGTH_LONG).show();
}
@Override
public void failure(String s) {
}
});
return weatherMain;
}
那么,如何等待Weather API的响应?
答案 0 :(得分:0)
我不知道您是如何尝试在AsyncTask中实现此功能的,但您可以按照以下方法进行操作。
public class RestManager extends AsyncTask<Void, Void, WeatherResponseModel> implements WeatherCallback{
private int mStatus;
private WeatherResponseModel mModel;
private String mError;
private Context mContext;
public RestManager(Context context){
mContext = context;
}
@Override
protected WeatherResponseModel doInBackground(Void... params) {
WeatherMap weatherMap = new WeatherMap(mContext, OWM_API_KEY);
weatherMap.getCityWeather(city, this);
mStatus = 0;
while(mStatus==0);//wait for response..
return mModel;
}
@Override
protected void onPostExecute(WeatherResponseModel weatherResponseModel) {
super.onPostExecute(weatherResponseModel);
if(mStatus==1){
//Success
Weather weather[] = weatherResponseModel.getWeather();
weatherMain = weather[0].getMain();
Toast.makeText(this,weatherMain,Toast.LENGTH_LONG).show();
}else{
//Error
}
}
@Override
public void success(WeatherResponseModel weatherResponseModel) {
mStatus = 1;
mModel = weatherResponseModel;
}
@Override
public void failure(String s) {
mStatus = -1;
mError=s;
}
}