LocationClient getLastLocation возвращает null в моем фрагменте

Я пытаюсь получить текущее местоположение с помощью LocationClient.getLastLocation(). Во-первых, я вызываю connect() для LocationClient в onCreate(), но это дало мне эту ошибку:

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.

Затем я вызываю connect() для LocationClient внутри onStart(). Это дает мне исключение NullPointerException.

Этот код отлично работал в действии, когда я вызываю connect() LocationClient в onCreate(). Однако он не работает во фрагменте. Где мне вызвать connect() для LocationClient?

Ближайший фрагмент.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

    }

}

ближайший_фрагмент.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>

person Figen Güngör    schedule 11.11.2014    source источник


Ответы (1)


Возможно, что метод doInBackground() для GetClosestKiosks вызывается до фактического подключения LocationClient.

Поэтому вы должны называть свой new GetClosestKiosks().execute() в подходящем месте. Таким образом, вы можете вызвать его внутри метода public void onConnected(Bundle arg0).

Кроме того, вы можете сделать mLocationClient.requestLocationUpdates() внутри метода doInBackground(), чтобы получить более свежее местоположение.

person ztan    schedule 12.11.2014
comment
Да, после отладки я понял это, ztan. Спасибо вам за ваши предложения. знак равно - person Figen Güngör; 13.11.2014