我将Yahoo天气库添加到m项目中。然后我尝试将YahooWeatherInfoListener实现为主片段。
有一个问题。
在AsyncTask
内,我无法将YahooWeatherInfoListener
投射到片段中。
我认为我在AsncTask中做错了。请看一下:
import zh.wang.android.apis.yweathergetter4a.WeatherInfo;
import zh.wang.android.apis.yweathergetter4a.YahooWeather;
import zh.wang.android.apis.yweathergetter4a.YahooWeather.SEARCH_MODE;
import zh.wang.android.apis.yweathergetter4a.YahooWeatherInfoListener;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class HomeFragment extends Fragment implements YahooWeatherInfoListener {
public HomeFragment(){}
private TextView Temperature;
private YahooWeather mYahooWeather = YahooWeather.getInstance(5000, 5000, true);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Temperature = (TextView) rootView.findViewById(R.id.txtLabel);
new searchByGPS().execute();
return rootView;
}
private class searchByGPS extends AsyncTask<Void, Void, Void>{
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... unused) {
mYahooWeather.setNeedDownloadIcons(true);
mYahooWeather.setSearchMode(SEARCH_MODE.GPS);
mYahooWeather.queryYahooWeatherByGPS(getActivity().getApplicationContext(), (YahooWeatherInfoListener) this);
return null;
}
protected void onPostExecute(Void unused) {
}
}
@Override
public void gotWeatherInfo(WeatherInfo weatherInfo) {
// TODO Auto-generated method stub
Temperature.setText(weatherInfo.getCurrentTempC());
}
}
答案 0 :(得分:2)
那是因为
(YahooWeatherInfoListener) this
this
指的是AsyncTask
。相反,您需要使用:
(YahooWeatherInfoListener) HomeFragment.this
实现这一目标的更简洁方法是:
private class SearchByGPSTask extends AsyncTask<Void, Void, Void>{
private YahooWeatherInfoListener mListener;
public SearchByGPSTask( YahooWeatherInfoListener listener ) {
super();
mListener = listener;
}
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... unused) {
mYahooWeather.setNeedDownloadIcons(true);
mYahooWeather.setSearchMode(SEARCH_MODE.GPS);
mYahooWeather.queryYahooWeatherByGPS(getActivity().getApplicationContext(), mListener );
return null;
}
protected void onPostExecute(Void unused) {
}
}
(注意:类通常是大写的,更好的名词 - “searchByGPS”听起来像一个方法,而“SearchByGPSTask”表示它是一个意味着做某事的类。)
答案 1 :(得分:1)
protected Void doInBackground(Void... unused) {
mYahooWeather.setNeedDownloadIcons(true);
mYahooWeather.setSearchMode(SEARCH_MODE.GPS);
mYahooWeather.queryYahooWeatherByGPS(getActivity().getApplicationContext(), (YahooWeatherInfoListener) HomeFragment.this);
return null;
}
您必须将this
更改为HomeFragment.this
,因为它与您的AsyncTask直接相关。
答案 2 :(得分:0)
使用此行mYahooWeather.queryYahooWeatherByGPS(getActivity().getApplicationContext(), (YahooWeatherInfoListener) this);
,您尝试将AsyncTask
转换为YahooWeatherInfoListener
。请改用HomeFragment.this