我正在使用加载程序从互联网上获取数据, GoogleApiClient 获取用户位置,我将字符串网址传递给加载器构造函数,在 onLocationChanged 方法之前调用的 onCreateLoader 方法,该方法将用户位置作为对象
问题是我需要onLocationChanged方法首先返回该位置,以便能够将正确的url传递给onCreateLoader方法。那么,有没有办法先运行 onLocationChanged 方法或者在create方法上延迟加载器
onCreateLoader代码
@Override
public android.content.Loader<Adhan> onCreateLoader(int id, Bundle args) {
Log.v(LOG_TAG, "onCreateLoader invoked query here " + mQueryUrl);
if (mQueryUrl != null) {
return new PrayTimeLoader(getContext(), mQueryUrl);
}
return null;
}
onLocationChanged代码
@Override
public void onLocationChanged(Location location) {
mLocation = location;
makeQueryUrl();
Log.v(LOG_TAG, "latitude is " + location.getLatitude());
Log.v(LOG_TAG, "Longitude is " + location.getLongitude());
}
makeQueryUrl代码
private String makeQueryUrl() {
StringBuilder theQuery = new StringBuilder();
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
if (mLocation != null) {
String latitude = Double.toString(mLocation.getLatitude());
String longitude = Double.toString(mLocation.getLongitude());
theQuery.append("http://api.aladhan.com/timings/")
.append(ts)
.append("?latitude=")
.append(latitude)
.append("&longitude=")
.append(longitude)
;
Log.v(LOG_TAG, "our url for today is " + theQuery);
}
mQueryUrl = String.valueOf(theQuery);
return mQueryUrl;
}
记录输出
08-08 20:48:19.406 25518-25518 / com.example.worldwide.wzakerapp V / PrayerFragment:onCreateLoader这里调用查询null
08-08 20:48:19.406 25518-25518 / com.example.worldwide.wzakerapp V / PrayerFragment:onCreateLoader这里调用查询null
08-08 20:48:19.634 25518-25518 / com.example.worldwide.wzakerapp V / PrayerFragment:onConnected调用true
08-08 20:48:19.645 25518-25518 / com.example.worldwide.wzakerapp V / PrayerFragment:请求位置
08-08 20:48:19.652 25518-25518 / com.example.worldwide.wzakerapp V / PrayerFragment:纬度为30.8567497
08-08 20:48:19.652 25518-25518 / com.example.worldwide.wzakerapp V / PrayerFragment:经度为30.8001775
答案 0 :(得分:2)
为什么不从onLocationChanged内部调用加载器?
void onLocationChanged(Location location) {
if (location != null) {
getLoaderManager().initLoader(0, null, this);
}
}
或者你可以运行
getLoaderManager().restartLoader(0, null, this);
在onLocationChanged()
之内答案 1 :(得分:1)
听起来你正在使用LoaderManager。我不确定你在哪里初始化它,但是在捕获位置后尝试重新启动加载器:
@Override
public void onLocationChanged(Location location) {
mLocation = location;
makeQueryUrl();
Log.v(LOG_TAG, "latitude is " + location.getLatitude());
Log.v(LOG_TAG, "Longitude is " + location.getLongitude());
getLoaderManager().restartLoader(0, null, this);
}