0

can you help me. i have an error in my code with a boolean isFromMockProvider() on a null object reference. this problem occurs when the gps on my provider is slow can you guys help me with dealing with the error

here is my code:

GetLocation getLocation = new GetLocation(getApplicationContext());
        Location location = getLocation.getLocation();
        boolean isMockLocation = location.isFromMockProvider();
        if (isMockLocation==true){
            showDialog();
        }
        else {
            tesmock.setText("No Use Mock ");
        }

3 Answers3

0

Your question is lacking quite a bit of context, so this involves some guess work:

What's probably happening is that when your gps is slow, getLocation.getLocation() returns null rather than a Location object, so trying to call location.isFromMockProvider() throws a NullPointerException.

The best way to solve this would be to check whether location is null before calling that function:

Location location = getLocation.getLocation();
if(location!=null){
    boolean isMockLocation = location.isFromMockProvider();
    //the stuff you then do with isMockLocation
} else{
    //display an error message or something saying the GPS is too slow
}
Itisdud
  • 41
  • 7
  • variable isMockLocation is never used – WILLHARTICER KARTIKA DAELI Jan 23 '22 at 16:49
  • It isn't as of current because I didn't fully copy and paste your code - of course you'd need to have the logic using isMockLocation after the declaration, where in my example I simply put a "the stuff you then do with isMockLocation". – Itisdud Jan 23 '22 at 17:00
0

Is it like this? I'm sorry because I'm a beginner

 Location location = getLocation.getLocation();
        if(location!=null){
            boolean isMockLocation = location.isFromMockProvider();
            if (isMockLocation==true){
                showDialog();
            }
            else {
                tesmock.setText("No Use Mock ");
            }
        } else{
            //display an error message or something saying the GPS is too slow
        }
0

You are using 2 If statements

GetLocation getLocation = new GetLocation(getApplicationContext());
    Location location = getLocation.getLocation();
if (location!=null){
    boolean isMockLocation = location.isFromMockProvider();
    if (isMockLocation==true){
        showDialog();
    }
    else {
        tesmock.setText("No Use Mock ");
    }
} else { //show Here a dialog saying GPS is slow or Something like this
}
Ninja
  • 11
  • 1