androidandroid-loadermanagerasynctaskloader

How to delay method call until another method been done first


I'm using loader to fetch data from the internet and GoogleApiClient to get the user location i pass a string url with location to the loader constructor ,onCreateLoader method called before onLocationChanged method that get the user location as an object

The problem is i need onLocationChanged method to return the location first to be able to pass a correct url to the onCreateLoader method. So, is there any way to run onLocationChanged method first or delay the loader on create method

onCreateLoader code

    @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 code

 @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 code

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

Log output


Solution

  • why don't you just call the loader from inside of onLocationChanged?

    void onLocationChanged(Location location) {
        if (location != null) {
            getLoaderManager().initLoader(0, null, this);
        }
    }
    

    alternatively you can run

    getLoaderManager().restartLoader(0, null, this);
    

    inside of onLocationChanged()