2016-08-15 3 views
0

Ich lese einige Daten aus der Firebase-Datenbank und das zurückgegebene Objekt ist null.FireBase-Datenbank Nullobjekt

Ich habe viele Möglichkeiten ausprobiert. Als ich (wie jetzt in Code) haben

marker(mMap.addMarker(new MarkerOptions().position(new LatLng(value, value2)).title("Mehehe"));) 

außerhalb onDataChange Verfahren tritt der Fehler auf. Aber wenn ich setzen Marker in onDataChange Methode und setzen Sie beide:

DatabaseReference myRef2 = database2.getReference("latitude"); 

und

DatabaseReference myRef = database.getReference("latitude"); 

, wenn die es ähnliche getRefrences kein Fehler vorhanden ist, aber wenn ich versuche,

DatabaseReference myRef2 = database2.getReference("latitude"); 

und

DatabaseReference myRef = database.getReference("longitude"); 

Dann kommen ähnliche Fehler wie wenn .addmarker ist außerhalb onDataChange Methode.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener, View.OnClickListener { 

    private ImageView imageView; 

    private GoogleMap mMap; 

    private GoogleApiClient client; 

    private DatabaseReference mDatabase; 

    private String email; 

    private double latitude; 
    private double longitude; 

    Double value; 
    Double value2; 

    @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); 

     FirebaseDatabase database = FirebaseDatabase.getInstance(); 
     DatabaseReference myRef = database.getReference("[email protected] - username"); 

     myRef.addValueEventListener(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot dataSnapshot) { 
       // This method is called once with the initial value and again 
       // whenever data at this location is updated. 
       String value = dataSnapshot.getValue(String.class); 
       Log.d("TAG", "Value is: " + value); 
       Toast.makeText(getApplicationContext(), value.toString(), Toast.LENGTH_SHORT).show(); 
      } 

      @Override 
      public void onCancelled(DatabaseError error) { 
       // Failed to read value 
       Log.w("TAG", "Failed to read value.", error.toException()); 
       Toast.makeText(getApplicationContext(), error.toException().toString(), Toast.LENGTH_SHORT).show(); 
      } 
     }); 

     client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); 

     imageView = (ImageView) findViewById(R.id.imageView); 
     imageView.setOnClickListener(this); 

    } 

    @Override 
    public void onClick(View view) { 

     if (view == imageView) { 

      Intent intent = new Intent(getApplicationContext(), ProfileSetUp.class); 
      startActivity(intent); 

     } 

    } 

    /** 
    * Manipulates the map once available. 
    * This callback is triggered when the map is ready to 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) { 
     mMap = googleMap; 

     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) { 
      // TODO: Consider calling 
      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 
      return; 
     } 

     mMap.setMyLocationEnabled(true); 

     LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     Criteria criteria = new Criteria(); 

     String provider = locationManager.getBestProvider(criteria, true); 

     Location myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); 
     //  Location myLocation = locationManager.getLastKnownLocation(provider); 

     mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

     //  double latitude = myLocation.getLatitude(); 
     //  double longitude = myLocation.getLongitude(); 

     latitude = myLocation.getLatitude(); 
     longitude = myLocation.getLongitude(); 

     mDatabase = FirebaseDatabase.getInstance().getReference(); 

     //  mDatabase.child("latitude").setValue(latitude); 
     //  mDatabase.child("longitude").setValue(longitude); 

     LatLng latLng = new LatLng(latitude, longitude); 

     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     mMap.animateCamera(CameraUpdateFactory.zoomTo(14)); 
     mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located")); 
     //  mMap.addMarker(new MarkerOptions().position(new LatLng(48.7352022, 19.1187914)).title("You are here!").snippet("Consider yourself located")); 


     FirebaseDatabase database2 = FirebaseDatabase.getInstance(); 
     DatabaseReference myRef2 = database2.getReference("latitude"); 

     myRef2.addValueEventListener(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot dataSnapshot) { 
       // This method is called once with the initial value and again 
       // whenever data at this location is updated. 
       value2 = dataSnapshot.getValue(Double.class); 
       Log.d("TAG", "Value is: " + value2); 
       //    Toast.makeText(getApplicationContext(), value3.toString(), Toast.LENGTH_SHORT).show(); 
       Toast.makeText(getApplicationContext(), value2.toString(), Toast.LENGTH_SHORT).show(); 

      } 

      @Override 
      public void onCancelled(DatabaseError error) { 
       // Failed to read value 
       Log.w("TAG", "Failed to read value.", error.toException()); 
       //    Toast.makeText(getApplicationContext(), error.toException().toString(), Toast.LENGTH_SHORT).show(); 
      } 

     }); 

     FirebaseDatabase database = FirebaseDatabase.getInstance(); 
     DatabaseReference myRef = database.getReference("longitude"); 

     myRef.addValueEventListener(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot dataSnapshot) { 
       // This method is called once with the initial value and again 
       // whenever data at this location is updated. 
       value = dataSnapshot.getValue(Double.class); 
       Log.d("TAG", "Value is: " + value); 

       //    mMap.addMarker(new MarkerOptions().position(new LatLng(value, value2)).title("Mehehe")); 
       Toast.makeText(getApplicationContext(), value.toString(), Toast.LENGTH_SHORT).show(); 
       Toast.makeText(getApplicationContext(), value2.toString(), Toast.LENGTH_SHORT).show(); 

      } 

      @Override 
      public void onCancelled(DatabaseError error) { 
       // Failed to read value 
       Log.w("TAG", "Failed to read value.", error.toException()); 
       //    Toast.makeText(getApplicationContext(), error.toException().toString(), Toast.LENGTH_SHORT).show(); 
      } 
     }); 

     mMap.addMarker(new MarkerOptions().position(new LatLng(value, value2)).title("Mehehe")); 

    } 

    @Override 
    public void onLocationChanged(Location location) { 



    } 
} 

Und es gibt Fehlermeldung: -

08-15 10:47:53.591 4280-4280/com.samo.facedatefb E/AndroidRuntime: FATAL EXCEPTION: main 
Process: com.samo.facedatefb, PID: 4280 
java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference 
    at com.samo.facedatefb.MapsActivity.onMapReady(MapsActivity.java:268) 
    at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source) 
    at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source) 
    at android.os.Binder.transact(Binder.java:385) 
    at xz.a(:com.google.android.gms.DynamiteModulesB:82) 
    at maps.ad.u$5.run(Unknown Source) 
    at android.os.Handler.handleCallback(Handler.java:815) 
    at android.os.Handler.dispatchMessage(Handler.java:104) 
    at android.os.Looper.loop(Looper.java:194) 
    at android.app.ActivityThread.main(ActivityThread.java:5549) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759) 

My Firebase Datenbank Snippet.

enter image description here

+0

Warum verwenden Sie mehrere Instanzen des gleichen FirebaseDatabase-Objekts? –

+0

Werden 'wert' und' wert2' nicht auf 'null' gesetzt, wenn Sie' mMap.addMarker (neue MarkerOptions(). Position (new LatLng (value, value2)). Title ("Mehehe")); ' ? – Poger

Antwort

0

Hier ist der Code, den Sie ein Modell zu verwenden, können Sie Ihre Breiten- und Längen

class Item { 
    private Double longitude; 
    private Double latitude; 

    public Item(Double longitude, Double latitude) { 
     this.latitude = latitude; 
     this.longitude = longitude; 
    } 

    public Double getLatitude() { 
     return latitude; 
    } 

    public Double getLongitude() { 
     return longitude; 
    } 
} 

Ihre Aktivität

class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener, View.OnClickListener { 

    //... 

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

     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); 

     LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     Criteria criteria = new Criteria(); 

     String provider = locationManager.getBestProvider(criteria, true); 

     Location myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); 
//  Location myLocation = locationManager.getLastKnownLocation(provider); 

     mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

//  double latitude = myLocation.getLatitude(); 
//  double longitude = myLocation.getLongitude(); 

     latitude = myLocation.getLatitude(); 
     longitude = myLocation.getLongitude(); 

     mDatabase = FirebaseDatabase.getInstance().getReference(); 

//  mDatabase.child("latitude").setValue(latitude); 
//  mDatabase.child("longitude").setValue(longitude); 

     LatLng latLng = new LatLng(latitude, longitude); 

     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     mMap.animateCamera(CameraUpdateFactory.zoomTo(14)); 
     mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located")); 
//  mMap.addMarker(new MarkerOptions().position(new LatLng(48.7352022, 19.1187914)).title("You are here!").snippet("Consider yourself located")); 

     DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference(); 

     mDatabase.addValueEventListener(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot dataSnapshot) { 

       Item myItem = dataSnapshot.getValue(Item.class); 
       mMap.addMarker(new MarkerOptions().position(new LatLng(myItem.getLat(), myItem.getLng())).title("Buhaahaha")); 
     // ... 
      } 

      @Override 
      public void onCancelled(DatabaseError databaseError) { 
      }); 
    } 
} 

Erklärung Es wird empfohlen, erhalten Klasse, die einen Standardkonstruktor enthält, der seine Felder initialisiert, die Anweisung Item myItem = dataSnapshot.getValue(Item.class); ruft automatisch den Konstruktor auf und initialisiert den entsprechenden Wert. Nun, woher weiß diese Aussage, welcher Wert von Latitude und was Longitude ist. Beachten Sie, dass wir in unserer Item Klasse unsere Felder so benannt haben, wie sie in unserer Firebase-Datenbank erscheinen. Das ist sehr wichtig, sie sollten genau so benannt werden. Jetzt, da wir unser Objekt initialisiert und Werte gesetzt haben, verwenden wir einfach Getter, um Werte aus der Datenbank zu erhalten.
Ihr Fehler.
Die Anweisung, die Sie geschrieben haben DatabaseReference myRef = database.getReference("longitude"); bedeutet "Holen Sie sich die Firebase-Datenbank Basisreferenz, dann erhalten Sie die untergeordnete 'Längengrad' Referenz". Also im Grunde seine Suche nach longitude Kind anstelle der longitude Wert.

Verwandte Themen