I am using google play service for a running app i am making. I am getting the problem that onlocationchanged is not being called. First i though it was the android device that was not working but after testing it with GPS test it seems the device was working as it should. So it must be my code. Onlocationchanged is just not being called by the gps_provider but when i use network_provider it is working but the updates are so slow and in accurate that you can't build a sport runner app with it.
This is my code, what should i do to fix this?
this is in my manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.befitdonate.befitdonate.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
This is my fragment i am using to track the users route on the map.
public class WorkoutActivity extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static String TAG = WorkoutActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationRequest mLocationRequest;
MapView mapView;
GoogleMap map;
private GoogleApiClient mGoogleApiClient;
private SharedPreferences preferenceSettings;
private SharedPreferences.Editor preferenceEditor;
private static final int PREFERENCE_MODE_PRIVATE = 0;
private static final String PREF_NAME = "UserDetails";
public static final String POST_USEREMAIL = "username";
MainActivity mainactivity;
String emailUser, workoutType;
Button stopWorkout, startWorkout;
TextView speed, info;
ImageView workoutImage;
LinearLayout mapLayout, startWorkoutLayout;
Double currentLat, currentLong;
Double Lat, Longi;
String latLong = "No Location Found!!!";
LocationManager lManager;
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
//counter that is incremented every time a new position is received, used to calculate average speed
int counter = 0;
//objects to store values for current and average speed
protected double currentSpeed;
protected double kmphSpeed;
protected double avgSpeed;
protected double avgKmph;
protected double totalSpeed;
protected double totalKmph;
ArrayList<LatLng> polylines;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferenceSettings = this.getActivity().getSharedPreferences(PREF_NAME, PREFERENCE_MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
emailUser = preferenceSettings.getString("Email", null);
Log.d("Saved user email:", "" + emailUser);
Bundle bundle = this.getArguments();
if (bundle != null) {
workoutType = bundle.getString("workoutType");
}
mGoogleApiClient = new GoogleApiClient.Builder(this.getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(1 * 1000) // 5 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_workout, container, false);
mapView = (MapView) view.findViewById(R.id.mapview);
stopWorkout = (Button) view.findViewById(R.id.stopWorkout);
startWorkout = (Button) view.findViewById(R.id.startWorkout);
startWorkoutLayout = (LinearLayout) view.findViewById(R.id.startWorkoutLayout);
mapLayout = (LinearLayout) view.findViewById(R.id.mapLayout);
workoutImage = (ImageView) view.findViewById(R.id.workoutImage);
speed = (TextView) view.findViewById(R.id.speed);
info = (TextView) view.findViewById(R.id.info);
mapView.onCreate(savedInstanceState);
mainactivity = (MainActivity )getActivity();
mainactivity.menuButton.setVisibility(View.GONE);
mainactivity.mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mainactivity.pageTitle.setText("Workout");
mapLayout.setVisibility(View.GONE);
polylines = new ArrayList<LatLng>();
// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
MapsInitializer.initialize(this.getActivity());
stopWorkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectOption();
}
});
workoutType = "walking";
startWorkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mapLayout.setVisibility(View.VISIBLE);
startWorkoutLayout.setVisibility(View.GONE);
}
});
if(workoutType.matches("running")){
Picasso.with(this.getActivity())
.load(R.drawable.newrun)
.fit()
.centerCrop()
.into(workoutImage);
}
if(workoutType.matches("cycling")){
Picasso.with(this.getActivity())
.load(R.drawable.newcycling)
.fit()
.centerCrop()
.into(workoutImage);
}
if(workoutType.matches("walking")){
Picasso.with(this.getActivity())
.load(R.drawable.newwalk)
.fit()
.centerCrop()
.into(workoutImage);
}
return view;
}
#Override
public void onDestroy() {
super.onDestroy();
mainactivity.mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
mapView.onResume();
mGoogleApiClient.connect();
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
//DO WHATEVER YOU WANT WITH GOOGLEMAP
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(false);
map.setTrafficEnabled(false);
map.setIndoorEnabled(true);
map.setBuildingsEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d(TAG, "Location update running");
handleNewLocation(location);
}
public void selectOption() {
final CharSequence[] items = { "Workout Opslaan", "Afbreken", "Sluiten" };
AlertDialog.Builder builder = new AlertDialog.Builder(WorkoutActivity.this.getActivity());
builder.setTitle("Workout opties");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Workout Opslaan")) {
} else if (items[item].equals("Afbreken")) {
mapView.onDestroy();
mainactivity.mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
mainactivity.menuButton.setVisibility(View.VISIBLE);
if (mGoogleApiClient.isConnected()) {
onDestroy();
}
Fragment fragment = new HomePage();
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment)
.commit();
} else if (items[item].equals("Sluiten")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
};
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this.getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
Lat = location.getLatitude();
Longi = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
CameraUpdate zoom=CameraUpdateFactory.zoomTo(17);
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(zoom);
counter++;
//current speed of the gps device
currentSpeed = round(location.getSpeed(),3, BigDecimal.ROUND_HALF_UP);
kmphSpeed = round((currentSpeed*3.6),3,BigDecimal.ROUND_HALF_UP);
//all speeds added together
totalSpeed = totalSpeed + currentSpeed;
totalKmph = totalKmph + kmphSpeed;
//calculates average speed
avgSpeed = round(totalSpeed/counter,3,BigDecimal.ROUND_HALF_UP);
avgKmph = round(totalKmph/counter,3,BigDecimal.ROUND_HALF_UP);
//gets position
currentLatitude = round(((double) (location.getLatitude())),3,BigDecimal.ROUND_HALF_UP);
currentLongitude = round(((double) (location.getLongitude())),3,BigDecimal.ROUND_HALF_UP);
String infoDetails = "Afstand: "+" | Tijd: ";
String updateSpeed = String.valueOf(kmphSpeed);
Log.d(TAG, updateSpeed.toString());
//info.setText();
speed.setText("Snelheid: "+updateSpeed+" km/hr");
buildPolyline();
}
//Method to round the doubles to a max of 3 decimal places
public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
public void buildPolyline(){
Log.d(TAG,"Adding polyline" );
LatLng polyline;
polyline = new LatLng(Lat, Longi);
polylines.add(polyline);
Log.d("Locations Array", ""+polylines);
map.addPolyline(new PolylineOptions().addAll(polylines).width(6.0f).color(Color.BLUE));
//map.moveCamera(CameraUpdateFactory.newLatLngZoom(Start, 14));
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.mapview))
.getMap();
// Check if we were successful in obtaining the map.
if (map != null) {
}
}
}
}
I have spend about a week trying several solution but still stuck with this problem. I need an accurate way to track the route of the runner. I can't find any sport app samples, but enough other location samples but nothing seems to be working. I hope someone can help me with this.
Thanks
you have to use Location manager and register for location updates.
Try adding this code:
protected LocationManager locationManager;
in onCreate() method call registerLocationUpdates();
void registerLocationUpdates() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_HIGH);
locationManager = (LocationManager)getActivity().getSystemService(LOCATION_SERVICE);
provider = locationManager.getBestProvider(criteria, true);
// Cant get a hold of provider
if (provider == null) {
Log.v(TAG, "Provider is null");
showNoProvider();
return;
} else {
Log.v(TAG, "Provider: " + provider);
}
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
Related
I'm a student currently learning and try to play around with google map api. Right now, I'm facing a problem with the getting the location lat, long. Yesterday, I can use it just fine, but suddenly I cannot use it anymore today. The code is kinda long, because I wanted to show that the app asked for permission for the location to be turn on before using the apps but I don't think I get it correctly. I don't think the app starts like how I wanted it to start.
The process should be, from previous activity intent to this MapsActivity will prompt the request permission to open location, and once the location is on, the google map marker will update to the current location.
Right now, the apps just keeps on crashing.
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
FusedLocationProviderClient mFusedLocationClient;
LocationRequest mLocationRequest;
LocationCallback mLocationCallback;
double mLocationLat, mLocationLong;
LocationSettingsRequest.Builder mLocationSettingsBuilder;
SettingsClient client;
Task<LocationSettingsResponse> task;
private static final int REQUEST_CHECK_SETTINGS = 0x1;
#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);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//toolbar.setTitle("AskForMech : Maps");
//toolbar.setLogo(R.drawable.ic_launcher);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(MapsActivity.this);
mLocationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
if(locationResult==null){
return;
} else {
mLocationLat = locationResult.getLastLocation().getLatitude();
mLocationLong = locationResult.getLastLocation().getLongitude();
}
}
};
setLocationRequestSettings();
}
public void getLocation(){ //error is here
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mLocationLat = location.getLatitude();
mLocationLong = location.getLongitude();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
getLocation(); //error is here
LatLng pos = new LatLng(mLocationLat, mLocationLong);
mMap.addMarker(new MarkerOptions().position(pos).title("You!"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(pos));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 18.00f));
}
#Override
protected void onResume() {
super.onResume();
//startLocationUpdate();
requestLocationUpdate();
}
#Override
protected void onPause() {
super.onPause();
if(mFusedLocationClient != null){
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
Toast.makeText(MapsActivity.this, "Listener is removed.", Toast.LENGTH_SHORT).show();
}
}
private void requestLocationUpdate(){
mLocationSettingsBuilder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
client = LocationServices.getSettingsClient(MapsActivity.this);
task = client.checkLocationSettings(mLocationSettingsBuilder.build());
task.addOnSuccessListener(MapsActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
startLocationUpdate();
}
});
task.addOnFailureListener(MapsActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if(e instanceof ResolvableApiException){
try{
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(MapsActivity.this, REQUEST_CHECK_SETTINGS);
}catch(IntentSender.SendIntentException sendEx) {
}
}
}
});
}
private void setLocationRequestSettings(){
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(3000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void startLocationUpdate(){
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(MapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
showExplanation();
} else {
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
0);
}
} else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
Toast.makeText(MapsActivity.this, "Location permission was granted!", Toast.LENGTH_SHORT).show();
}
}
private void showExplanation(){
AlertDialog.Builder builder = new AlertDialog.Builder(MapsActivity.this);
builder.setTitle("Requires Location Permission.");
builder.setMessage("This app needs location permission to get the location information.");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
0);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MapsActivity.this, "Sorry, this function cannot be used until permission is granted.",Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
}
you should use the callback method onLocationChanged() instead of getLastKnownLocation (). Indeed, getLastKnownLocation() can return null (see here)
I prefer to use onLocationChanged() that is called once a location change is detected. It turns out that it works great for me.
If you have any trouble to implement a LocationListener, take a look at this post : https://stackoverflow.com/a/42218626/3780625
Best
I try to get current location when the app running in background, so I use service. However, the data does not change in background, the service does not work. I want to know the problem. Here is the code of the app.
MainActivity as follow:
public class MainActivity extends Activity {
Button btn_start;
private static final int REQUEST_PERMISSIONS = 100;
boolean boolean_permission;
TextView tv_latitude, tv_longitude, tv_address,tv_area,tv_locality;
SharedPreferences mPref;
SharedPreferences.Editor medit;
Double latitude,longitude;
Geocoder geocoder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.btn_start);
tv_address = (TextView) findViewById(R.id.tv_address);
tv_latitude = (TextView) findViewById(R.id.tv_latitude);
tv_longitude = (TextView) findViewById(R.id.tv_longitude);
tv_area = (TextView)findViewById(R.id.tv_area);
tv_locality = (TextView)findViewById(R.id.tv_locality);
geocoder = new Geocoder(this, Locale.getDefault());
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
medit = mPref.edit();
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boolean_permission) {
if (mPref.getString("service", "").matches("")) {
medit.putString("service", "service").commit();
Intent intent = new Intent(getApplicationContext(), GoogleService.class);
startService(intent);
} else {
Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
}
}
});
fn_permission();
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION
},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = Double.valueOf(intent.getStringExtra("latitude"));
longitude = Double.valueOf(intent.getStringExtra("longitude"));
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
tv_area.setText(addresses.get(0).getAdminArea());
tv_locality.setText(stateName);
tv_address.setText(countryName);
} catch (IOException e1) {
e1.printStackTrace();
}
tv_latitude.setText(latitude+"");
tv_longitude.setText(longitude+"");
tv_address.getText();
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(GoogleService.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
Service as follow:
public class GoogleService extends Service implements LocationListener{
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude,longitude;
LocationManager locationManager;
Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000;
public static String str_receiver =
"com.findmyelderly.findmyelderly.receiver";
Intent intent;
public GoogleService() {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
intent = new Intent(str_receiver);
// fn_getlocation();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private void fn_getlocation() {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnable && !isNetworkEnable) {
} else {
if (isNetworkEnable) {
location = null;
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
if (isGPSEnable) {
location = null;
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
}
private class TimerTaskToGetLocation extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
fn_getlocation();
}
});
}
}
private void fn_update(Location location){
intent.putExtra("latutide",location.getLatitude()+"");
intent.putExtra("longitude",location.getLongitude()+"");
sendBroadcast(intent);
}
}
build.gradle as follow
.........
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.android.support:multidex:1.0.0'
AndroidManifest as follow
..........
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
.........
<service android:name=".GoogleService" android:exported="false" android:enabled="true"/>
</application>
</manifest>
I am very puzzled.
One thing you could try is to check the permissions of the app on the phone itself. I've found with my device (Android version 6.0.1) it's not enough to just add "uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> and
"uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />"
in the manifest, you have to grant permissions to the app manually on the device.
To do this, go to Settings > Apps > 'yourApp' > Permissions and slide across the bar to turn on Location for that app.
I'm new enough to Android apps myself so there may be a bigger problem in your case I'm not sure but worth a try anyway!
I'm trying to display heatmap points in android using google maps utility library, nothing is displayed on the map. I don't know if I need something else, I've looked at examples but in my case it doesn't work. I'm using fragments.
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
private HeatmapTileProvider mProvider;
protected LatLng mCenterLocation = new LatLng( 39.7392, -104.9903 );
public MapFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
// For showing a move to my location button
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
// For dropping a marker at a point on the Map
LatLng colorado = new LatLng(39.7392, -104.9903);
googleMap.addMarker(new MarkerOptions().position(colorado).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(colorado).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
addHeatMap();
}
});
return rootView;
}
public void addHeatMap(){
ArrayList<LatLng> locations = generateLocations();
mProvider = new HeatmapTileProvider.Builder().data(locations).build();
mProvider.setRadius(HeatmapTileProvider.DEFAULT_RADIUS );
googleMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider));
}
private ArrayList<LatLng> generateLocations() {
ArrayList<LatLng> locations = new ArrayList<LatLng>();
double lat;
double lng;
Random generator = new Random();
for (int i = 0; i < 1000; i++) {
lat = generator.nextDouble() / 3;
lng = generator.nextDouble() / 3;
if (generator.nextBoolean()) {
lat = -lat;
}
if (generator.nextBoolean()) {
lng = -lng;
}
locations.add(new LatLng(mCenterLocation.latitude + lat, mCenterLocation.longitude + lng));
}
return locations;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
Checking the Heatmaps guide, I don't see any issues about it. Try to call clearTileCache(), its indicated in its API reference that you should call it after setRadius.
I have two activities in first activity, I have two text views fromLocation and toLocation. On click of from and to text view I am calling next activity in which I have a map and I choose a location which I am storing in string and showing on text view. This choose location I want to show on fromLocation text view of first activity onClick of a layout of useLocation in second activity on the basis of which text view is choose. If onClick of fromLocation the address should show on fromLocation text view and onClick of toLocation address should show on toLocation. This will be onResume method of first activity.
Now I am getting the address on both text views when I choose address for first time onClick on fromLocation text view.
How to do this..?
GoSendActivity(FirstActivity)
public class GoSend extends AppCompatActivity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private GoogleMap mGoogleMap;
private MarkerOptions markerOptions;
private LinearLayout ll;
private TextView additionalContactFrom,additionalContactTo,txt_from,txt_to;
private LinearLayout linearLayoutFrom,linearLayoutTo;
private ImageView next;
private Toolbar toolbar;
private EditText locdetailsFrom,locdetailsTo,itemDetails;
private Intent i;
private LatLng currentLocation,curentpoint,center;
private GPSTracker gps;
double latitude,longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gosendlayout);
setUI();
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
}
public void setUI() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("COURIER");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
locdetailsFrom = (EditText) findViewById(R.id.editText_from_details);
locdetailsFrom.setText(GoSendData.instance.getmFromLocationDetails());
locdetailsTo = (EditText) findViewById(R.id.editText_to_details);
locdetailsTo.setText(GoSendData.instance.getmToLocationDetails());
itemDetails = (EditText) findViewById(R.id.editText_ItemDetail);
txt_from = (TextView) findViewById(R.id.Text_from);
txt_to = (TextView) findViewById(R.id.Text_to);
additionalContactFrom = (TextView) findViewById(R.id.contactDetailsFrom);
additionalContactTo = (TextView) findViewById(R.id.contactDetailsTo);
linearLayoutFrom = (LinearLayout) findViewById(R.id.LinearLayoutFrom);
linearLayoutTo = (LinearLayout) findViewById(R.id.LinearLayoutTo);
next = (ImageView) findViewById(R.id.imageView_next);
txt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), PickLocationActivity.class);
/// GoSendData.instance.addressType=0;
startActivity(i);
}
});
txt_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), PickLocationActivity.class);
//GoSendData.instance.addressType=1;
startActivity(i);
}
});
additionalContactFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (linearLayoutFrom.getVisibility() == View.GONE) {
linearLayoutFrom.setVisibility(View.VISIBLE);
} else {
linearLayoutFrom.setVisibility(View.GONE);
}
}
});
additionalContactTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (linearLayoutTo.getVisibility() == View.GONE) {
linearLayoutTo.setVisibility(View.VISIBLE);
} else {
linearLayoutTo.setVisibility(View.GONE);
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), GoSendDetailsActivity.class);
startActivity(i);
}
});
}
#Override
public void onResume() {
int LocationClick;
super.onResume(); // Always call the superclass method first
txt_from.setText(GoSendData.instance.mFromLocation);
txt_to.setText(GoSendData.instance.mToLocation);
}
private void setupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mGoogleMap.addMarker(markerOptions);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
setupMap();
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
ChooseFromMapActivity(second activity)
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center,curentpoint;
private LinearLayout markerLayout,useLocation;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude,longitude;
private GPSTracker gps;
Intent intent;
double x, y;
StringBuilder str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
SetUpUI();
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(ChooseFromMapActivity.this,GoSend.class);
startActivity(intent);
}
});
}
private void SetUpUI(){
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("CHOOSE FROM MAP");
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
if ((addresses != null) && (addresses.size() > 0)) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
}
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
GoSendData.instance.mFromLocation=addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ";
GoSendData.instance.mToLocation=addresses.get(0).getAddressLine(0)+addresses.get(0).getAddressLine(1)+"";
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
If i understand correctly.. You should launch second activity as startActivityForResult and after choosing location on map return it as a result.
The first activity should now this value from the method onActivityResult
http://developer.android.com/training/basics/intents/result.html
Click on first textview launch second activity with requestcode
Second activity after choosing location finishes with setResult, where you store chosen location
Get the result in onActivityResult of first activity and set it to textView
the same for second textview. Use different requestcodes for different textview, which you should check in onActivityResult to determine which textView data was chosen in second activity
I am using map to get current location and now I want to send my current location to another activity which has form to input all the data.
I am confused about which variables and methods I should use to send the location data.
ChooseFromMapActivity
This is the activity where I am getting my current location. And now on Click of useLocation layout I want to send this location to the edit text of another activity i.e GoSendActivity.
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
private LinearLayout useLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
if ((addresses != null) && (addresses.size() > 0)) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
}
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
GoSendActivity
This is my GoSendActivity which has edit text view. I want to get the current location on edttxt_from text view.
public class GoSend extends AppCompatActivity {
LatLng latLng;
private GoogleMap mMap;
MarkerOptions markerOptions;
LinearLayout ll;
Toolbar toolbar;
EditText editTextLocation;
EditText edtxt_from;
EditText edtxt_to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gosendlayout);
setUI();
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void setUI() {
ll = (LinearLayout) findViewById(R.id.LinearLayoutGoSend);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("GO-SEND");
try {
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
edtxt_from=(EditText)findViewById(R.id.editText_from);
edtxt_to=(EditText)findViewById(R.id.editText_to);
edtxt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
edtxt_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
}
}
Location class
public class Location {
private int id;
private String mFrom_loc;
private String mTo_loc;
private String mFromloc_details;
private String mToloc_details;
private String mItems_details;
public Location(int id,String mFrom_loc,String mFromloc_details,String mTo_loc,String mToloc_details,String mItems_details)
{
this.id=id;
this.mFrom_loc=mFrom_loc;
this.mFromloc_details=mFromloc_details;
this.mTo_loc=mTo_loc;
this.mToloc_details=mToloc_details;
this.mItems_details=mItems_details;
}
public Location(String mFrom_loc){
this.mFrom_loc=mFrom_loc;
}
public Location(){}
public int getId(int id){return id;}
public String getmFrom_loc(String mFrom_loc){return mFrom_loc;}
public String getmTo_loc(String mTo_loc){return mTo_loc;}
public String getmFromloc_details(String mFromloc_details){return mFromloc_details;}
public String getmToloc_details(String mToloc_details){return mToloc_details;}
public String getmItems_details(String mItems_details){return mItems_details;}
public void setId(){this.id=id;}
public void setmFrom_loc(){this.mFrom_loc=mFrom_loc;}
public void setmTo_loc(){this.mTo_loc=mTo_loc;}
public void setmFromloc_details(){this.mFromloc_details=mFromloc_details;}
public void setmToloc_details(){this.mToloc_details=mToloc_details;}
public void setmItems_details(){this.mItems_details=mItems_details;}
}
How can I achieve this?? Please help..
try this :
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChooseFromMapActivity.this , GoSendActivity.class);
intent.putExtra("Latitude", latitude);
intent.putExtra("Longitude", longitude);
startActivity(intent);
}
});
And inside onCreate of GoSendActivity,get latitude and longitude like this :
Bundle extras = getIntent().getExtras();
if (extras != null) {
double latitude = extras.getDouble("Latitude");
double longitude = extras.getDouble("Longitude");
}
Now you can set latitude and longitude to your edittext edittext.setText(String.valueOf(latitude));
Apart from passing the data to the next activity using intents, you can also use shared preferences, TinyDB lib achieves great results for caching data. Yoou will need to sync this in your gradle file :
compile 'com.mukesh:tinydb:1.0.1'
then in your onCreate in each activity you will be using the same, initialize the tinyDB by passing application context
TinyDB tinyDB = new TinyDB(getApplicationContext());
With that you can store and retrieve any data within the app using a key-value pair,example to store your coordinates, just call :
tinyDB.putDouble("latitude",latitude);
tinyDB.putDouble("longitude",longitude);
And you can retrieve the data this way:
double latitude = tinyDB.getDouble("latitude");
double longitude = tinyDB.getDouble("longitude");
This class supports all data formats, from Strings,Double,Float and even objects such as ararayLists. Would highly recommend you to try it out.
Make this class as serialisable and put it into intent using bundle.putSerializable("myclaa",location).
Class Location implements Seraializable{
}