Google Places Autocomplete API crashed on some phones - android

I am trying to implement Google Places Autocomplete API, but the search bar for it crashed on some phones every time when I search for something.
It does work on some phones (like Moto G 2nd Generation XT1068) but crashes on Lenovo A7000 whenever I search anything in the search bar and then press enter.
Another problem I face is; I want to change the default google maps location that shows near South Africa. Change it to a specific location. How can I do that?
package com.docto365.activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import com.docto365.R;
public class HospitalMapsActivity extends FragmentActivity /*implements OnMapReadyCallback*/ implements LocationListener{
private GoogleMap mMap;
LocationManager location;
Toolbar mActionBarToolbar;
private static final LatLngBounds Bhubaneswar = new LatLngBounds(
new LatLng(20.192597, 85.792239), new LatLng(20.409371, 85.824544));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospital_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
/*SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);*/
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setHint("Search Hospitals & Clinics");
autocompleteFragment.setBoundsBias(Bhubaneswar);
mActionBarToolbar=(Toolbar)findViewById(R.id.toolbar);
mActionBarToolbar.setTitle(" Hospitals & Clinics");
mActionBarToolbar.setNavigationIcon(R.drawable.ic_arrow_back);
mActionBarToolbar.setTitleTextColor(Color.WHITE);
mActionBarToolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
location= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
location.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 400, 1000, this);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
//Log.i(TAG, "Place: " + place.getName());
//Toast.makeText(HospitalMapsActivity.this, "Place: " + place.getName(), Toast.LENGTH_LONG).show();
//EditText et = (EditText) findViewById(R.id.autotext);
//String destination = et.getText().toString();
String destination = (String) place.getName();
List<Address> addressList = null;
if (destination == null || !destination.equals("")) {
Geocoder geocoder = new Geocoder(HospitalMapsActivity.this);
try {
addressList = geocoder.getFromLocationName(destination, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title(destination));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
//Log.i(TAG, "An error occurred: " + status);
Toast.makeText(HospitalMapsActivity.this, "An error occured: " + status, Toast.LENGTH_LONG).show();
}
});
//setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded()
{
if(mMap==null)
mMap=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if(mMap!=null)
setUpMap();
}
private void setUpMap()
{
//mMap.addMarker(new MarkerOptions().position(new LatLng(20.271790,85.843858)).title("Marker").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.setMyLocationEnabled(true);
//mMap.animateCamera( CameraUpdateFactory.zoomTo( 17.0f ) );
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(HospitalMapsActivity.this,"Tap on healthcare centre name to book a cab",Toast.LENGTH_LONG).show();
return false;
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
AlertDialog.Builder dialog = new AlertDialog.Builder(HospitalMapsActivity.this);
dialog.setTitle("Book Cab");
dialog.setMessage("Do you want to book a cab?"/*HospitalMapsActivity.this.getResources().getString(R.string.gps_network_not_enabled)*/);
dialog.setPositiveButton("Book now"/*HospitalMapsActivity.this.getResources().getString(R.string.open_location_settings)*/, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent i = new Intent(HospitalMapsActivity.this, Book.class);
startActivity(i);
//get gps
}
});
dialog.setNegativeButton("Later"/*HospitalMapsActivity.this.getResources().getString(R.string.open_location_settings)*/, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
//get gps
}
});
dialog.show();
}
});
LocationManager lm = (LocationManager)HospitalMapsActivity.this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {
Toast.makeText(HospitalMapsActivity.this,"Something is wrong",Toast.LENGTH_LONG).show();
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {
Toast.makeText(HospitalMapsActivity.this,"Something is wrong",Toast.LENGTH_LONG).show();
}
if(gps_enabled==false /*&& network_enabled==false*/) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(HospitalMapsActivity.this);
dialog.setTitle("Location Services Disabled");
dialog.setMessage("Please enable location services."/*HospitalMapsActivity.this.getResources().getString(R.string.gps_network_not_enabled)*/);
dialog.setPositiveButton("Enable"/*HospitalMapsActivity.this.getResources().getString(R.string.open_location_settings)*/, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
HospitalMapsActivity.this.startActivity(myIntent);
//get gps
}
});
dialog.show();
}
mMap.addMarker(new MarkerOptions().position(new LatLng(20.260423, 85.777747)).title("AMRI HOSPITALS").icon(BitmapDescriptorFactory.fromResource(R.drawable.sp)));
}
#Override
public void onLocationChanged(Location arg0) {
LatLng latLng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15.0f);
mMap.animateCamera(cameraUpdate);
location.removeUpdates(this);
setUpMapIfNeeded();
//mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(20.269556,85.841157) , 14.0f) );
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}

To address your problems:
It does work on some phones (like Moto G 2nd Generation XT1068) but crashes on Lenovo A7000 whenever I search anything in the search bar and then press enter.
Please check the following:
Check if your Android platform is included in supported versions given in Android guide.
As mentioned in Google Places API - Troubleshooting, majority of the errors that your app is likely to experience are usually caused by configurations error. To get the status message for the errors that occur , call PlaceAutocomplete.getStatus() in onActivityResult() callback.
In using Place Autocomplete, please check if autocomplete is properly added to your app, as given in Place Autocomplete, using the following ways:
Add an autocomplete widget
Get place predictions programmatically
You may also check the given workaround in this GitHub post - Google Places Autocomplete does not work on mobile wherein a relevant code was placed into a function and then used the ng-focus directive to execute the expression on the desired element like:
<input id="searchBar" type="text" placeholder="Search" ng-focus="disableTap()">
Another problem I face is; I want to change the default google maps location that shows near South Africa. Change it to a specific location. How can I do that?
To change default google maps location and to get precise results, try given steps in Update your location on Google wherein you can:
Turn your location on or off, and
Check and update your location
For more information, please try going through the given documentations.
I hope one works for you.

Related

GPS-Service , Main Activity and Map Activity (Pass co-ordinates from service to map current location)

I am new to android and try to implement an activity with two tab one show co-ordinates which i got from GPS-Service and i want to mark that current location (co-ordinates value using marker) in map using coordinates value which i got from GPS services. And kindly help me for implementing Geo Fencing in map also.
GPS Service
package com.app.servicegps;
/**
* Created by Android on 29-Dec-16.
*/
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
public class GPS_Service extends Service {
private LocationListener listener;
private LocationManager locationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("coordinatesLongt",location.getLongitude());
i.putExtra("coordinatesLangt",location.getLatitude());
sendBroadcast(i);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);
}
#Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null){
//noinspection MissingPermission
locationManager.removeUpdates(listener);
}
}
}
Map Activity
package com.app.servicegps;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements LocationListener,OnMapReadyCallback,
SensorEventListener, DialogInterface.OnClickListener {
private GoogleMap mMap;
private BroadcastReceiver broadcastReceiver;
Marker now;
String langt = null;
String longt= null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onLocationChanged(Location location) {
if(now != null){
now.remove();
}
//TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
//double latitude = location.getLatitude();
// Getting longitude of the current location
// double longitude = location.getLongitude();
double latitude= Double.parseDouble(langt);
double longitude= Double.parseDouble(longt);
// Creating a LatLng object for the current location
// LatLng latLng = new LatLng(latitude, longitude);
LatLng latLng = new LatLng(latitude, longitude);
now = mMap.addMarker(new MarkerOptions().position(latLng));
// Showing the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//get value
if(intent.getAction().equals("location_update"))
{
langt=intent.getStringExtra("coordinatesLangt");
longt=intent.getStringExtra("coordinatesLongt");
}
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
/* LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
#Override
public void onSensorChanged(SensorEvent event) {
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
Main Activity
package com.app.servicegps;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button btn_start, btn_stop;
private TextView textView;
private BroadcastReceiver broadcastReceiver;
#Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
textView.append("\n" +intent.getExtras().get("coordinates"));
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}
#Override
protected void onDestroy() {
super.onDestroy();
if(broadcastReceiver != null){
unregisterReceiver(broadcastReceiver);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.button);
btn_stop = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView);
if(!runtime_permissions())
enable_buttons();
}
private void enable_buttons() {
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i =new Intent(getApplicationContext(),GPS_Service.class);
startService(i);
}
});
btn_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),GPS_Service.class);
stopService(i);
}
});
}
private boolean runtime_permissions() {
if(Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},100);
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 100){
if( grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
enable_buttons();
}else {
runtime_permissions();
}
}
}
}
Kindly help me for Geo fencing how i implement it it map activity.
The basic this i want is a main activity with tabs fragments.
Fragment 1st - Show Coordinates
Fragment 2nd Show Map
And A Geo Fencing To Show Notification when i enter in a tag place.
Interface class
public interface LocationInter {
void onUpdateLocation(Location location);
}
Implement the interface in main activity.
Add below lines in GPS service class.
private static LocationInter locationListener = null;
public void LocationInstance(LocationGuideInter locationListeners) {
if (locationListener == null) {
locationListener = locationListeners;
}
}
In Location change add this line
if (locationListener != null) {
locationListener.onUpdateLocation(location);
}
This is taken from android documentation so you can look at more details here
Set up for Geofence Monitoring
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Create geofence objects
Use Geofence.Builder to create a geofence, setting the desired radius, duration, and transition types for the geofence. For example, to populate a list object named mGeofenceList:
mGeofenceList.add(new Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this
// geofence.
.setRequestId(entry.getKey())
.setCircularRegion(
entry.getValue().latitude,
entry.getValue().longitude,
Constants.GEOFENCE_RADIUS_IN_METERS
)
.setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.build());
Specify geofences and initial triggers
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}
Define an Intent for geofence transitions
public class MainActivity extends FragmentActivity {
...
private PendingIntent getGeofencePendingIntent() {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
// calling addGeofences() and removeGeofences().
return PendingIntent.getService(this, 0, intent, PendingIntent.
FLAG_UPDATE_CURRENT);
}
Add geofences
public class MainActivity extends FragmentActivity {
...
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(this);
}
Handle Geofence Transitions
public class GeofenceTransitionsIntentService extends IntentService {
protected void onHandleIntent(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
String errorMessage = GeofenceErrorMessages.getErrorString(this,
geofencingEvent.getErrorCode());
Log.e(TAG, errorMessage);
return;
}
// Get the transition type.
int geofenceTransition = geofencingEvent.getGeofenceTransition();
// Test that the reported transition was of interest.
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
// Get the geofences that were triggered. A single event can trigger
// multiple geofences.
List triggeringGeofences = geofencingEvent.getTriggeringGeofences();
// Get the transition details as a String.
String geofenceTransitionDetails = getGeofenceTransitionDetails(
this,
geofenceTransition,
triggeringGeofences
);
// Send notification and log the transition details.
sendNotification(geofenceTransitionDetails);
Log.i(TAG, geofenceTransitionDetails);
} else {
// Log the error.
Log.e(TAG, getString(R.string.geofence_transition_invalid_type,
geofenceTransition));
}
}
Geofences tutorial from Raywendrlich here

how to get current location through gps using android

I am trying to create an android program to get the location
but unfortunately its throwing the exception as unfortunately APP is stopped
Can you suggest me please .code is the following
package com.example.ngo;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity
implements OnClickListener {
private LocationManager locationMangaer=null;
private LocationListener locationListener=null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to"+
" see the changes in coordinates."+"\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager
.GPS_PROVIDER, 5000, 10,locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----Method to Check GPS is enable or disable ----- */
#SuppressLint("NewApi") private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext()
.getContentResolver();
boolean gpsStatus = Settings.Secure
.isLocationProviderEnabled(contentResolver,
LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}

How to display a Dialog fragment inside location listener to trigger another activity

I have an app location listener which pops up toast alerts when the user gets within a specified distance of any point in a list. Instead of a toast popup I'd like to call a dialog fragment that, when the user selects yes, transfers the user into a quiz activity which asks them a question based on their location.
In short I want to be able to display this dialog fragment, instead of the toast, in my location listener activity. Thus far I have tried
DialogFragment dialog = new LocationDialog();
showDialog(dialog);
in place of the toast alert but I get the error "The method showDialog(DialogFragment) is undefined for the type QLocationListener. I've been going around in circles following various tutorials, guides and Google's android documentation without avail so some guidance would be greatly appreciated.
All my code is functioning as standalone apps I'm just struggling to link the location listener + main activity to the quiz via the dialog fragment. I also hope to be able to pass location information to the quiz in a bundle so it knows which question and answers to display but that's a task for another day...
Main Activity
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.location.LocationManager;
import android.os.Bundle;
public class MainActivity extends Activity {
private static final long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 1;
private static final long MINIMUM_TIME_BETWEEN_UPDATE = 1000;
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
QLocationListener qLL = new QLocationListener();
qLL.parentActivity = this;
// create the hard-coded list of points of interest
ArrayList<QuizContent> pointList = new ArrayList<QuizContent>();
// ExampleA
QuizContent MapPoint = new QuizContent(25,5, "example question?", "a", "b","c","d", "a");
// ExampleB
QuizContent MapPoint2 = new QuizContent(26,5, "example question?", "a", "b","c","d", "a");
// ExampleC
QuizContent MapPoint3 = new QuizContent(27,5, "example question?", "a", "b","c","d", "a");
pointList.add(MapPoint);
pointList.add(MapPoint2);
pointList.add(MapPoint3);
// now set up the location manager and listener
qLL.pointList = pointList;
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATE,
MINIMUM_DISTANCECHANGE_FOR_UPDATE,
qLL
);
}
}
QLocation Listener
import java.util.ArrayList;
import android.app.AlertDialog;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.widget.Toast;
import android.widget.TextView;
public class QLocationListener implements LocationListener {
public MainActivity parentActivity ;
// this is my list of quiz content (questions, answers, locations)
public ArrayList<QuizContent> pointList;
// this method is called when the location is changed
public void onLocationChanged(Location location) {
// now measure distance from all locations in quiz list
for (int i=0;i<pointList.size();i++){
QuizContent gp = pointList.get(i);
Location fixedLoc = new Location("one");
Double lat = Double.valueOf(String.valueOf(gp.getLatitude()));
Double lng = Double.valueOf(String.valueOf(gp.getLongitude()));
fixedLoc.setLatitude(lat);
fixedLoc.setLongitude(lng);
Log.i("location",lat+" "+location.getLatitude());
Log.i("location",lng+" "+location.getLongitude());
// calculate distance
float distance = location.distanceTo(fixedLoc);
if (i == 0) { // this is location a
if (distance < 10) {
DialogFragment dialog = new LocationDialog();
showDialog(dialog);
}
}
if (i == 1) { // this is location b
if (distance < 10) {
Toast.makeText(parentActivity.getBaseContext(),
"Welcome to location b", Toast.LENGTH_LONG).show();
}
}
if (i == 3) { // this is location c
if (distance < 10) {
Toast.makeText(parentActivity.getBaseContext(),
"Welcome to location c", Toast.LENGTH_LONG).show();
}
}
}
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
Dialog Fragment
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class LocationDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setMessage("Quiz Location Found, answer the question?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(getActivity(), Quiz.class));
// take the quiz!
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return alertDialog.create();
}
}
You need to call showDialog on Activity/App context
Try:
From activity:
QLocationListener qLocationListener= new QLocationListener(this)
In QLocationListener:
Activity act;
QLocationListener(Activity a)
{
//Constructor
act=a;
}
and then finally where you call showDialog:
act.showDialog(dialog);

Remove default user's location icon

Im developing an app using Google Maps v2 for Android and I managed to put a custom icon to the user's position but I can't remove the default one, so it overlays my custom icon like in the image:
(It is that big just for now :p )
My code is like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
map.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
if (location == null)
return;
mPositionMarker = map.addMarker(new MarkerOptions()
.flat(true)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.logop1))
.anchor(0.5f, 1f)
.position(new LatLng(location.getLatitude(), location.getLongitude())));
}
});
}
So:
1) Is there a way to remove the default blue dot of user's current location?
2) Will the user location be updated when I move in the "real world" (I cant test it for conectivity reasons) or do I have to write/override a method to update users position?
Thanks in advance
You will have to stop using GoogleMap.setMyLocationEnabled and write a bit more code, including having your own LocationClient and adding Circle for accuracy.
You have to do that on your own.
- set to false gmaps.getUiSettings().setMyLocationButtonEnabled(false);
create your own location button
if you get your current location, set a marker with your icon on that
if you click on your location button, move the camera and center it to the map
That will remove the blue dot
map.setMyLocationEnabled(true); remove line
Thanks joao2fast4u (lol) and ṁᾶƔƏň ツ. I followed your recomendations and I managed to make it work. Since I didn't see any answer concrete to this problem I'm posting my solution here:
package com.onsoftwares.ufvquest;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapActivity extends ActionBarActivity implements LocationListener, GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {
private GoogleMap map;
private Marker mPositionMarker;
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
private LatLng mLatLng;
private boolean mUpdatesRequested = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mLocationClient = new LocationClient(this, this, this);
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest.setFastestInterval(1000);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
}
#Override
protected void onStart() {
super.onStart();
mLocationClient.connect();
};
#Override
protected void onStop() {
if (mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(this);
mLocationClient.disconnect();
}
super.onStop();
};
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// Get the current location
Location currentLocation = mLocationClient.getLastLocation();
// Display the current location in the UI
if (currentLocation != null) {
LatLng currentLatLng = new LatLng (currentLocation.getLatitude(), currentLocation.getLongitude());
if (mPositionMarker == null) {
mPositionMarker = map.addMarker(new MarkerOptions()
.position(currentLatLng)
.title("Eu")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.male_user_marker)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15));
} else
mPositionMarker.setPosition(currentLatLng);
}
}
}

How to transfer data from one activity to another? Android application [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 8 years ago.
I want to trasfer data (a longitude and a latitude) from one activity to another. The goal is to transfer this data to the camera, to see how the objects (augmented reality) move in real-time.
LocationGoogleMap.class
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.beyondar.android.plugin.googlemap.GoogleMapWorldPlugin;
import com.beyondar.android.world.GeoObject;
import com.beyondar.android.world.World;
import com.example.pfg_v7.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class LocationGoogleMap extends FragmentActivity implements
OnMarkerClickListener, OnClickListener, LocationListener {
private GoogleMap mMap;
private GoogleMapWorldPlugin mGoogleMapPlugin;
private World mWorld;
Marker mMark;
private LocationManager oLoc;
private Location currentLoc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_google);
Button myLocationButton = (Button) findViewById(R.id.myLocationButton);
myLocationButton.setVisibility(View.VISIBLE);
myLocationButton.setOnClickListener(this);
Criteria oGPSSettings = new Criteria();
oGPSSettings.setAccuracy(Criteria.ACCURACY_FINE);
oGPSSettings.setSpeedRequired(true);
oGPSSettings.setAltitudeRequired(true);
oGPSSettings.setBearingRequired(true);
oGPSSettings.setCostAllowed(false);
oGPSSettings.setPowerRequirement(Criteria.POWER_MEDIUM);
oLoc = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = oLoc.getBestProvider(oGPSSettings, true);
if (provider != null) {
oLoc.requestLocationUpdates(provider, 1000, 1, this);
} else {
Toast.makeText(getBaseContext(), "No GPS", Toast.LENGTH_SHORT)
.show();
finish();
}
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (mMap == null) {
return;
}
// We create the world and fill the world
mWorld = CreateWorld.generateObjects(this);
// As we want to use GoogleMaps, we are going to create the plugin and
// attach it to the World
mGoogleMapPlugin = new GoogleMapWorldPlugin(this);
// Then we need to set the map into the GoogleMapPlugin
mGoogleMapPlugin.setGoogleMap(mMap);
// Now that we have the plugin created let's add it to our world.
// NOTE: It is better to load the plugins before start adding object in
// to the world.
mWorld.addPlugin(mGoogleMapPlugin);
mMap.setOnMarkerClickListener(this);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mGoogleMapPlugin.getLatLng(), 15));
mMap.animateCamera(CameraUpdateFactory.zoomTo(19), 2000, null);
}
#Override
public void onLocationChanged(Location location) {
currentLoc = location;
LatLng oPos = new LatLng(currentLoc.getLatitude(),
currentLoc.getLongitude());
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (mMap != null) {
mMap.clear();
mMark = mMap.addMarker(new MarkerOptions().position(oPos).title(
"My Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(oPos, 17));
}
// We create the world and fill the world
mWorld = CreateWorld.generateObjects(this);
// As we want to use GoogleMaps, we are going to create the plugin and
// attach it to the World
mGoogleMapPlugin = new GoogleMapWorldPlugin(this);
// Then we need to set the map into the GoogleMapPlugin
mGoogleMapPlugin.setGoogleMap(mMap);
// Now that we have the plugin created let's add it to our world.
// NOTE: It is better to load the plugins before start adding object in
// to the world.
mWorld.addPlugin(mGoogleMapPlugin);
}
/*
*
* mMap = ((SupportMapFragment)
* getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); if
* (mMap == null) { return; }
*
* // We create the world and fill the world mWorld =
* CreateWorld.generateObjects(this);
*
*
*
* // As we want to use GoogleMaps, we are going to create the plugin and //
* attach it to the World mGoogleMapPlugin = new GoogleMapWorldPlugin(this);
* // Then we need to set the map into the GoogleMapPlugin
* mGoogleMapPlugin.setGoogleMap(mMap); // Now that we have the plugin
* created let's add it to our world. // NOTE: It is better to load the
* plugins before start adding object in // to the world.
* mWorld.addPlugin(mGoogleMapPlugin);
*
* //NO
* AÑADIDO//////----------------------------------------////////////////
* ////////////////////////////////////////
* mMap.setOnMarkerClickListener(this);
*
* mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mGoogleMapPlugin.getLatLng
* (), 15)); mMap.animateCamera(CameraUpdateFactory.zoomTo(19), 2000, null);
* //NO
* AÑADIDO/////-----------------------------------------////////////////
* /////////////////////////////////////////
*
* // Lets add the user position to the map GeoObject user = new
* GeoObject(1000l); user.setGeoPosition(mWorld.getLatitude(),
* mWorld.getLongitude()); user.setImageResource(R.drawable.flag);
* user.setName("User position"); mWorld.addBeyondarObject(user);
*
* BeyondarLocationManager.addWorldLocationUpdate(mWorld);
* BeyondarLocationManager.addGeoObjectLocationUpdate(user);
*
* // We need to set the LocationManager to the BeyondarLocationManager.
* BeyondarLocationManager .setLocationManager((LocationManager)
* getSystemService(Context.LOCATION_SERVICE));
*/
#Override
public boolean onMarkerClick(Marker marker) {
// To get the GeoObject that owns the marker we use the following
// method:
GeoObject geoObject = mGoogleMapPlugin.getGeoObjectOwner(marker);
if (geoObject != null) {
Toast.makeText(
this,
"Click on a marker owned by a GeoOject with the name: "
+ geoObject.getName(), Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
protected void onResume() {
super.onResume();
// When the activity is resumed it is time to enable the
// BeyondarLocationManager
oLoc.removeUpdates(this);
oLoc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
}
#Override
protected void onPause() {
super.onPause();
// To avoid unnecessary battery usage disable BeyondarLocationManager
// when the activity goes on pause.
oLoc.removeUpdates(this);
}
#Override
public void onClick(View v) {
// When the user clicks on the button we animate the map to the user
// location
LatLng userLocation = new LatLng(currentLoc.getLatitude(),
currentLoc.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
mMap.animateCamera(CameraUpdateFactory.zoomTo(19), 2000, null);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
oLoc.removeUpdates(this);
oLoc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
}
#Override
public void onProviderEnabled(String provider) {
oLoc.removeUpdates(this);
oLoc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
Toast.makeText(getBaseContext(), provider + " is enabled.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
oLoc.removeUpdates(this);
Toast.makeText(getBaseContext(), provider + " is disabled.",
Toast.LENGTH_SHORT).show();
}
}
CameraWithLocation.class
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import com.beyondar.android.fragment.BeyondarFragmentSupport;
import com.beyondar.android.world.World;
public class CameraWithLocation extends FragmentActivity implements
OnSeekBarChangeListener, OnClickListener {
private BeyondarFragmentSupport mBeyondarFragment;
private World mWorld;
private SeekBar mSeekBarMax, mSeekBarMin;
private Button mShowMap;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
loadViewFromXML();
// We create the world and fill it ...
mWorld = CreateWorld.generateObjects(this);
// .. and send it to the fragment
mBeyondarFragment.setWorld(mWorld);
// We also can see the Frames per seconds
mBeyondarFragment.showFPS(true);
}
private void loadViewFromXML() {
setContentView(R.layout.camera_with_location);
mBeyondarFragment = (BeyondarFragmentSupport) getSupportFragmentManager()
.findFragmentById(R.id.beyondarFragment);
mSeekBarMax = (SeekBar) findViewById(R.id.seekBarMax);
mSeekBarMin = (SeekBar) findViewById(R.id.seekBarMin);
mSeekBarMax.setOnSeekBarChangeListener(this);
mSeekBarMin.setOnSeekBarChangeListener(this);
mSeekBarMax.setMax(100);
mSeekBarMin.setMax(100);
mShowMap = (Button) findViewById(R.id.showMapButton);
mShowMap.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == mShowMap) {
Intent intent = new Intent(this, LocationGoogleMap.class);
startActivity(intent);
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (seekBar == mSeekBarMax) {
mBeyondarFragment.setMaxFarDistance(progress);
} else if (seekBar == mSeekBarMin) {
mBeyondarFragment.setMinFarDistanceSize(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
CreateWorld.class
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.beyondar.android.plugin.googlemap.GoogleMapWorldPlugin;
import com.beyondar.android.world.GeoObject;
import com.beyondar.android.world.World;
import com.example.pfg_v7.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class CreateWorld{
public static final int LIST_TYPE_EXAMPLE_1 = 1;
public static World sharedWorld;
public static World generateObjects(Context context) {
if (sharedWorld != null) {
return sharedWorld;
}
sharedWorld = new World(context);
// The user can set the default bitmap. This is useful if you are
// loading images form Internet and the connection get lost
sharedWorld.setDefaultImage(R.drawable.beyondar_default_unknow_icon);
// User position (you can change it using the GPS listeners form Android
// API)
sharedWorld.setGeoPosition(40.332177, -3.766126);
// Create an object with an image in the app resources.
GeoObject go1 = new GeoObject(1l);
go1.setGeoPosition(40.390691, -3.636787);
go1.setImageResource(R.drawable.rectangle);
go1.setName("CercaDeCasa");
GeoObject go2 = new GeoObject(2l);
go2.setGeoPosition(40.391076, -3.635275);
go2.setImageResource(R.drawable.rectangle);
go2.setName("Cruce Superior");
GeoObject go3 = new GeoObject(3l);
go3.setGeoPosition(40.390821, -3.635967);
go3.setImageResource(R.drawable.rectangle);
go3.setName("Cruce del parque");
GeoObject go4 = new GeoObject(4l);
go4.setGeoPosition(40.390288, -3.635356);
go4.setImageResource(R.drawable.rectangle);
go4.setName("Callejuela");
// Add the GeoObjects to the world
sharedWorld.addBeyondarObject(go1);
sharedWorld.addBeyondarObject(go2);
sharedWorld.addBeyondarObject(go3);
sharedWorld.addBeyondarObject(go4);
return sharedWorld;
}
}
To sum up: I'd need to give to the Camera class the information about my location.
For example :
In MainActivity :
Intent intent = new Intent();
intent.setClass(this, Other_Activity.class);
intent.putExtra("EXTRA_ID", "SOME DATAS");
startActivity(intent);
In Other_Activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String datas= extras.getString("EXTRA_ID");
if (datas!= null) {
// do stuff
}
}
More informations here :
http://developer.android.com/reference/android/content/Intent.html
taken from here: Simple example for Intent and Bundle
Check this link please..
It says..
Use this to "put" the file...
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String keyIdentifer = null;
i.putExtra("STRING_I_NEED", strName);
startActivity(i);
Then, to retrieve the value try something like:
String newString;
if (savedInstanceState == null) {
extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}

Categories

Resources