2017-01-02 56 views
0

我已經在片段中實現了映射。我想要當前位置,所以我已經實現了返回位置的位置監聽器。我打電話給api,讓所有商家都拿到商家名單。從那個列表中我得到了商人的經緯度。當試圖瀏覽片段時在getActivity()上獲取空指針異常

當我第一次啓動應用程序,並去在家庭活動,添加地圖的SearchMerchant片段。我可以看到當前的位置和標記,如果我回到另一個片段,再次來到SearchMerchant片段,當我嘗試檢查網絡連接時,在onLocationChanged方法中,我得到空指針異常。

Process: com.kiranacustomerapp, PID: 9934 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference 
                      at com.kiranacustomerapp.helper.CommonUtils.isConnectedToInternet(CommonUtils.java:44)                   at com.kiranacustomerapp.Fragments.SearchMerchantFragment.onLocationChanged(SearchMerchantFragment.java:373) 
                     at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:297) 

CommonUtils類:

public static boolean isConnectedToInternet(Context context) { 

    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    if (manager != null) { 
     NetworkInfo[] info = manager.getAllNetworkInfo(); 
     if (info != null) { 
      for(int i=0;i<info.length;i++) { 
       if (info[i].getState() == NetworkInfo.State.CONNECTED) { 
        return true; 
       } 
      } 
     } 
    } 

    return false; 
} 

SearchMapFragment:

public class SearchMerchantFragment extends Fragment implements GetSearchedMerchantsAsyncTask.GetSearchedMerchantsCallBack,OnMapReadyCallback , GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{ 
    // TODO: Rename parameter arguments, choose names that match 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // getLocation(); 

     initializeLocationManager(); 
     requestLocation(); 

    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     View view = inflater.inflate(R.layout.fragment_search_merchant, container, false); 

     setUpUI(view); 


     return view; 
    } 


    public void setUpUI(View view) { 

     setUpMapIfNeeded(); 



    } 

    @Override 
    public void doPostExecute(ArrayList<Merchants> merchantsArrayList) { 

     merchantsList.clear(); 
     merchantsList.addAll(merchantsArrayList); 
     merchantsAdapter.notifyDataSetChanged(); 
    } 

    //get searched merchants 
    public void accessMerchants() { 
     if (CommonUtils.isConnectedToInternet(getContext())) { 
      new GetSearchedMerchantsAsyncTask(getActivity(), SearchMerchantFragment.this).execute(access_token, sessionUserId,String.valueOf(mLastLocation.getLatitude()),String.valueOf(mLastLocation.getLongitude())); 
     } else { 
      showAlert(String.valueOf(R.string.check_network)); 
     } 
    } 


    private void setUpMapIfNeeded() { 
     if (mGoogleMap == null) { 
      mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_fragment); 
      mapFragment.getMapAsync(this); 
      // getLocation(); 
     } 
    } 

    //setup map 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mGoogleMap = googleMap; 

     buildGoogleApiClient(); 

     mGoogleApiClient.connect(); 

    } 

    protected synchronized void buildGoogleApiClient() { 
     // Toast.makeText(getActivity(),"buildGoogleApiClient",Toast.LENGTH_SHORT).show(); 
     mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     // Toast.makeText(getActivity(),"onConnected",Toast.LENGTH_SHORT).show(); 

    } 

    @Override 
    public void onConnectionSuspended(int i) { 
     // Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     // Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show(); 
    } 


    private class LocationListener implements android.location.LocationListener { 

     private static final String TAG = "GPS"; 

     public LocationListener(String provider) { 
      Log.e(TAG, "LocationListener " + provider); 
      mLastLocation = new Location(provider); 
     } 

     @Override 
     public void onLocationChanged(Location location) { 
      Log.e(TAG, "onLocationChanged: " + location); 
      mLastLocation.set(location); 
      try { 

       if (mLastLocation != null) { 

        //place marker at current position 
        // mGoogleMap.clear(); 
        mLatLang = new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude()); 

        accessMerchants(); 

        MarkerOptions markerOptions = new MarkerOptions(); 
        markerOptions.position(mLatLang); 
        markerOptions.title(getString(R.string.position)); 
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)); 
        mMarker = mGoogleMap.addMarker(markerOptions); 

        CameraPosition cameraPosition = new CameraPosition.Builder().target(mLatLang).zoom(14).build(); 

        mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); 

        mLocationRequest = new LocationRequest(); 
        mLocationRequest.setInterval(5000); //5 seconds 
        mLocationRequest.setFastestInterval(3000); //3 seconds 
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 

        mGoogleMap.setMyLocationEnabled(true); 
        mGoogleMap.getUiSettings().setZoomControlsEnabled(true); 
        mGoogleMap.getUiSettings().setAllGesturesEnabled(true); 

        for (Merchants merchants : merchantsList) { 
         LatLng latLng = new LatLng(merchants.getLatitude(), merchants.getLongitude()); 
         MarkerOptions marker = new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).title(merchants.getKirana_name()); 
         Marker m = mGoogleMap.addMarker(marker); 
         markers.add(m); 
        } 
       } 
      } catch (SecurityException e) { 

      } 
     } 

     @Override 
     public void onProviderDisabled(String provider) { 
      Log.e(TAG, "onProviderDisabled: " + provider); 
     } 

     @Override 
     public void onProviderEnabled(String provider) { 
      Log.e(TAG, "onProviderEnabled: " + provider); 
     } 

     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 
      Log.e(TAG, "onStatusChanged: " + provider); 
     } 
    } 

    LocationListener[] mLocationListeners = new LocationListener[]{ 
      new LocationListener(LocationManager.GPS_PROVIDER), 
      new LocationListener(LocationManager.NETWORK_PROVIDER) 
    }; 
    private void initializeLocationManager() { 

     if (mLocationManager == null) { 
      mLocationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE); 
     } 
    } 

    public void requestLocation() { 

     try { 
      mLocationManager.requestLocationUpdates(
        LocationManager.NETWORK_PROVIDER, 0,0, 
        mLocationListeners[1]); 
     } catch (java.lang.SecurityException ex) { 

     } catch (IllegalArgumentException ex) { 

     } 

     try { 
      mLocationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER,0,0, 
        mLocationListeners[0]); 
     } catch (java.lang.SecurityException ex) { 

     } catch (IllegalArgumentException ex) { 

     } 

    } 

} 

我想要得到的位置一次,並調用異步任務來獲得商家列表。獲取位置後,我想停止獲取位置,現在當我調用onLocationChange方法中的異步任務時,只要位置發生變化,它就會開始調用異步任務。所以它經常發生。

這裏怎麼回事?請幫助,謝謝。

回答

0

您正在呼籲setUpUI(view);onCreateView()其中調用getLocation()。在您的getLocation()中,您致電getActivity()獲取LocationManager實例。 getActivity()返回null,因爲您在onCreateView()中調用該函數。

問題是你不應該在onCreateView()中調用getContext()getActivity(),因爲不能保證活動被創建,所以上下文將是空的。這種情況只發生在某個時間而不是所有時間。

注:你應該習慣沒有得到上下文onCreateView(),得到它onActivityCreated()

很簡單修復: 移動你的getLocation()呼叫onActivityCreated()這是在這種情況下,保證你得到它使用方面:)

+0

仍然收到空指針異常,並在地圖上我不能看到位置,如果從片段導航。 – Sid

0

檢查

CommonUtils.isConnectedToInternet(getActivity()) 
上下文以及所有的方法或線

看看是否getActivity()沒有返回你null。

移動您的getLocation();裏面的方法onActivityCreated()或應該在onConnect()中調用;

+0

仍然收到空指針異常,並在地圖上我不能看到位置,如果從片段導航 – Sid

相關問題