2016-03-08 45 views
2

我正在開發一個應用程序,其中onLongClick將標記放到Google地圖上。我的問題是應用程序關閉時保存這些標記。將谷歌地圖標記保存到Android工作室的SharedPreferences中

我已經使用Shared Preference來保存lat和lng的值,並在應用程序重新啓動時加載這些值。但是,當我將這些值傳遞給一個方法來創建一個標記時,錯誤貓說我正試圖調用一個空引用的方法。

任何幫助將不勝感激。請找到下面的代碼。

public class SecondMaps extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener { 

    private GoogleMap mMap; 
    EditText addressEditText; 
    String title; 
    LatLng position1; 

    SharedPreferences sharedPreferences; 
    int locationCount; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_second_maps); 
     // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 


     // Opening the sharedPreferences object 
     sharedPreferences = getSharedPreferences("location", 0); 

     // Getting number of locations already stored 
     locationCount = sharedPreferences.getInt("locationCount", 0); 


     // If locations are already saved 
     if (locationCount != 0) { 

      String lat = ""; 
      String lng = ""; 

      // Iterating through all the locations stored 
      for (int i = 0; i < locationCount; i++) { 

       // Getting the latitude of the i-th location 
       lat = sharedPreferences.getString("lat" + i, "0"); 

       // Getting the longitude of the i-th location 
       lng = sharedPreferences.getString("lng" + i, "0"); 


       Toast.makeText(this, lat + "," + lng, Toast.LENGTH_LONG).show(); 

       double lat3 = Double.valueOf(lat).doubleValue(); 
       double lng3 = Double.valueOf(lng).doubleValue(); 

       position1 = new LatLng(lat3, lng3); 
       drawMarker(position1); 
      } 

     } 

    } 


    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 
     mMap.setOnMapLongClickListener(this); 
     mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); 
     if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      return; 
     } 
     mMap.setMyLocationEnabled(true); 
     mMap.setTrafficEnabled(true); 
     mMap.getUiSettings().setZoomControlsEnabled(true); 

     LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     Criteria criteria = new Criteria(); 

     Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false)); 
     if (location != null) { 
      mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
        new LatLng(location.getLatitude(), location.getLongitude()), 13)); 


      CameraPosition cameraPosition = new CameraPosition.Builder() 
        .target(new LatLng(location.getLatitude(), location.getLongitude()))  // Sets the center of the map to location user 
        .zoom(17)     // Sets the zoom 
        .bearing(90)    // Sets the orientation of the camera to east 
          // Sets the tilt of the camera to 30 degrees 
        .build();     // Creates a CameraPosition from the builder 
      mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); 

     } 
    } 

    public void homeClick(MenuItem item) { 
     startActivity(new Intent(this, Home.class)); 
    } 

    public void mapClick(MenuItem item) { 
     startActivity(new Intent(this, SecondMaps.class)); 
    } 

    public void settingsClick(MenuItem item) { 
     startActivity(new Intent(this, Settings.class)); 
    } 

    @Override 
    public void onMapLongClick(LatLng latLng) { 

     addressEditText = (EditText) findViewById(R.id.editTextAddMarker); 
     title = addressEditText.getText().toString(); 

     if (title.length() > 2) { 
      MarkerOptions markerOpt1 = new MarkerOptions() 
        .title(title) 
        .anchor(0.5f, 0.5f); 
      markerOpt1.position(latLng); 
      mMap.addMarker(markerOpt1); 
      Toast.makeText(this, "Reminder Added", Toast.LENGTH_LONG).show(); 

      addressEditText.setText(""); 

      locationCount++; 

      /** Opening the editor object to write data to sharedPreferences */ 
      SharedPreferences.Editor editor = sharedPreferences.edit(); 

      // Storing the latitude for the i-th location 
      editor.putString("lat" + Integer.toString((locationCount - 1)), Double.toString(latLng.latitude)); 

      // Storing the longitude for the i-th location 
      editor.putString("lng" + Integer.toString((locationCount - 1)), Double.toString(latLng.longitude)); 

      // Storing the count of locations or marker count 
      editor.putInt("locationCount", locationCount); 


      /** Saving the values stored in the shared preferences */ 
      editor.commit(); 

     } else if (title.length() < 1) { 
      Toast.makeText(this, "Enter Reminder", Toast.LENGTH_LONG).show(); 
     } 
    } 
    private void drawMarker(LatLng point){ 
     // Creating an instance of MarkerOptions 
     MarkerOptions markerOptions = new MarkerOptions(); 

     // Setting latitude and longitude for the marker 
     markerOptions.position(point); 

     // Adding marker on the Google Map 
     mMap.addMarker(markerOptions); 
    } 

    public void clearMarker(View view) { 
     // Opening the editor object to delete data from sharedPreferences 
     SharedPreferences.Editor editor = sharedPreferences.edit(); 

     // Clearing the editor 
     editor.clear(); 

     // Committing the changes 
     editor.commit(); 
    } 
} 

錯誤:

java.lang.RuntimeException: Unable to start activity ComponentInfo{conenterprize.remintherefv/conenterprize.remintherefv.SecondMaps}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference 

回答

3

不要試圖與谷歌地圖在onCreate或其他一些生命週期開始相互作用的方法,因爲一旦它被添加在地圖是不會立即準備好作爲佈局。

取而代之,在onMapReady方法中繪製標記。

+1

非常感謝! –

+0

很高興我可以幫助:)請問你能接受答案嗎? – tknell

+0

沒問題,完成! –