2017-10-12 66 views
0
public class MainActivity extends AppCompatActivity { 
    static ArrayList<String>places; 
    static ArrayList<String>lat; 
    static ArrayList<String>lng; 


    static ArrayAdapter arrayAdapter; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     ListView listView = (ListView)findViewById(R.id.listView); 
     lat = new ArrayList<String>(); 
     lng = new ArrayList<String>(); 


     SharedPreferences sharedPreference = this.getSharedPreferences("com.example.inbal.memorableplaces", Context.MODE_PRIVATE); 
     try { 
      places =(ArrayList<String>) ObjectSerializer.deserialize(sharedPreference.getString("Places",ObjectSerializer.serialize(new ArrayList<String>()))); 
      lat =(ArrayList<String>) ObjectSerializer.deserialize(sharedPreference.getString("Lat",ObjectSerializer.serialize(new ArrayList<String>()))); 
      lng =(ArrayList<String>) ObjectSerializer.deserialize(sharedPreference.getString("Lng",ObjectSerializer.serialize(new ArrayList<String>()))); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } 
     if (lat.size()==0) 
      lat.add(""); 
     if (lng.size()==0) 
      lng.add(""); 


     if (places.size()==0) 
      places.add("Add a new place"); 
     arrayAdapter= new ArrayAdapter(this,android.R.layout.simple_list_item_1,places); 

     listView.setAdapter(arrayAdapter); 
     listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 
        Intent intent = new Intent(getApplicationContext(), MapsActivity.class); 
        intent.putExtra("placeName", i); 
        startActivity(intent); 
      } 
     }); 
    } 
} 


    public class MapsActivity extends FragmentActivity implements 
    OnMapReadyCallback,GoogleMap.OnMapLongClickListener{ 

    private GoogleMap mMap; 
    LocationManager locationManager; 
    LocationListener locationListener; 

    @Override 
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
     super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
     if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){ 
      if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) 
       locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,10,locationListener); 


     } 

    } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_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); 

    } 


    /** 
    * Manipulates the map once available. 
    * This callback is triggered when the map is ready Gto be used. 
    * This is where we can add markers or lines, add listeners or move the camera. In this case, 
    * we just add a marker near Sydney, Australia. 
    * If Google Play services is not installed on the device, the user will be prompted to install 
    * it inside the SupportMapFragment. This method will only be triggered once the user has 
    * installed Google Play services and returned to the app. 
    */ 
    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     Intent intent = getIntent(); 
     int num = intent.getIntExtra("placeName", 0); 
     if (num == 0) { 
      mMap = googleMap; 
      mMap.setOnMapLongClickListener(this); 
      locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
      locationListener = new LocationListener() { 
       @Override 
       public void onLocationChanged(Location location) { 
        LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude()); 
        mMap.clear(); 
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15)); 
       } 

       @Override 
       public void onStatusChanged(String s, int i, Bundle bundle) { 
       } 

       @Override 
       public void onProviderEnabled(String s) { 

       } 

       @Override 
       public void onProviderDisabled(String s) { 

       } 
      }; 


      if (Build.VERSION.SDK_INT < 23) 
       locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 10, locationListener); 
      else { 
       if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) 
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 20, 10, locationListener); 
       else 
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); 

      } 


     } 
     else { 
      String lat = MainActivity.lat.get(num); 
      String lng = MainActivity.lng.get(num); 
      LatLng location= new LatLng(Double.parseDouble(lat),Double.parseDouble(lng)); 
      mMap.moveCamera(CameraUpdateFactory.newLatLng(location)); 
     } 

    } 

    @Override 
    public void onMapLongClick(LatLng latLng) 
    { 
     Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); 
     try { 
      List<Address> listAddress = geocoder.getFromLocation(latLng.latitude,latLng.longitude,1); 
      String address = ""; 

      if (listAddress!=null && listAddress.size()>0) { 
       if (listAddress.get(0).getLocality() != null) { 
        address+=listAddress.get(0).getLocality(); 
        if (listAddress.get(0).getThoroughfare() != null) 
         address=address+", "+listAddress.get(0).getThoroughfare(); 
         if (listAddress.get(0).getSubThoroughfare() != null) 
          address=address +" "+listAddress.get(0).getSubThoroughfare(); 
       } 
       mMap.clear(); 
       mMap.addMarker(new MarkerOptions().position(latLng).title(address)); 
      } 
       MainActivity.places.add(address); 
       MainActivity.lat.add(Double.toString(latLng.latitude)); 
       MainActivity.lng.add(Double.toString(latLng.longitude)); 
       SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.inbal.memorableplaces",Context.MODE_PRIVATE); 
      sharedPreferences.edit().putString("Places",ObjectSerializer.serialize(MainActivity.places)).apply(); 
      sharedPreferences.edit().putString("Lat",ObjectSerializer.serialize(MainActivity.lat)).apply(); 
      sharedPreferences.edit().putString("Lng",ObjectSerializer.serialize(MainActivity.lng)).apply(); 
      MainActivity.arrayAdapter.notifyDataSetChanged(); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

嘿,我建立一個應該保存位置的項目。唯一的問題是,我按下位置​​並保存他後,我不能再次顯示位置。 行mMap.moveCamera(CameraUpdateFactory.newLatLng(location));使應用程序崩潰,因爲它說不能移動由LatLng的地圖

顯示java.lang.NullPointerException:試圖調用虛擬方法無效 com.google.android.gms.maps.GoogleMap.moveCamera(com.google。 android.gms.maps.CameraUpdate)」 對空對象引用

回答

1

那是因爲你設置只有當條件num == 0滿足變量mMap

你的代碼更改爲:

@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 
    Intent intent = getIntent(); 
    int num = intent.getIntExtra("placeName", 0); 
    if (num == 0) { 
     //.... 
    } else { 
     //.... 
    } 
}