Search code examples
androidgetter-setterandroid-jobscheduler

Getter and Setter is not working in JobScheduler


I get into an issue which I am not able to figure out. I had used getter and setter for a string type longitude which is set in onLocationChanged() method of location provider(which is changing its value as expected) and the getter is supposed to be used in onStartJob() of JobService. However the getter is always null, although the value in setter part keeps changing.

public class MyJobService extends JobService
        implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
{
    String latitude;
    String longitude;

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getLongitude() {
        return longitude;
    }

        @Override
    public boolean onStartJob(JobParameters jobParameters) {
        Toast.makeText(this,"MyJobService.onStartJob()",Toast.LENGTH_SHORT).show();

        Log.e("token", "Start Job Called");
        setUpLocationClientIfNeeded();
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(10000);
        mLocationRequest.setFastestInterval(10000);
        Log.e("longitude", getLongitude() + "zz"); // this value is always null

        return false;
    }

        @Override
    public void onLocationChanged(Location location) {
        Log.e("token",location.getLatitude()+""+location.getLongitude());
        Toast.makeText(this, location.getLatitude()+" "+location.getLongitude()+ "", Toast.LENGTH_SHORT).show();
        setLongitude(location.getLongitude() + "");
        Log.e("longitude inside location change", getLongitude() + "zz");
        // this value keeps changing, however it is not affecting the getLongitude method in onStartJob()
    }
}

Solution

  • I don't know much about job schedulers but by seeing your code, If your onLocationChanged is working fine and it is updating the value of longitude properly then you should just make your variable static.

    instead of

    String latitude;
    String longitude;
    

    use

    public static String latitude;
    public static String longitude;
    

    This way, you don't even need to use getters and setters. One more thing is you should avoid using getters and setters in android. Instead you should directly make your variables public static and access them directly for better performance.