UPD:当我从数据库中获取时,我发现纬度和经度字段发生了一些不好的事情,例如它没有正确显示Toast
。
我在我的项目中使用Firebase数据库。它会为Firebase数据库保存包含附加信息的位置,我需要在地图上显示与该位置对应的标记。
然而,阅读根本不起作用。我已按照此guide将数据库定义为我的类中的字段,在onCreate
方法中添加了实例化并添加了ValueListener
。
DatabaseReference databaseEvents;
//some code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
databaseEvents = FirebaseDatabase.getInstance().getReference("events");
}
//somecode
databaseEvents.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// events.clear();
Toast.makeText(MapsActivity.this, "LUL", Toast.LENGTH_SHORT).show();
for (DataSnapshot event : dataSnapshot.getChildren()) {
Event e = event.getValue(Event.class);
events.add(e);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//here I'm trying to display the markers.
当我尝试输出events
的大小时,它总是打印0,因此它不会在地图上打印任何标记。
完整的代码在这里:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener, GoogleMap.OnInfoWindowClickListener {
private static final int PLACE_PICKER_REQUEST = 1;
private GoogleMap mMap;
private Button addEventBtn;
private PlacePicker.IntentBuilder builder;
private Place place;
private EditText editEventName;
private Spinner typeOfEvent;
private LatLng coordOfNewMarker;
private String nameOfNewMarker;
private String typeOfNewMarker;
private ViewGroup infoWindow;
private TextView infoTitle;
private TextView infoSnippet;
private Button infoButton1, infoButton2;
private OnInfoWindowElemTouchListener infoButtonListener1, infoButtonListener2;
DatabaseReference databaseEvents;
@Override
public void onClick(View v) {
place = null;
switch (v.getId()) {
case R.id.AddEventButton:
callPlacePicker();
break;
}
}
@Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(this, "Info window clicked",
Toast.LENGTH_SHORT).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
databaseEvents = FirebaseDatabase.getInstance().getReference("events");
}
@Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
addEventBtn = findViewById(R.id.AddEventButton);
final MapWrapperLayout mapWrapperLayout = findViewById(R.id.map_relative_layout);
mapWrapperLayout.init(mMap, getPixelsFromDp(MapsActivity.this, 39 + 20));
// We want to reuse the info window for all the markers,
// so let's create only one class member instance
this.infoWindow = (ViewGroup)getLayoutInflater().inflate(R.layout.custom_infowindow, null);
this.infoTitle = infoWindow.findViewById(R.id.nameTxt);
this.infoSnippet = infoWindow.findViewById(R.id.addressTxt);
this.infoButton1 = infoWindow.findViewById(R.id.btnOne);
this.infoButton2 = infoWindow.findViewById(R.id.btnTwo);
this.infoButtonListener1 = new OnInfoWindowElemTouchListener(infoButton1,
getResources().getDrawable(R.drawable.round_but_green_sel),
getResources().getDrawable(R.drawable.round_but_red_sel))
{
@Override
protected void onClickConfirmed(View v, Marker marker) {
Toast.makeText(MapsActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoButton1.setOnTouchListener(infoButtonListener1);
this.infoButtonListener2 = new OnInfoWindowElemTouchListener(infoButton2,
getResources().getDrawable(R.drawable.round_but_green_sel),
getResources().getDrawable(R.drawable.round_but_red_sel))
{
@Override
protected void onClickConfirmed(View v, Marker marker) {
Toast.makeText(MapsActivity.this, marker.getSnippet() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoButton2.setOnTouchListener(infoButtonListener2);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener1.setMarker(marker);
infoButtonListener2.setMarker(marker);
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
final ArrayList<Event> events = new ArrayList<>();
databaseEvents.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// events.clear();
Toast.makeText(MapsActivity.this, "LUL", Toast.LENGTH_SHORT).show();
for (DataSnapshot event : dataSnapshot.getChildren()) {
Event e = event.getValue(Event.class);
events.add(e);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
/*
This code was being used for SQLite database which now is not being used at all.
ArrayList<Double> lat = new ArrayList<>();
ArrayList<Double> lng = new ArrayList<>();
ArrayList<String> name = new ArrayList<>();
ArrayList<String> type = new ArrayList<>();
String query = "SELECT * FROM "+ "locations";
Cursor cursor = locations.getWritableDatabase().rawQuery(query,null);
while(cursor.moveToNext()){
lat.add(cursor.getDouble(cursor.getColumnIndex("lat")));
lng.add(cursor.getDouble(cursor.getColumnIndex("lng")));
name.add(cursor.getString(cursor.getColumnIndex("name")));
type.add(cursor.getString(cursor.getColumnIndex("type")));
}*/
// It always print 0.
Toast.makeText(MapsActivity.this, ((Integer) events.size()).toString(), Toast.LENGTH_SHORT).show();
int sz = events.size();
for(int i = 0; i < sz; i++) {
mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(events.get(i).getLatitude()), Double.parseDouble(events.get(i).getLongitude())))
.title(events.get(i).getName())
.snippet(events.get(i).getType()));
}
addEventBtn.setOnClickListener(this);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(this, data);
openDialog();
}
}
}
public void openDialog() {
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
editEventName = view.findViewById(R.id.editEventName);
typeOfEvent = view.findViewById(R.id.spinnerEventType);
final LocationsDB locations = new LocationsDB(this);
final StatsDB stats = new StatsDB(this);
try {
final String selected = typeOfEvent.getSelectedItem().toString();
}
catch (Exception e) {
Toast.makeText(this, "BAD", Toast.LENGTH_LONG);
}
builder.setView(view)
.setTitle("Create Event")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("create", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
coordOfNewMarker = place.getLatLng();
nameOfNewMarker = editEventName.getText().toString();
typeOfNewMarker = typeOfEvent.getSelectedItem().toString();
ContentValues event = new ContentValues();
Geocoder geocoder;
List<Address> addresses = new ArrayList<>();
geocoder = new Geocoder(getApplication(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(coordOfNewMarker.latitude,
coordOfNewMarker.longitude,
1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0);
event.put("lat", coordOfNewMarker.latitude);
event.put("lng", coordOfNewMarker.longitude);
event.put("name", nameOfNewMarker);
event.put("type", typeOfNewMarker);
event.put("address", address);
locations.insert(event);
addEvent(coordOfNewMarker.longitude, coordOfNewMarker.latitude, typeOfNewMarker, nameOfNewMarker, address);
ContentValues created = new ContentValues();
created.put("type", "created");
created.put("number", stats.get() + 1);
stats.update(created);
mMap.addMarker(new MarkerOptions().position(place.getLatLng()).title(editEventName.getText().toString())
.snippet(typeOfEvent.getSelectedItem().toString()));
}
});
builder.show();
}
public void callPlacePicker() {
builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static int getPixelsFromDp(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dp * scale + 0.5f);
}
private void addEvent(Double lng, Double ltd, String type, String name, String address) {
String id = databaseEvents.push().getKey();
Event e = new Event(id, lng.toString(), ltd.toString(), type, name, address);
databaseEvents.child(id).setValue(e);
Toast.makeText(this, "Event added!", Toast.LENGTH_LONG).show();
}
}