-3

I don't know why i'm getting null object reference on this code it seems fine but when i push the button and call the connect method it must give me the current location of user but it hangs and jump out, this is the code of my fragment class i already added the permissions to my Manifest file and the app has necessary permissions.

This is not a duplicated post i don't know why people here don't pay attention first in the duplicated post the answer is only for avoid the application to not hang even though here we already have the premission to access the location but it returns null.

public class GalleryFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

private EditText searchinput;
private Button searchbtn;
private JSONArray jsonArray;
private GoogleApiClient mLocationClient;
Location currentLocation;

@SuppressLint("ValidFragment")
public GalleryFragment(JSONArray array) {
    // Required empty public constructor
    this.jsonArray = array;
}

public GalleryFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
    if (mLocationClient == null) {
        mLocationClient = new GoogleApiClient.Builder(this.getContext())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
    searchinput = (EditText) rootView.findViewById(R.id.searchfld);
    searchbtn = (Button) rootView.findViewById(R.id.searchbtn);
    searchbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String input = searchinput.getText().toString();
            mLocationClient.connect();
        }
    });

    return rootView;
}


@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.i("salam", " Connected");

    if(ContextCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

        currentLocation = LocationServices.FusedLocationApi.getLastLocation(mLocationClient);
    }
    Log.i ("salam ", "   " + currentLocation.getLongitude());

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}

Log:

java.lang.NullPointerException: Attempt to invoke virtual method 'float android.location.Location.distanceTo(android.location.Location)' on a null object reference

Update: i fixed my problem by using the right way of access request

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) // grant the access from user when the activity created
            != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, // if the permission wasn't granted so ask for permission
                PERMISSION_ACCESS_FINE_LOCATION);
    } else { // if it was granted so get the location
        getLocation();
    }
}

Then:

@Override
    public void onConnected(@Nullable Bundle bundle) { // this is an override method which will execute when we connect to client service of google

        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { // if the permission was granted then get the location
            LocationServices.FusedLocationApi.requestLocationUpdates( // update the location of user
                    mLocationClient, mLocationRequest, this);
            // You need to ask the user to enable the permissions
            LocationTracker tracker = new LocationTracker(getContext()) { // here we use a custom library name Location Tracer on github: https://github.com/quentin7b/android-location-tracker
                @Override
                public void onLocationFound(@NonNull Location location) {
                    currentLocation = location;
                }

                @Override
                public void onTimeout() {
                }
            };
            tracker.startListening();

            if (currentLocation == null) {
                currentLocation = LocationServices.FusedLocationApi.getLastLocation(mLocationClient);
            }
        } else {
            Toast.makeText(getContext(),"The application need to access your location TURN ON the Location Service and Restart the application",Toast.LENGTH_LONG).show();
        }
    }

And finally manage the request by this method:

  @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        boolean allowed = true;
        switch (requestCode) {
            case PERMISSION_ACCESS_FINE_LOCATION:
                // If request is cancelled, the result arrays are empty.
                for (int res : grantResults) {
                    allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
                }
                break;
            default:
                allowed = false;
                break;
        }
        if (allowed) {
            getLocation();
        } else {
            Toast.makeText(getContext(),"You need to 'Enable' the location service", Toast.LENGTH_SHORT).show();
        }
    }

good luck and thanks

Blacksword
  • 331
  • 3
  • 17
  • @Rotwand why you made the post as duplicated when that's not the answer they just put an if statement to avoid the error it doesnt solve the problem the location is still null which it shouldn't – Blacksword Sep 15 '16 at 12:58
  • `i'm getting null object reference` Then, you're getting a NullPointerException. Hence, the dupe. Nothing to be surprised of – Phantômaxx Sep 15 '16 at 13:15
  • @Rotwang so? because of that all errors have the same reasons? what kind of explnation is that? i say i can't get the location and it gave me null the problem is "GETTING THE LOCATION" why? BECAUSE OF NULL? why it is null? = ANSWER – Blacksword Sep 15 '16 at 13:16
  • `because of that all errors have the same reasons?` **OF COURSE**. All NPEs are caused by the same issue. – Phantômaxx Sep 15 '16 at 13:19
  • i don't think so! btw the post which you duplicated has't gave any solution it just stop the error!! the solution is get the location and not give you null!, remove the duplicated please there is no relation between this post and that – Blacksword Sep 15 '16 at 13:23
  • All NPEs are caused by the very same issue. And have the very same solution. You don't think so, because you still didn't learn about NPEs - Which is what the duplicate post is meant to teach you. – Phantômaxx Sep 15 '16 at 13:24
  • The "last location" may be null as [the documentation](https://developer.android.com/training/location/retrieve-current.html#last-known) explains and you are supposed deal with it in your code. If the location is "null" i.e. unknown then you'll need to request a single location update or continuous location updates, whatever is your preference. – Markus Kauppinen Sep 15 '16 at 13:35
  • @MarkusKauppinen `@Nullable` with this there must be any problem and i already tested it on a mapview and it worked as i set a manual location in emulator but this still happens – Blacksword Sep 15 '16 at 13:38
  • When you boot up an Android device it doesn't automatically determine its location. If your app is the first one to ever ask for the "latest location", it will be unknown (and you receive `null`). Your app probably works, if you run Google Maps first and wait until it shows your correct location. Then the "latest location" has been determined as Google Maps requests location updates. Any `@Nullable` annotation or such isn't going to make the device determine its location. – Markus Kauppinen Sep 15 '16 at 13:51
  • yea you were right so you suggest to make a listener to get the location? i open google map and push the button of my location they i back to app and it works now. thanks man – Blacksword Sep 15 '16 at 14:00
  • Yep, use a listener. StackOverflow's [documentation section](http://stackoverflow.com/documentation/android/1837/location#t=201609151406096171107) has a growing collection of example codes. – Markus Kauppinen Sep 15 '16 at 14:08
  • 1
    Your question should be along the lines of "why am I getting a null return from..." as that is what you want to know. You should also describe what you've tried that _didn't_ fix the problem. – Brian White Sep 15 '16 at 17:19
  • the question is clear i'm asking why this code in that specific line is giving null i haven't ask something in general i was asking the logic of code is right but it gave null btw @MarkusKauppinen described it well – Blacksword Sep 15 '16 at 20:13
  • @AryaR. you haven't posted the LogCat so this question is really a guessing game. Always put LogCat in there. We can't know where the NPE occurred or why it happened, and so on. – Sufian Sep 20 '16 at 16:20
  • @Sufian look at my comments under my post the answer is there – Blacksword Sep 21 '16 at 07:04
  • LogCat must go in the question because comments do not have formatting feature. Besides, it is a pain to go through the comments to find full log. – Sufian Sep 21 '16 at 07:29
  • @Sufian have done – Blacksword Sep 21 '16 at 08:31
  • That ain't full LogCat. Put complete LogCat like you see in [this question](http://stackoverflow.com/questions/28577680/android-proguard-multidex-causes-classnotfoundexception). – Sufian Sep 21 '16 at 08:33

1 Answers1

0
if(ContextCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

    currentLocation = LocationServices.FusedLocationApi.getLastLocation(mLocationClient);
}
Log.i ("salam ", "   " + currentLocation.getLongitude());

Here you have accessed currentLocation outside if block and if block will be executed if and only if user has granted related permissions.

You are getting NullPointerException because user has not granted permission and currentLocation is not being assigned here.

if user has not granted permissions the you can request to those permissions alternatively using

ActivityCompat.requestPermissions(...)

and use callback to know if he has granted permissions and access your location data there.

@Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
}
Nikhil
  • 3,711
  • 8
  • 32
  • 43