Communication between two Activities? - android

I'm making an app in which I'm using GoogleMaps.Now, I have a question about communication between MapActivity and ToursActivity.To simplify it, my app is about band Metallica, and I have list of Tours. When user clicks on one of the Tours, it should open a new Activity with that location. I won't put ToursActivity here, cause there is a bunch of code that you don't need.Also, I'm keeping all my data on Firebase, if that's important.
This is my MapActivity:
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int REQUEST_LOCATION_PERMISSION = 10;
private GoogleMap.OnMapClickListener mCustomOnMapClickListener;
private GoogleMap mGoogleMap;
private MapFragment mMapFragment;
#BindView(R.id.lvTours) ListView lvTours;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tours_coord);
this.initialize();
lvTours.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
public void initialize(){
this.mMapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.fGoogleMap);
this.mMapFragment.getMapAsync(this);
this.mCustomOnMapClickListener = new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
MarkerOptions newMarkerOptions = new MarkerOptions();
newMarkerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.tour));
newMarkerOptions.title("Tour");
newMarkerOptions.snippet("It' was here!");
newMarkerOptions.position(latLng);
mGoogleMap.addMarker(newMarkerOptions);
}
};
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.mGoogleMap = googleMap;
UiSettings uiSettings = this.mGoogleMap.getUiSettings();
uiSettings.setZoomControlsEnabled(true);
uiSettings.setMyLocationButtonEnabled(true);
uiSettings.setZoomGesturesEnabled(true);
this.mGoogleMap.setOnMapClickListener(this.mCustomOnMapClickListener);
goToLocation(33.835293 , -117.914505);
}
public void goToLocation(double lat, double lng){
LatLng latLng = new LatLng(lat, lng);
CameraPosition position = CameraPosition.builder()
.target(latLng)
.zoom(16f)
.bearing(0.0f)
.tilt(0.0f)
.build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position),null);
}
private boolean hasLocationPermission() {
String LocationPermission = android.Manifest.permission.ACCESS_FINE_LOCATION;
int status = ContextCompat.checkSelfPermission(this, LocationPermission);
if (status == PackageManager.PERMISSION_GRANTED) {
this.mGoogleMap.setMyLocationEnabled(true);
return true;
}
return false;
}
private void requestPermission() {
String[] permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions(MapActivity.this, permission, REQUEST_LOCATION_PERMISSION);
}
}

You can use Intent with extra parameters.
For example, on ToursActivity.java
Intent intent = new Intent(ToursActivity.this, MapActivity.class);
intent.putExtra("lat", latitude);
intent.putExtra("long", longitude);
startActivity(intent);
Then you can get get these parameters on onCreate() method of MapActivity.java:
Intent intent = getIntent();
long latitude = intent.getLongExtra("lat", 0);
long longitutde = intent.getLongExtra("long", 0);

You can use intent with extra parameters.
Intent intent = new Intent(ToursActivity.this, MapActivity.class);
intent.putExtra("latitude", latitude);
intent.putExtra("longitude", longitude);
startActivity(intent);
Then you can get your values in onCreate() method of MapActivity.
Intent intent = getIntent();
Bundle extras = intent.getExtras();
double latitude = intent.getDouble("latitude");
double longitude = intent.getDouble("longitude");

Related

How to move camera and marker in google map to data of Latitude and Longitude received by intent.putExtra Android

I have pass data of latitude and longitude from (activtiy1 ) to(activtiy2 ) by intent.putExtra.
It works, but location is default location it view in marker and camera in sydney , and not according to data that I passes from the first activity to the second activity.
The first activity
public class Main3Activity extends AppCompatActivity {
TextView textView4;
Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
textView4 =(TextView)findViewById(R.id.textView4);
button2=(Button)findViewById(R.id.button2);
Intent i = getIntent();
final String Latitude=i.getStringExtra("Latitude");
final String Longitude=i.getStringExtra("Longitude");
textView4.setText(textView4.getText() + Longitude+Longitude );
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Main3Activity.this, MapsActivity.class);
intent.putExtra("Latitude", Latitude);
intent.putExtra("Longitude", Longitude);
startActivity(intent);
}
});
}
}
The second activity
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
Double Latitude=0.0;
Double Longitude=0.0;
TextView textView;
#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);
Intent i = getIntent();
Latitude=i.getDoubleExtra("Latitude",0.0);
Longitude=i.getDoubleExtra("Longitude",0.0);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(Latitude, Longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
example of the data I pass to clarify problem \
And example of problem
what is there problem ? anyone know the solution for it ?
You should change
final String Latitude=i.getStringExtra("Latitude");
final String Longitude=i.getStringExtra("Longitude");
to
Latitude=i.getDoubleExtra("Latitude",0.0);
Longitude=i.getDoubleExtra("Longitude",0.0);
like in MapsActivity. Don't forget to initialize it.
Everywhere you get Latitude and Longitude value, they should be in Double not String.

How to set method onItemClick to open a Google Maps?

I'm building an app, and I run on a problem with Google Maps. I wrote most of the code, but I don't how how to set that when user clicks on item(method onItemClick), in my case I have ListView on Firebase that is showing Tours of concerts, which you can see here:my tours listview to open a specific place and show it on map. For example, user clicks on Anaheim, CA concert and it shows where that place is. Thanks in advance.
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int REQUEST_LOCATION_PERMISSION = 10;
private GoogleMap.OnMapClickListener mCustomOnMapClickListener;
private GoogleMap mGoogleMap;
private MapFragment mMapFragment;
#BindView(R.id.lvTours) ListView lvTours;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
this.initialize();
}
public void initialize(){
this.mMapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.fGoogleMap);
this.mMapFragment.getMapAsync(this);
this.mCustomOnMapClickListener = new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
MarkerOptions newMarkerOptions = new MarkerOptions();
newMarkerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.tour));
newMarkerOptions.title("Tour");
newMarkerOptions.snippet("It' was here!");
newMarkerOptions.position(latLng);
mGoogleMap.addMarker(newMarkerOptions);
}
};
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.mGoogleMap = googleMap;
UiSettings uiSettings = this.mGoogleMap.getUiSettings();
uiSettings.setZoomControlsEnabled(true);
uiSettings.setMyLocationButtonEnabled(true);
uiSettings.setZoomGesturesEnabled(true);
this.mGoogleMap.setOnMapClickListener(this.mCustomOnMapClickListener);
}
private boolean hasLocationPermission() {
String LocationPermission = android.Manifest.permission.ACCESS_FINE_LOCATION;
int status = ContextCompat.checkSelfPermission(this, LocationPermission);
if (status == PackageManager.PERMISSION_GRANTED) {
this.mGoogleMap.setMyLocationEnabled(true);
return true;
}
return false;
}
private void requestPermission() {
String[] permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions(MapActivity.this, permission, REQUEST_LOCATION_PERMISSION);
}
#OnItemClick(R.id.lvTours)
public void onClick()
{
}
}
Since you have your coordinates, you can build a LatLng(latitude, longitude) object
then you can move the camera of your map like this:
build a new camera position using CameraPosition.Builder() and then ask to your mGoogleMap to animate to that position:
CameraPosition position = CameraPosition.builder()
.target(location)
.zoom(16f)
.bearing(0.0f)
.tilt(0.0f)
.build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position), null)
using that position you can even put a marker on the map:
mGoogleMap.addMarker(new MarkerOptions().position(position)
.title("some title"));

Android Button not listening accepting clicklistener under mapfragment class

I have a button in this view which also has map class but somehow I cant set a listener to this button:
fileBtn.setOnClickListener(this);
I am not sure this is because this is a map class/fragment or any other reason.
The full class here:
/**
* This shows how to listen to some {#link GoogleMap} events.
*/
public class MapsActivity extends AppCompatActivity
implements OnMapClickListener, OnMapLongClickListener,
OnMapReadyCallback, OnClickListener {
private TextView mTapTextView;
private Button fileBtn;
private static final int REQUEST_PICK_FILE = 1;
private File selectedFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mTapTextView = (TextView) findViewById(R.id.tap_text);
mTapTextView.setText("Loaded");
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(map);
mapFragment.getMapAsync(this);
}
Button fileBtn = (Button) findViewById(R.id.loadfile);
fileBtn.setOnClickListener(this);
public void onClick(View v) {
switch(v.getId()) {
case R.id.loadfile:
Intent intent = new Intent(this, FilePicker.class);
startActivityForResult(intent, REQUEST_PICK_FILE);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
switch(requestCode) {
case REQUEST_PICK_FILE:
if(data.hasExtra(FilePicker.EXTRA_FILE_PATH)) {
selectedFile = new File
(data.getStringExtra(FilePicker.EXTRA_FILE_PATH));
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_SUBJECT, "Test single attachment");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"amirfarazmand#gmail.com"});
intent.putExtra(Intent.EXTRA_TEXT, "Mail with an attachment");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(data.getStringExtra(FilePicker.EXTRA_FILE_PATH))));
intent.setType("application/pdf");
startActivity(Intent.createChooser(intent, "Send mail"));
}
break;
}
}
}
private GoogleMap googleMap;
#Override
public void onMapReady(GoogleMap map) {
map.setOnMapClickListener(this);
map.setOnMapLongClickListener(this);
googleMap = map;
enableMyLocation();
}
/* private static final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);
private static final LatLng ADELAIDE = new LatLng(-34.92873, 138.59995);
private static final LatLng PERTH = new LatLng(-31.95285, 115.85734); */
public int i=0;
public Polygon polygon;
public Polyline polyline;
List<LatLng> coordinates=new ArrayList<LatLng>();
public void onMapClick(LatLng point) {
mTapTextView.setText("tapped, point=" + point);
if (i==0){
i=1;
coordinates.add(point);
googleMap.addMarker(new MarkerOptions()
.position(point)
.title(String.valueOf(point.latitude))
.snippet(String.valueOf(point.latitude))
.rotation((float) -15.0)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
);
} else if (i==1) {
i=i+1;
coordinates.add(point);
polyline = googleMap.addPolyline((new PolylineOptions())
.add(coordinates.get(0), coordinates.get(1)));
}else if (i>1){
coordinates.add(point);
polyline.remove();
if (i>2){polygon.remove();};
polygon = googleMap.addPolygon(new PolygonOptions()
.addAll(coordinates)
.strokeColor(Color.BLACK)
.strokeWidth(10));
//polygon = googleMap.addPolygon((new PolygonOptions())
// .add(coordinates.get(0), coordinates.get(1),coordinates.get(2)));
i=i+1;
}/*else{
List<LatLng> polygonList = polygon.getPoints();
Toast.makeText(getBaseContext(), polygonList.toString(), Toast.LENGTH_LONG).show();
polygonList.add(point);
polygon.remove();
polygon = googleMap.addPolygon((new PolygonOptions()));
polygon.setPoints(polygonList);
i=i+1;
}*/
}
public boolean mapView = true;
#Override
public void onMapLongClick(LatLng point) {
if(mapView) {
mTapTextView.setText("long pressed, point=" + point);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mapView=!mapView;
}else{
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mapView=!mapView;
}
}
//Load coorodinates from file
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (googleMap != null) {
// Access to the location has been granted to the app.
googleMap.setMyLocationEnabled(true);
googleMap.setTrafficEnabled(true);
}
}
/**
* Displays a dialog with error message explaining that the location permission is missing.
*/
private void showMissingPermissionError() {
PermissionUtils.PermissionDeniedDialog
.newInstance(true).show(getSupportFragmentManager(), "dialog");
}
}
I think you need to declare button and click listner in onCreate() method rather than outside
of it.Like:
oncreate()
{
b1=(Button)findviewbyId(R.id.abc);
b1.setOnclicklistener(this);
}
when You implement View.Onclicklistener...You will get override method onClick
....Inside that based on id you implement your logic.
You should add listener inside onCreate. Then override method for onClick.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mTapTextView = (TextView) findViewById(R.id.tap_text);
mTapTextView.setText("Loaded");
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(map);
mapFragment.getMapAsync(this);
Button fileBtn = (Button) findViewById(R.id.loadfile);
fileBtn.setOnClickListener(this);
}
Override method.
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.loadfile:
Intent intent = new Intent(this, FilePicker.class);
startActivityForResult(intent, REQUEST_PICK_FILE);
break;
}
}
Why these line
Button fileBtn = (Button) findViewById(R.id.loadfile);
fileBtn.setOnClickListener(this);
are outside onCreate() method ?
The Reason is that because ur Class implements OnClickListener instead of View.OnClickListener
Button fileBtn = (Button) findViewById(R.id.loadfile);
fileBtn.setOnClickListener(this);
Your code is dizzy, what I understood is you need to put this code inside onCreate.

Latitude value set to 0

I set a value from MainActivity to Fragment, but the value become 0 in Fragment.
when I got log in moveToLocation(), value of latitude was 0, but when I got log in setLocation, value of latitude was correct passed value.
why is this?
MainActivity
MapFragment mapFragment = new MapFragment();
mapFragment.setLocation(111, 222, "abcAddress");
Fragment
public class MapFragment extends Fragment {
private GoogleMap mMap;
private double mLatitude;
private double mLongitude;
private String mAddress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
Log.d("", "You must update Google Maps.");
getActivity().finish();
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mMap = ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
moveToLocation();
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.map_page, null);
}
public void setLocation(double latitude, double longitude, String address) {
mLatitude = latitude;
mLongitude = longitude;
mAddress = address;
}
protected void moveToLocation() {
CameraPosition location = new CameraPosition.Builder()
.target(new LatLng(mLatitude, mLongitude)).zoom(15.5f)
.bearing(0).tilt(25).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(location));
MarkerOptions marker = new MarkerOptions().position(new LatLng(mLatitude, mLongitude)).title(mAddress);
marker.snippet("Snippet");
mMap.addMarker(marker);
}
}
You should not create the new instance of MapFragment.
To pass the values, set them in Argument while adding them in the Transaction :
Bundle bundle = new Bundle();
bundle.putDouble("lat", latitude);
bundle.putDouble("long", longitude);
bundle.putString("address", address);
myFragment.setArguments(bundle);
And fetch the value in onCreate() like :
#Override
public View onCreate(Bundle savedInstanceState) {
Bundle mBundle = getArguments();
if (mBundle != null) {
String address = mBundle.getString("address");
// Call method
setLocation(mBundle.getDouble("lat"), mBundle.getDouble("long"), mBundle.getString("address"));
} else {
Toast.makeText(getActivity(), "Location Not Found", Toast.LENGTH_SHORT).show();
}
}
Hope it helps ツ

Switching GoogleMap between activities

I have two activities one that send coordinates and one that recieves and drawing them.
I need that both of them will show GoogleMap... in the first activity i can see google map right away but then when i call to the second activity from BroadcastReceiver i just see blank white screen.
Thats my Second activity code:
public class NewActivity extends FragmentActivity {
GoogleMap googleMap;
String message;
String number;
double[] d = new double[4];
ArrayList<LatLng> points= new ArrayList<LatLng>() ;
#Override
public void onStart() {
super.onStart();
final LocalBroadcastManager localBroadcastManager =
LocalBroadcastManager.getInstance(this);
final IntentFilter localFilter = new IntentFilter();
localBroadcastManager.registerReceiver(localBroadcastReceiver, localFilter);
}
#Override
public void onStop() {
super.onStop();
final LocalBroadcastManager localBroadcastManager =
LocalBroadcastManager.getInstance(this);
// Make sure to unregister!!
localBroadcastManager.unregisterReceiver(localBroadcastReceiver);
}
BroadcastReceiver localBroadcastReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
setContentView(R.layout.ye);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
message=intent.getStringExtra("message");
number=intent.getStringExtra("number");
int p=0;
Matcher m = Pattern.compile("(?!=\\d\\.\\d\\.)([\\d.]+)").matcher(message);
while(m.find())
{
double k = Double.parseDouble(m.group(1));
d[p]=k;
p++;
}
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.color(Color.BLUE);
// Setting the width of the polyline
polylineOptions.width(6);
// Adding the taped point to the ArrayList
LatLng coordlocation = new LatLng(d[0], d[1]);
points.add(coordlocation);
LatLng coordlocation2 = new LatLng(d[2], d[3]);
points.add(coordlocation2);
// Setting points of polyline
polylineOptions.addAll(points);
googleMap.addPolyline(polylineOptions);
}
};
}
Note : I didnt registered the localBroadcastReceiver in the manifest file since i dont know if its neccessary.
I solved it by adding this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ye);
}

Categories

Resources