LocationClient getLastLocation在我的片段中返回null

时间:2014-11-11 11:25:42

标签: android android-fragments currentlocation location-client

我正在尝试使用LocationClient.getLastLocation()获取当前位置。首先,我在onCreate()中为LocationClient调用connect(),但它给了我这个错误:

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.

然后我在onStart()中调用了LocationClient的connect()。它给了我NullPointerException。

当我在onCreate()中调用LocationClient的connect()时,此代码在一个活动中运行正常。但是,它不是片段式的。我应该在哪里为LocationClient调用connect()?

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 个答案:

答案 0 :(得分:2)

doInBackground()实际连接之前,可能会调用GetClosestKiosks LocationClient方法。

因此,您应该在适当的地方致电new GetClosestKiosks().execute()。所以你可以在public void onConnected(Bundle arg0)方法中调用它。

此外,您可能希望在mLocationClient.requestLocationUpdates()方法中执行doInBackground()以获取更新的位置。