0

LocationClient.getLastLocation()을 사용하여 현재 위치를 가져 오려고합니다. 첫째,에서 onCreate()에서 LocationClient에 대한 connect()를 호출하지만 나에게이 오류 준 :() ONSTART 내부 ​​LocationClient에 대한LocationClient getLastLocation 내 조각에 null을 반환합니다.

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. 

가 그럼 난 (연결 통화). 그것은 나에게 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> 

답변

2

LocationClient 실제로 접속되기 전에 GetClosestKiosksdoInBackground()의 메소드를 호출하는 것도 가능하다.

따라서 new GetClosestKiosks().execute()으로 전화해야합니다. 따라서 public void onConnected(Bundle arg0) 메소드 내부에서 호출 할 수 있습니다.

또한 최신 위치를 얻으려면 doInBackground() 방법을 사용하여 mLocationClient.requestLocationUpdates()을 수행 할 수 있습니다.

+0

그래, 디버깅 후 나는 그걸 알아 냈어. 제안 해 주셔서 감사합니다. =) –