LocationClient getLastLocation returns null in my fragment

633 views Asked by At

I am trying to get current location with LocationClient.getLastLocation(). First, I call connect() for LocationClient in onCreate() but it gave me this error:

11-11 13:20:45.297: E/AndroidRuntime(9188): Caused by: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.

Then I call connect() for LocationClient inside onStart(). It gives me NullPointerException.

This code was working fine in an activity when I call connect() of LocationClient in onCreate(). However, it's not working in fragment. Where should I call connect() for LocationClient?

ClosestFragment.java:

public class ClosestFragment extends Fragment implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {

    private GoogleMap map;
    JSONArray jsonArray;
    JSONObject jsonObject, jsonObjResult;
    String json = "";
    ProgressDialog progress;
    Location mCurrentLocation;
    LocationClient mLocationClient;
    SharedPreferences sp;
    Double latitude = 0.0;
    Double longitude = 0.0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get back arguments
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Defines the xml file for the fragment
        View view = inflater.inflate(R.layout.closest_fragment, container, false);

        return view;
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    public static ClosestFragment newInstance() {
        ClosestFragment fragment = new ClosestFragment();

        return fragment;
    }

    @Override
    public void onStart() {

        super.onStart();

     // Connect the location client to start receiving updates
            mLocationClient = new LocationClient(getActivity(), this, this);
            mLocationClient.connect();  

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        FragmentManager fm = getChildFragmentManager();

        fm.beginTransaction()
                .replace(R.id.map, SupportMapFragment.newInstance()).commit();

        new GetClosestKiosks().execute();

    }

    private class GetClosestKiosks extends AsyncTask<Void, Void, Void> {


        String message="";

        ArrayList<KioskInfo> kioskList = new ArrayList<KioskInfo>();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {

            Location mCurrentLocation = mLocationClient.getLastLocation();
            if (mCurrentLocation != null) {
                latitude = mCurrentLocation.getLatitude();
                Log.e("ASD", "" + latitude);
                longitude = mCurrentLocation.getLongitude();
                Log.e("ASD", "" + longitude);
            } else {
                sp = PreferenceManager
                        .getDefaultSharedPreferences(getActivity());

                String lat = sp.getString("lat", "0");
                String lon = sp.getString("lon", "0");
                latitude = Double.parseDouble(lat);
                longitude = Double.parseDouble(lon);
            }   

            return null;
        }

        @Override
        protected void onPostExecute(Void args) {

        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnected(Bundle arg0) {
        mCurrentLocation = mLocationClient.getLastLocation();
        if (mCurrentLocation != null) {
            latitude = mCurrentLocation.getLatitude();
            longitude = mCurrentLocation.getLongitude();
            String msg = "Updated Location: "
                    + Double.toString(mCurrentLocation.getLatitude()) + ","
                    + Double.toString(mCurrentLocation.getLongitude());
            // Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
            Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
        } else {
            String lat = sp.getString("lat", "");
            String lon = sp.getString("lon", "");
            latitude = Double.parseDouble(lat);
            longitude = Double.parseDouble(lon);
        }

    }

    @Override
    public void onDisconnected() {
        // TODO Auto-generated method stub

    }

}

closest_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="20" >

    <FrameLayout
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="10" >
    </FrameLayout>

    <ListView
        android:id="@+id/kiosklist"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="10" >
    </ListView>

</LinearLayout>
1

There are 1 answers

1
ztan On BEST ANSWER

It is possible that the doInBackground() method of GetClosestKiosks is called before the LocationClient is actually connected.

So you should call your new GetClosestKiosks().execute() in a appropriate place. So you might call it inside the public void onConnected(Bundle arg0) method.

In addition, you might want to do mLocationClient.requestLocationUpdates() inside the doInBackground() method to get the more recent location.