Reputation: 89
Here is my target event :
refDatabase.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
LatLng newlocation = new LatLng(dataSnapshot.child("latitude").getValue(Double.class),dataSnapshot.child("longitude").getValue(Double.class));
nama = new String(dataSnapshot.child("nama").getValue(String.class));
kec = new String(dataSnapshot.child("kecamatan").getValue(String.class));
kab = new String(dataSnapshot.child("kebupaten").getValue(String.class));
googleMap.addMarker(new MarkerOptions().position(newlocation).title(nama+", "+kec+", "+kab));
}
});
How can I get the object newlocation
and put that in this event:
tampil.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
}
});
Upvotes: 2
Views: 1145
Reputation: 138824
You can achieve this, using a callback. Fist you need to create an interface:
public interface MyCallback {
void onCallback(LatLng newlocation);
}
Then you need to create a method that is actually getting the data from the database. This method should look like this:
public void readData(MyCallback myCallback) {
refDatabase.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
newlocation = new LatLng(dataSnapshot.child("latitude").getValue(Double.class),dataSnapshot.child("longitude").getValue(Double.class));
nama = new String(dataSnapshot.child("nama").getValue(String.class));
kec = new String(dataSnapshot.child("kecamatan").getValue(String.class));
kab = new String(dataSnapshot.child("kebupaten").getValue(String.class));
googleMap.addMarker(new MarkerOptions().position(newlocation).title(nama+", "+kec+", "+kab));
myCallback.onCallback(newlocation);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
}
In the end just simply call readData()
method and pass an instance of the MyCallback
interface as an argument in your onClick()
method like this:
tampil.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
readData(new MyCallback() {
@Override
public void onCallback(LatLng newlocation) {
//Do what you need to do with newlocation
}
});
}
});
For more informations, I recommend you see the anwser from this post and also take a look at this video.
Upvotes: 1
Reputation: 8715
You can use EventBus libray for this purpose: https://github.com/greenrobot/EventBus in three steps
Upvotes: 0