I have created an app that shows the list of bar locations by a marker on a map taken from a database on firebase.
each bar has a list of beverages.
what I wish to happen is that when a marker is clicked a new activity will open with the name of the bar selected at the top of the new activity
What i wish to happen is that when the marker is clicked it will open a new activity
//Declaration list of venues
List<Venue> venueList;
//onCreate method
venueList = new ArrayList<>();
mVenues.push().setValue(marker);
//onMapsReady method, gets the venues into the map
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mVenues.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot s : dataSnapshot.getChildren()){
Venue venue = s.getValue(Venue.class);
venueList.add(venue);
for (int i = 0; i < venueList.size(); i++)
{
LatLng latLng = new LatLng(venue.venueLat,venue.venueLong);
if (mMap != null) {
marker = mMap.addMarker(new MarkerOptions()
.position(latLng).title(venue.venueName));
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Marker Click Event
//CMarker click event to take user to purchase beverage
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener(){
public boolean onMarkerClick(Marker marker) {
String title = marker.getTitle();
{
for (int i = 0; i < venueList.size();) {
//getting the selected venue
Venue venue = venueList.get(i);
//creating an intent
Intent intent = new Intent(getApplicationContext(), viewbeverageActivity.class);
//putting venue name and id to intent
intent.putExtra(VENUE_ID, venue.getVenueId());
intent.putExtra(VENUE_NAME, venue.getVenueName());
//starting the activity with intent
startActivity(intent);
}
return false;
}
}
});
//Venue Class
package uk.ac.ferry_j2ulster.beerapp;
import com.google.firebase.database.IgnoreExtraProperties;
public class Venue {
private String venueId;
public String venueName;
private String venueType;
public double venueLat;
public double venueLong;
public Venue(){
}
public Venue(String venueId, String venueName, String venueType,double venueLat, double venueLong) {
this.venueId = venueId;
this.venueName = venueName;
this.venueType = venueType;
this.venueLat = venueLat;
this.venueLong = venueLong;
}
public String getVenueId() {
return venueId;
}
public String getVenueName() {
return venueName;
}
public String getVenueType() {
return venueType;
}
public double getVenueLong() { return venueLong;
}
public double getVenueLat() {return venueLat;
}
}
I hope to open a new activity with the bar that was selected as a title at the top
no errors, not sure how to start with this one
The problem is that you are using a loop to go through each Venue, and calling startActivity() for all venues.
Instead, define a HashMap that will map each Marker ID to a Venue ID:
Map<String, String> mMarkerMap = new HashMap<>();
Then, put an entry in the HashMap for each Marker:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot s : dataSnapshot.getChildren()){
Venue venue = s.getValue(Venue.class);
venueList.add(venue);
for (int i = 0; i < venueList.size(); i++)
{
LatLng latLng = new LatLng(venue.venueLat,venue.venueLong);
if (mMap != null) {
marker = mMap.addMarker(new MarkerOptions()
.position(latLng).title(venue.venueName));
//Added:
mMarkerMap.put(marker.getId(), venue.getVenueId());
}
}
}
}
Then, when the user taps a Marker, get the title and Venue ID from the Marker/HashMap, and send it to the new activity:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//...........
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String venueID = mMarkerMap.get(marker.getId());
String venueName = marker.getTitle();
Intent intent = new Intent(MapActivity.this, NewActivity.class);
intent.putExtra(VENUE_NAME, venueName);
intent.putExtra(VENUE_ID, venueID);
startActivity(intent);
return false;
}
});
}
In the new activity, simply get the title and Venue ID Strings passed in:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
String venueName = getIntent().getStringExtra(MapActivity.VENUE_NAME);
if (title != null) {
getSupportActionBar().setTitle(title);
}
String venueID = getIntent().getStringExtra(MapActivity.VENUE_ID);
if (venueID != null) {
//use venue ID to get the information about this venue
}
//.......
}
You need to pass venue information also to the activity :
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//...........
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String title = marker.getTitle();
Venue venue = NULL;
for(int i=0;i<venueList.size();i++)
{
if(venueList.get(i).getTitle().equal(title))
venue = venueList.get(i);
}
Intent intent = new Intent(MapActivity.this, NewActivity.class);
intent.putExtra("title", title);
intent.putExtra("venue",venue.toJSON());
startActivity(intent);
return false;
}
});
}
Make a toJSON() function in your venue class and also fromJSON() which will help you in sending venue data as well.
Related
I want to pass data between Activities using Intents. I can already send the data but the problem is that the data only contains the last item.
I'm not sure but I think the problem is with the for statement based on the following references:
Parsing JSON to custom ArrayList, only returning last item?
Listview only displaying last item of arraylist
Here is my code. I hope someone can help solve my issues.
private void getAllDataLocation() {
loading = ProgressDialog.show(this, null, "Menampilkan Semua Tempat...", true, false);
mApiService.getAllPartner().enqueue(new Callback<ResponsePartner>() {
#Override
public void onResponse(Call<ResponsePartner> call, Response<ResponsePartner> response) {
if (response.isSuccessful()) {
loading.dismiss();
final List<PlaceItem> placeItems = response.body().getAllPlace();
initMarker(placeItems);
} else {
loading.dismiss();
Toast.makeText(mContext, "Gagal Mengambil Data Semua Tempat", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponsePartner> call, Throwable t) {
loading.dismiss();
Toast.makeText(mContext, "Koneksi Internet Bermasalah", Toast.LENGTH_SHORT).show();
}
});
}
and
private void initMarker(final List<PlaceItem> listData) {
//for each semua data dan tampilkan markernya
for (int i = 0; i < listData.size(); i++) {
final int finall = i;
//set latlng nya
LatLng marker_location = new LatLng(Double.parseDouble(listData.get(i).getLatitude()), Double.parseDouble(listData.get(i).getLongitude()));
//tambah markernya
marker_bg.setColorFilter(getResources().getColor(R.color.marker_primary));
MarkerOptions markerOptions = new MarkerOptions().title(listData.get(i).getName()).position(marker_location);
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(Tools.createBitmapFromView(ActivityMaps.this, marker_view)));
mMap.addMarker(markerOptions);
//start for marker specific zoom ex: for specific city you want to zoom
LatLng marker_zoom_specific = new LatLng(Constant.city_lat, Constant.city_lng);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(marker_zoom_specific, 12));
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = listData.get(finall).getId();
String cityName = listData.get(finall).getCityName();
String description = listData.get(finall).getDescription();
String address = listData.get(finall).getAddress();
String phone = listData.get(finall).getPhone();
String website = listData.get(finall).getWebsite();
String logo = listData.get(finall).getLogo();
String toolbarTitle = listData.get(finall).getName();
String latitude = listData.get(finall).getLatitude();
String longitude = listData.get(finall).getLongitude();
Intent toDetail = new Intent(ActivityMaps.this, ActivityPlaceDetail.class);
toDetail.putExtra(Constant.KEY_ID_PARTNER, id);
toDetail.putExtra(Constant.KEY_NAME, toolbarTitle);
toDetail.putExtra(Constant.KEY_CITY_NAME, cityName);
toDetail.putExtra(Constant.KEY_DESCRIPTION, description);
toDetail.putExtra(Constant.KEY_ADDRESS, address);
toDetail.putExtra(Constant.KEY_PHONE, phone);
toDetail.putExtra(Constant.KEY_WEBSITE, website);
toDetail.putExtra(Constant.KEY_LOGO, logo);
toDetail.putExtra(Constant.KEY_LATITUDE, latitude);
toDetail.putExtra(Constant.KEY_LONGITUDE, longitude);
startActivity(toDetail);
}
});
}
}
Its better to pass the whole class object rather than passing individual key-value pair.
PlaceItem placeItem = listData.get(finall).getId();
intent.putExtra("data", placeItem);
Make sure your PlaceItem implements Serializable
And when you getIntent use :
Intent intent = getIntent();
PlaceItem placeItem = (PlaceItem) intent.getSerializableExtra("data");
String id = placeItem.getId();
String cityName = placeItem.getCityName();
and so on..
I am currently working with the google map. I already show the markers and the title and snippet of the marker.
Now my problem is when I click the info window it will be redirected to a new activity and get the data of the marker that was clicked. Here is my code:
public class FindApartment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener,GoogleMap.OnInfoWindowClickListener {
public static final String ID = "id";
public static final String VERIFICATION = "verification";
private static final String TAG_APARTMENTNAME = "apartmentName";
private static final String TAG_CATEGORY = "Category";
private static final String TAG_PRICE = "price_month";
public static final String LAT = "latt";
public static final String LNG = "longt";
MarkerOptions markerOptions = new MarkerOptions();
CameraPosition cameraPosition;
LatLng center, latLng;
String verification, apartmentname, category, price, id;
GoogleMap mGoogleMap;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
MapView mapView;
String tag_json_obj = "json_obj_req";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_apartment, container, false);
mapView = (MapView) rootView.findViewById(R.id.map1);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
mapView.onResume();
return rootView;
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions myMarker = new MarkerOptions();
myMarker.position(latLng);
myMarker.title("me");
myMarker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
mCurrLocationMarker = mGoogleMap.addMarker(myMarker);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,17));
getMarkers();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.setOnInfoWindowClickListener(this);
if(mGoogleMap!= null){
mGoogleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View view = getLayoutInflater().inflate(R.layout.info_window, null);
TextView textName = (TextView) view.findViewById(R.id.textName);
TextView textViewPrice = (TextView) view.findViewById(R.id.textViewPrice);
TextView detail = (TextView)view.findViewById(R.id.detail);
LatLng ll = marker.getPosition();
textName.setText(marker.getSnippet());
textViewPrice.setText(marker.getTitle());
detail.setText("click to see full detail");
return view;
}
});
}
I'm using Android Volley and the array is on the Stringrequest. How can I get the data of the marker that was clicked on info window?
private void addMarker(LatLng latLng, String category, final String price, final String id) {
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(price);
markerOptions.snippet(category);
markerOption(verification, markerOptions);
mGoogleMap.addMarker(markerOptions);
}
public void onInfoWindowClick(Marker marker) {
id = marker.getId();
String snippet = marker.getSnippet();
Intent intent = new Intent(getActivity(), InfoWindowActivity.class);
startActivity(intent);
}
private void markerOption(String verification, MarkerOptions markerOptions) {
if(verification.contains("pending")) {
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
else {
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
}
}
private void getMarkers() {
String url = Server.URL2 + "markers.php";
final HashMap<String, String> apartmentID = new HashMap<String, String>();
StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Response: ", response.toString());
try {
JSONObject jObj = new JSONObject(response);
String getObject = jObj.getString("apartments");
JSONArray jsonArray = new JSONArray(getObject);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
verification = jsonObject.getString(VERIFICATION);
apartmentname = jsonObject.getString(TAG_APARTMENTNAME);
category = jsonObject.getString(TAG_CATEGORY);
price = jsonObject.getString(TAG_PRICE);
id = jsonObject.getString("userID");
apartmentID.put(ID, id);
latLng = new LatLng(Double.parseDouble(jsonObject.getString(LAT)), Double.parseDouble(jsonObject.getString(LNG)));
// Adds a data marker to show to google map
addMarker(latLng, category, price, id);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}
Intent intent = new Intent(getActivity(), InfoWindowActivity.class);
intent.putExtra("snippet", snippet);
intent.putExtra("id", id)
... //put all your info here
startActivity(intent);
Access that data on next activity for example in onCreate or wherever you need it.
String snippet = getIntent().getStringExtra("snippet");
int id = getIntent().getIntExtra("id");
...//get all your info here
Is it what you were looking for? Question is not completely clear..
UPD: I've found that there is something bad is happening to latitude and longitude field when I'm getting it from the database, for example it does not shows correctly using Toast.
I'm using a Firebase database in my project. It saves locations with additional information to Firebase database and I need to display markers corresponding to that locations on the map.
The writing database works without perfect.
However, reading does not work at all. I've followed this guide and defined the database as a field on my class, added instantiation in onCreate method and added 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.
When I'm trying to output the size of events it always prints 0 and so it does not print any marker on the map.
The full code is here:
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();
}
}
I am using google maps api to plot a few markers on the map based on locations that I retrieve from Firebase database. This works fine when I retrieve the data from database in a different activity and pass them by intents but when I retrieve the data in this activity, it's plotting a blank map.
My Database:
report
-KZPjqQOP086w1t6dOUY
-KZZnf5c4QdNnLHMgfrG
-KZ_90sfB2QTLtmcSvHW
-KZ_9SnWuu_wDBStHAD6
-KZ_9VGt5UKw9W7Hzdhp
currentstatus: "still_there"
description: "new"
img: "iVBORw0KGgoAAAANSUhEUgAAAMMAAAEECAIAAAAahxdFAAA..."
latitude: "37.3400953"
longitude: "-121.8955277"
severity: "Minor"
size: "Extra Large"
street: "300-364 Coleman Avenue"
timeNdate: "Wed Dec 21 22:13:28 PST 2016"
I tried to debug this and it looks like it is plotting the map before it retrieves the data. How can I correct this so it plots them right?
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
SharedPreferences sharedPreferences;
public String latReport;
public String longiReport;
public String streetReport;
public String repClicked;
private GoogleMap Mmap;
String SLat;
String SLong;
String gmail;
String who;
String Data;
HashMap<Marker, String> Imagemap = new HashMap<>();
// ArrayList<Report> reportArrayList;
ArrayList<String> Lat;
ArrayList<String> Lng;
ArrayList<String> Street = new ArrayList<>();
ArrayList<String> emailid = new ArrayList<>();
ArrayList<String> description = new ArrayList<>();
ArrayList<String> size = new ArrayList<>();
ArrayList<String> severity = new ArrayList<>();
ArrayList<String> img = new ArrayList<>();
//ArrayList<String> Street = new ArrayList<>();
Query queryRef;
int i;
DatabaseReference mRef;
DatabaseReference dRef;
ArrayList<Report> reportArrayList;
ArrayAdapter<Report> arrayAdapter;
Report value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
Intent intent = getIntent();
who = intent.getStringExtra("Off");
String markerimage;
Lat = new ArrayList<>();
dRef = FirebaseDatabase.getInstance().getReference();
reportArrayList = new ArrayList<>();
mRef = dRef.child("report");
Query qRef;
qRef = mRef.orderByChild("emailId");
qRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
value = dataSnapshot.getValue(Report.class);
Log.i(TAG, "onChildAdded: "+value.getEmailId());
Log.i(TAG, "Locaton: "+value.getLatitude());
Log.i(TAG, "Locaton: "+value.getLongitude());
reportArrayList.add(value);
Lat.add(value.getLatitude());
Lng.add(value.getLatitude());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
for (i = 0; i < Lat.size(); i++) {
Log.i(TAG, "onChildAdded: "+Lat.get(i));
latReport = reportArrayList.get(i).getLatitude();
longiReport = reportArrayList.get(i).getLongitude();
streetReport = reportArrayList.get(i).getStreet();
double number = Double.parseDouble(latReport);
double number2 = Double.parseDouble(longiReport);
Marker marker = map.addMarker(new MarkerOptions()
.position(new LatLng(number, number2))
.title(streetReport));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(number, number2), 15));
Mmap = map;
String cimage = img.get(i);
Imagemap.put(marker,cimage);
}
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String markerimage = Imagemap.get(marker);
Intent intentnew = new Intent(getApplicationContext(), OfficialDetail.class);
for (int iter = 0; iter < Lat.size(); iter++) {
if (markerimage.equals(img.get(iter)))
{
Data = Street.get(iter);
intentnew.putExtra("street_of", Data);
Data = Lat.get(iter);
intentnew.putExtra("lat_of", Data);
Data = Lng.get(iter);
intentnew.putExtra("long_of", Data);
Data = description.get(iter);
intentnew.putExtra("lat_of", Data);
Data = size.get(iter);
intentnew.putExtra("size_of", Data);
Data = severity.get(iter);
intentnew.putExtra("severity_of", Data);
Data = img.get(iter);
intentnew.putExtra("img_of", Data);
if(who=="User")
intentnew.putExtra("Off","User");
else
intentnew.putExtra("Off","Off");
break;
}
}
startActivity(intentnew);
return false;
}
});
}
}
Edit: I had posted code where I was just checking if the code was being retrieved. This is the latest code. I populated the Lat Array list after I retrieve from the database
I would appreciate any help.
Map<String, List<Driver>> markerMap = new HashMap<String, List<Driver>>();
private List<Driver> markerArray = new ArrayList<Driver>();
public void markerDriver() {
markerArray = new ArrayList<>();
Firebase ref = new Firebase(Config.FIREBASE_URL_DRIVER);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() == 0) {
markerInfo();
} else {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Toast.makeText(MainMapActivity.this, "for", Toast.LENGTH_SHORT).show();
name = snapshot.child("driversName").getValue().toString().trim();
busNum = snapshot.child("busNum").getValue().toString().trim();
latitude = Double.valueOf(snapshot.child("latitude").getValue().toString().trim());
longitude = Double.valueOf(snapshot.child("longitude").getValue().toString().trim());
availableSeat = snapshot.child("availableSeat").getValue().toString().trim();
estimatedTime = snapshot.child("estimatedTime").getValue().toString().trim();
if ((!latitude.equals(null) || latitude.equals(0)) && (!longitude.equals(null) || longitude.equals(0)) && availableSeat.equals("") && (!estimatedTime.equals("") || estimatedTime.equals("0"))) {
convertLatLong();
getTotalPass();
markerArray.add(new Driver(name, totalPassenger, busNum, latitude, longitude, currentLocation, estimatedTime));
markerMap.put("key"+key++, markerArray);
}
}
for (i = 0; i < markerArray.size(); i++) {
createMarker(markerArray.get(i).getDriversName(), markerArray.get(i).getTotalPassenger(), markerArray.get(i).getBusNum(), markerArray.get(i).getLatitude(), markerArray.get(i).getLongitude(), markerArray .get(i).getLocation(), markerArray.get(i).getEstimatedTime());
}
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(MainMapActivity.this, "markerDriver: " + firebaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I am putting my arrayList inside the HashMap because ArrayList alone don't have the capability to edit/update some data inside the list. So what I am trying to do is how do I retrieve the data inside the HashMap and createMarker
protected void createMarker(String driversName, final int totalPass, final String busNum, double latitude, double longitude, String location, String estimatedTime) {
Marker marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(location)
.snippet("Driver's Name: " + driversName + "\nTotal Passenger: " + totalPass + "\nBus number: " + busNum+"\nEstimated time: "+estimatedTime));
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(com.google.android.gms.maps.model.Marker marker) {
dialogInfo(marker);
return true;
}
});
}
1.First create a POJO class like this
public class InterRejectedHistory {
String seeker_role,rejected_date;
String SeekerType;
public InterRejectedHistory(String seeker_role,String seekerType) {
this.seeker_role = seeker_role;
this.SeekerType= seekerType;
}
public String getSeekerType() {
return SeekerType;
}
public void setSeekerType(String seekerType) {
SeekerType = seekerType;
}
public InterRejectedHistory() {
}
public String getSeeker_role() {
return seeker_role;
}
public void setSeeker_role(String seeker_role) {
this.seeker_role = seeker_role;
}
public String getRejected_date() {
return rejected_date;
}
public void setRejected_date(String rejected_date) {
this.rejected_date = rejected_date;
}}
2.Step 2 [set the values from your class]
InterRejectedHistory interRejectedHistory;
List<InterRejectedHistory> dbList;
dbList=new ArrayList<InterRejectedHistory>();
interRejectedHistory.setSeeker_role(c.getString("SEEKERROLE"));
interRejectedHistory.setSeekerType(c.getString("SEEKERTYPE"));
dbList.add(new InterRejectedHistory(interRejectedHistory.getSeeker_role(),interRejectedHistory.getSeekerType()));
Note : In Mycase i was set the values in POJO and loaded into a adapter.
Wherever you want get the value from POJO class
ArrayList<InterRejectedHistory> list;
role.setText(list.get(position).getSeeker_role());
Happy Coding!