I am able to display all items from Autocomplete suggestion but when i click an item i want the longitude and latitude coordinates associated with the item to be plotted on the map. I currently dont know how to achieve. `please help here.
I have pasted my method below
private void searchAutocomplete(){
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
//Create a new ArrayAdapter with your context and the simple layout for the dropdown menu provided by Android
final ArrayAdapter<String> autoComplete = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1);
//Child the root before all the push() keys are found and add a ValueEventListener()
database.child("wr").child("clubs").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Basically, this says "For each DataSnapshot *Data* in dataSnapshot, do what's inside the method.
for (DataSnapshot suggestionSnapshot : dataSnapshot.getChildren()){
//Get the suggestion by childing the key of the string you want to get.
String suggestion = suggestionSnapshot.child("name1").getValue(String.class);
//Add the retrieved string to the list
autoComplete.add(suggestion);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
AutoCompleteTextView ACTV= (AutoCompleteTextView)findViewById(R.id.autocompleteView);
ACTV.setAdapter(autoComplete);
ACTV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
You should update final ArrayAdapter<String> autoComplete to instead be something like final ArrayAdapter<Place> autoComplete and then implement something like:
public class Place {
private float latitude;
private float longitude;
private String name;
// implement your constructor
// implement your accessors
}
And then from your onClick you would received the Place, and you can just do something like place.getLatitude() and place.getLongitude.
That's how I would implement this.
You simply need to listen for click events and add a Marker when an item is clicked.
Example:
tv.setOnItemClickListener((adapterView, view, pos, id) -> {
mGoogleMap.addMarker(new MarkerOptions()
.position(mDataList.get(pos).getLocation()));
});
You'll need to make sure your google map has been loaded of course.
Related
I have an android application where a MapsActivity is included to display a number of markers using GoogleMaps.
The markers are created through Timestamp objects
Timestamp object attributes
(double lat,lon;
int stepSum;
long timeMilli;
String state=null;)
stored in Firebase Database.
So I retrieve each Timestamp from the database and try to create a marker with those attibutes above. My problem is that when I click a marker the custom info window is being displayed but its the same for all markers. It should show different attributes for different markers.
Why this is happening
In the drawMarkers() method I instantiate a separate infowindow when I am creating a new marker and set that info window to the
GoogleMap object with mMap.setInfoWindowAdapter(infoWindow);.
As I result mMap.setInfoWindowAdapter(infoWindow);is called as many times as markers are created and finally only the last infowindow survives. That is the problem but I can't figure out a solution.
How to implement an infowindow that when I click a marker it presents some kind of data and when I am clicking another marker it presents different kind of data (same layout, different attributes).
A valid example also would do.
CustomInfoWindow class
private class CustomInfoWindow implements GoogleMap.InfoWindowAdapter{
private String title=null,hour=null,state=null;
private int steps=0;
public CustomInfoWindow(){}
public CustomInfoWindow(String title, String hour, String state, int steps) {
this.title = title;
this.hour = hour;
this.state = state;
this.steps = steps;
}
#Override
public View getInfoWindow(Marker marker) {
return null;
}
public void setState(String state) {
this.state = state;
}
#Override
public View getInfoContents(Marker marker) {
LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
View root = inflater.inflate(R.layout.marker_infowindow,null);
TextView titleTextView = (TextView) root.findViewById(R.id.infowindow_title);
TextView hourTextView = (TextView) root.findViewById(R.id.infowindow_hour);
TextView stepsTextView = (TextView) root.findViewById(R.id.infowindow_steps);
TextView stateTextView = (TextView) root.findViewById(R.id.infowindow_state);
titleTextView.setText(title);
if (state!=null){
stateTextView.setText(getApplicationContext().getString(R.string.state)+" "+state);
stateTextView.setVisibility(View.VISIBLE);
}
hourTextView.setText(getApplicationContext().getString(R.string.time)+" "+hour);
stepsTextView.setText(getApplicationContext().getString(R.string.steps_so__far)+" "+steps);
return root;
}
public void setTitle(String title) {
this.title = title;
}
public void setHour(String hour) {
this.hour = hour;
}
public void setSteps(int steps) {
this.steps = steps;
}
}
How markers are drawn
private void drawMarkers(Calendar c){
String userId = this.user.getAccount().getId();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
final DatabaseReference timestampRef = FirebaseDatabase.getInstance().getReference()
.child(FirebaseConstant.TIMESTAMPS.toString());
timestampRef.child(userId).child(""+year).child(""+month).child(""+dayOfMonth)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long childCounter=0;
for (DataSnapshot timestampSnapshot:dataSnapshot.getChildren()){
CustomInfoWindow infoWindow=new CustomInfoWindow();
Timestamp temp = timestampSnapshot.getValue(Timestamp.class);
if (temp!=null){
infoWindow.setTitle(getString(R.string.todays_timestamp));
infoWindow.setHour(getFormatedHourFromTimeMilli(temp.getTimeMilli()));
infoWindow.setSteps(temp.getStepSum());
if (temp.getState()!=null){
infoWindow.setState(temp.getState());
}
mMap.setInfoWindowAdapter(infoWindow);
drawTimestamp(temp);
infoWindow=null;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
I have read google's tutorial about info windows but couldn't solve my problem.
Hope this example will help you just use it as simple xml layout.
Remember button will not work just textview will complete your requirement on the spot if you want get buttons in workable condition follow chose007 example.
My solution
Create a class that extends GoogleMap.InfoWindowAdapter. That will be your custom infowindow for the whole map.
Inside onMapReady() set an implementation of your customInfoWindow object to the GoogleMap object. That will be the one and only infowindow that it will be displayed when a user is clicking a marker from the map.
Finally, inside onMapReady() method set an OnMarkerClickListener to the GoogleMap object as well. Your implementation of the GoogleMap.OnMarkerClickListener.onMarkerClick(Marker marker) will only change the content (change the attributes of the infowindow object, call it however you want) of the infowindow, depending on which marker is clicked.
I'm making something like a social app.
I would like that if someone has already viewed something before, that the button in the view will change colors.
I have a method to check if someone has viewed this list before. It works in the clickListener, and will say "Already pressed."
I'm having a hard time figuring out how to change the color of the button, maybe on the onCreate method. I've tried passing it as an argument, but the color will change on the second time the list is pulled up...
This is how I call up my dialog and pass it the list ID.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View r = inflater.inflate(R.layout.list_view_dialog_layout, container, false);
checklistView = (UserlistView) r.findViewById(R.id.user_list);
checklistview.getList(getArguments().getString("list_id")); // Can be modified
return r;
}
in that function getList, I make my call to my database to get the info of the list.
public void getList(final String listID) {
// TODO fetch list information from params and fill fields
Event.requestEvent(listID, "AuthToken", new List.ListReceivedListener() {
#Override
public void onListReceived(lissts... lissteses) {
List lst = lissteses[0];
setInfo(lst);
LISTID = listID;
}
});
}
public void setInfo(List lst){
listTitleView.setText(lst.listName);
viewsCount.setText(Integer.toString(lst.views));
}
I have a checker function to see if the user has already clicked the "have viewed"
public static boolean viewed(String id, final String user){
DatabaseReference rootref = FirebaseDatabase.getInstance().getReference("views").child(id);
rootref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user)){
result = true;
}
else{
result = false;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return result;
}
then, I wanted to call it in the getList() as such
if(viewed(lstID, curuser){
viewButton.setColorFilter(R.color.blue);
}
this doesn't work for the first time the view is created, and so, if the user has already clicked view, logs out and logs back in, and click view again, messing up the view count.
int flag=0;
button.setOnClickLitener(new OnClickListener()){
#Override
public void onClick(View arg0) {
flag++;
}
});
if(flag>0){
button.setBackgroundColor(getResources().getColor(R.color.yourColor));
}
Another solution is this.
button.setBackgroundColor(getResources().getColor(R.color.youCustomColor));
I would like to users to add and save markers on Firebase database.
i am unsure of how to do it, i currently have the user adding the marker and saving it but it does not appear on others users app.
public void onMapLongClick(final LatLng latLng) {
LayoutInflater li = LayoutInflater.from(context);
final View v = li.inflate(R.layout.alert_layout, null);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setView(v);
builder.setCancelable(false);
builder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText title = (EditText)v.findViewById(R.id.ettittle);
EditText snittle = (EditText)v.findViewById(R.id.etsnittle);
Marker marker0 = mMap.addMarker(new MarkerOptions()
.position(latLng)
.title(title.getText().toString()).snippet(snittle.getText().toString())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.tackshops)));
hash.put(marker0, R.drawable.agriculture);
prefs.edit().putString("Lat",String.valueOf(latLng.latitude)).apply();
prefs.edit().putString("Lng",String.valueOf(latLng.longitude)).apply();
locationCount++;
editor.putString("title"+(locationCount-1), title.getText().toString());
editor.putString("snippet"+(locationCount-1),snittle.getText().toString());
}
});
this is my method for saving the marker on the Firebase Database
private void drawMarker(final LatLng latLng){
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.
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
Agriculture marker = userSnapshot.getValue(Agriculture.class);
mMap.addMarker(new MarkerOptions().position(latLng))
.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.tackshops));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Failed to read value
}
});
Saving data into FireBase :
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("Sample_My_Location").push().setValue(l);
And you can see your data as JSON structure on FireBase console at https://console.firebase.google.com/ .
Make sure you have successfully setup firebase in your project. Check here https://codelabs.developers.google.com/codelabs/firebase-android/#0
You should save coordinates of your location (Lat Long) on Firebase. And then you can retrieve and show markers on Map.
Firebase Realtime Database this will let you know how to save and retrieve data.
I already added multiple marker in google map. But when I click on the particular marker, it should show dialog containing some message and selection button.How to get this?
You should do like #Vurtne says.
Here you can see many another interesting things what you can do with markers.
https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/MarkerDemoActivity.java
It can be useful for you.
By creating a class with all the information you want to show in dialog box, you can solve the problem. Just use the marker id as a key to that information so you can get specific data from the class.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//here I'm using Firebase but you can add marker statically or from any other source
mList.addListenerForSingleValueEvent(new ValueEventListener() {
double location_left, location_right;
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int count = 0;
for (DataSnapshot child : dataSnapshot.getChildren()) {
String rightLocation = child.child("lat").getValue().toString();
String leftLocation = child.child("lon").getValue().toString();
String city = child.child("city").getValue().toString();
String deg = child.child("deg").getValue().toString();
String speed = child.child("speed").getValue().toString();
location_left = Double.parseDouble(leftLocation);
location_right = Double.parseDouble(rightLocation);
Marker marker = mMap.addMarker(new MarkerOptions().position(new LatLng(location_right, location_left)).title(city).snippet("Wind Speed: "+speed).icon(BitmapDescriptorFactory.fromResource(R.drawable.wlll)));
//adding all the information in LocationDetails class with marker id so I can get the specific information, but you can store the data in sqlite db or anything
locationDetailses.add(new LocationDetails(marker.getId(), location_right, location_left, city, Double.parseDouble(deg), Double.parseDouble(speed)));
}
LatLng position = new LatLng(88.0433, 92.66942);
mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
//Here setting onClickListener on mMap object of GoogleMap
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
AlertDialog.Builder builder = new AlertDialog.Builder(Map_Activity.this);
//searching marker id in locationDetailses and getting all the information of a particular marker
for (int i = 0; i<locationDetailses.size(); i++) {
//matching id so, alert dialog can show specific data
if (marker.getId().equals(locationDetailses.get(i).getMarkerID())){
builder.setTitle("City: "+locationDetailses.get(i).getCity());
builder.setMessage("Wind Speed: "+locationDetailses.get(i).getSpeed()+"\n"+"Degree: "+locationDetailses.get(i).getDeg()+"\n"+"We can plant WindMill here");
}
}
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog
AlertDialog dialog = builder.create();
dialog.show();
// Add the button
return false;
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
You can use onMarkerClick and get the marker info like this:
yourMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
});
Using google map on clicklistener you can open alert dialog
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
alertDialog();
}
}
});
I have a ListView that I am trying to use with a checkable item list. I am calling the toggle() method on my list item class in the ArrayAdaptor, but the checkbox is not being ticked in the UI. However, I can confirm that the correct items are being selected in the UI, and that the "isChecked()" status reports back correctly--just the UI doesn't change at all. Are there any special methods I need to call to update the checkbox graphic for the UI?
To put it another way--how do I programmatically tell the UI that a checkbox should show up as "checked"? It seems this should be a very simple process, but I've been having a lot of trouble finding this information.
Code is as follows:
For the item data class in the ArrayAdaptor:
public class SelectedItemData extends CheckedTextView {
public String _item_name;
public String getItemName()
{
return _item_name;
}
public void setItemName(String in_name)
{
_item_name = in_name;
}
// methods
public SelectedItemData(Context context) {
super(context);
init();
}
public void init()
{
this._item_name = "UNSET";
this.setChecked(false);
}
#Override
public String toString()
{
return _item_name;
}
}
In the Activity class (located within the onCreate method):
_selectedItemsListView = (ListView) findViewById(R.id.selected_items_listview);
_selectedItemsListView.setItemsCanFocus(false);
_selectedItemsListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
_selectedItemsListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View view, int position, long id) {
#SuppressWarnings("unchecked")
ArrayAdapter<SelectedItemData> itemsAdapter = (ArrayAdapter<SelectedItemData>)_selectedItemsListView.getAdapter();
SelectedItemData selectedItem = itemsAdapter.getItem(position);
selectedItem.toggle();
Toast.makeText(view.getContext(), "Item " + selectedItem.getItemName() + " Selected!", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Is Item Checked? " + selectedItem.isChecked());
_selectedItemsListView.setAdapter(itemsAdapter);
}
});
Any guidance on how to enable the UI to properly display that one of the items have been selected/checked would be great. Thanks!
You have to update your adapter with the new item and set it to the listview. (itemsAdapter.setItem(item,position))