Android – java, send location-data from a class toward and activity-view - android

please help me with this, I´m working with android studio – java. I have an Activity(MainActivity) where I want to show the information about location; but I want this information come from other class(Location) toward this MainActivity, how can I make this location class send the location data automatically.
Well, I had try to call the method in MainActivity where I get the location data from class-location, but this methods has parameters “Location location”, so I can’t call it directly.
And I had try put a method inside the “location method” to send the information, but It doesn’t work
I declare the location variables global and put It in other method to send them but doesn’t’ work
I´m trying using the location information (latitude and longitude) from a class using extra, but how can get the data.
Anyway… please help me, the Idea is pass the location information: “getLatitude()”and “getLongitude()” for a class to my MainActivity automatically and to a DDBB later.
So much thank for any help
this is "the MainActivity" class
public class MainActivity extends AppCompatActivity {
TextView tvlatitud, tvlongitud;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvlongitud = findViewById(R.id.tv_longitud);
tvlatitud = findViewById(R.id.tv_latitud);
location = new Location(this);
askLocation();
}
public void askLocation(){
location.updateGPS();
}
public void showData(String lat, String lon ){
tvlatitud.setText(lat);
tvlongitud.setText(lon);
}
and this is the Location class
public class Location extends AppCompatActivity {
private static final int PERMISSIONS_FINE_LOCATION = 99;
FusedLocationProviderClient fusedLocationProviderClient;
LocationRequest locationRequest;
String latitude1, longitude1;
private MainActivity mainActivity;
public Location(MainActivity mainActivity){
this.mainActivity = mainActivity;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationRequest = new LocationRequest();
locationRequest.setInterval(1000 * 30);
locationRequest.setFastestInterval(1000 * 50);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
updateGPS();
}
public void updateGPS() {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(Location.this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<android.location.Location>() {
#Override
public void onSuccess(android.location.Location location) {
updateUIValues(location);
mainActivity.showData(latitude1, longitude1);
}
});
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,}, PERMISSIONS_FINE_LOCATION);
}
}
}
private void updateUIValues(android.location.Location location) {
latitude1 = String.valueOf(location.getLatitude());
longitude1 = String.valueOf(location.getLongitude());
}
}

Related

Android GoogleMaps - Inheriting a map fragment from a base fragment activity abstract class

I'm working on a project where I am switching between two map activities.
The structure I'm attempting is something like this:
BaseMapsActivity extends FragmentActivity
MapsActivity1 extends BaseMapsActivity
MapsActivity2 extends BaseMapsActivity
In order to prevent code duplication. I'd like to put my Google API client code in the base Activity and then some map styling code in the base onMapReady() and simply make changes for each sub activity afterwards (adding markers, etc).
My question is, how can I prepare this mapFragment with style and location logic in the base class, and then inflate a frame layout with the fragment in the sub activities to modify it? How would the steps of this process play out? Is this even possible?
public abstract class BaseMapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
public static final String TAG = "BaseMapsActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.base_map_activity);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e(TAG, "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e(TAG, "Can't find style. Error: ", e);
}
mMap.moveCamera(CameraUpdateFactory.zoomTo(14));
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
and for the sub activity 1...
public class MapsActivity1 extends BaseMapsActivity implements LocationListener, View.OnClickListener {
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private GoogleMap mMap;
private FirebaseAuth firebaseAuth;
private FirebaseUser user;
private DatabaseReference databaseRef;
private static final String TAG = "MapsActivity1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onMapReady(mMap);
and the second activity...
public class MapsActivity2 extends BaseMapsActivity implements OnMapReadyCallback,
View.OnClickListener, OnProgressListener {
// GoogleMap mMap;
private static GoogleMap mMap;
SeekBar colorSeek;
private double longitude;
private double latitude;
private Bundle mapSpots;
private Button backToMap;
private SeekBar.OnSeekBarChangeListener seekBarListener;
private LatLng user;
private static final String TAG = "MapsActivity2";
private static final int HUE_MAX = 360;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
super.onMapReady(mMap);
Thanks T
Needed to call super.onMapReady(Bundle savedInstanceState) not in the onMapReady override in the child class, so instead of:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
super.onMapReady(mMap);
It needs to be this:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
super.onMapReady(mMap);
#Override
protected void onMapReady(GoogleMap googleMap){
mMap = googleMap;
super.onMapReady(mMap);

Adding Markers in Maps during app is running unsuccessful

I have been trying to implement markers in my google maps activity while the application runs. There are some pre-defined "Location" objects, and there is a marker at the "current location" of the user.
Using a SeekBar, I'm trying to change the range of the current location in which the markers of the location objects should be displayed, but on changing the SeekBar, nothing happens (no markers get added, there's just one at the current location). Apologies for the unwanted extra code, I believe the most important parts to look at are onConnected(), onSeekBarChangedListener() and onMapReady()
This is my MapsActivity.java:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.
OnConnectionFailedListener, OnSeekBarChangeListener {
private GoogleApiClient googleApiClient;
private SeekBar rangeSeekBar;
private GoogleMap mMap;
private Intent intent;
private Location currentLocation;
private Location[] locations;
private double range;
Location locationOne;
Location locationTwo;
Location locationThree;
Location locationFour;
Location locationFive;
Location locationSix;
Location locationSeven;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
locationOne = new Location("");
locationTwo = new Location("");
locationThree = new Location("");
locationFour = new Location("");
locationFive = new Location("");
locationSix = new Location("");
locationSeven = new Location("");
locationOne.setLatitude(10.1399);
locationOne.setLongitude(76.1784);
locationTwo.setLatitude(10.2244);
locationTwo.setLongitude(76.1978);
locationThree.setLatitude(9.6175);
locationThree.setLongitude(76.4301);
locationFour.setLatitude(9.5987);
locationFour.setLongitude(76.3116);
locationFive.setLatitude(9.6175);
locationFive.setLongitude(76.4301);
locationSix.setLatitude(9.6737);
locationSix.setLongitude(76.5610);
locationSeven.setLatitude(15.5152);
locationSeven.setLongitude(73.8565);
locations = new Location[]{
locationOne,
locationTwo,
locationThree,
locationFour,
locationFive,
locationSix,
locationSeven
};
rangeSeekBar = (SeekBar)findViewById(R.id.rangeSeekBar);
rangeSeekBar.setProgress(0);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
protected void onStop() {
super.onStop();
googleApiClient.disconnect();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng india = new LatLng(20.5937, 78.9629);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(india, 5));
if(googleApiClient==null){
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
googleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if(ContextCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MapsActivity.this,new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},1);
} else {
currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
LatLng currentLoc = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(currentLoc).title("Your current location"));
}
addingMarkersInRange(0);
}
public void addingMarkersInRange(double range){
for(int i=0;i<locations.length;i++){
if(currentLocation.distanceTo(locations[i])<range) {
LatLng tempLatLng = new LatLng(locations[i].getLatitude(), locations[i].getLongitude());
mMap.addMarker(new MarkerOptions().position(tempLatLng));
mMap.moveCamera(CameraUpdateFactory.newLatLng(tempLatLng));
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
addingMarkersInRange(rangeSeekBar.getProgress()*700000);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
Your addinMarkersInRange() method is only adding markers for LatLngs in locations array. So, you need to add to locations array before invoking addingMarkersInRange. But, since you cannot add to an array, please change locations to a List and you should be good to go.
You are not setting listener on SeekBar object. Please set OnSeekBarChangeListener like so in your onCreate():
// code you already have
rangeSeekBar = (SeekBar)findViewById(R.id.rangeSeekBar);
rangeSeekBar.setProgress(0);
// register event listener here
rangeSeekBar.setOnSeekBarChangeListener(this);
I think you have issue in addingMarkersInRange().
But let proceed in a way,
First set listener to seekbar. Then set max value of seekbar.
Now initially call addingMarkersInRange(1) instead of passing zero.
Now while seek bar change make use of isfromUser flag in onProgress change.
And remove that onCameraChange() & place it outside of for loop. And use latlongbound to animate camera zoom level.
Now run and check any change made on UI ...!

Android GPS location always null inside AsyncTask

I am trying to get the current location of the user from an asynctask. My application depends on the latitude and longitude values. I am trying to show a ProgressDialog to the user till the location is fetched.
Problem :- The location value is always null. I know that getting gps location takes time. But my location value is null even after waiting for sometimes. Its always null.
Below is my code :-
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//some action …
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (id == R.id.action_settings)
{
return true;
}
if(id == R.id.action_location)
{
LocationTask locGetter = new LocationTask(MainActivity.this);
locGetter.execute();
}
return super.onOptionsItemSelected(item);
}
}
Below is my AsyncTask
public class LocationTask extends AsyncTask<Void,Void,Void> implements LocationListener
{
private ProgressDialog dialog;
private Activity callingActivity;
LocationManager locationManager;
String provider = LocationManager.GPS_PROVIDER;
public LocationTask(Activity activity)
{
callingActivity = activity;
}
#Override
protected void onPreExecute()
{
dialog= ProgressDialog.show(callingActivity,"Getting Co-ordinates","Please Wait....");
}
#Override
protected Void doInBackground(Void... voids)
{
locationManager = (LocationManager) callingActivity.getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(provider);
showLocation(location);
return null;
}
private void showLocation(Location location)
{
if(location == null)
{
Log.d("Location","Failed to get location");
}
else
{
Log.d("Location","Latitude :- "+location.getLatitude()+" Longitude :- "+location.getLongitude());
}
}
#Override
protected void onPostExecute(Void aVoid)
{
dialog.dismiss();
super.onPostExecute(aVoid);
}
#Override
public void onLocationChanged(Location location)
{
showLocation(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
UPDATE :-
As mentioned by Ivan I have modified my AsyncTask to get location as below :-
#Override
protected Void doInBackground(Void... voids) {
locationManager = (LocationManager) callingActivity.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(provider,0,0,this);
if(locationManager != null) {
Location location = locationManager.getLastKnownLocation(provider);
showLocation(location);
}
return null;
}
But this throws "windows leaked" exception in the dialog= ProgressDialog.show(callingActivity,"Getting Co-ordinates","Please Wait...."); inside onPrexecute() method.
Seems to me that you might be missing the requestLocationUpdates(...) call.
Please check this related question for a better understanding on what might be missing, as it sure doesn't look to be a problem with it being inside an AsyncTask, although I don't really see the need for the AsyncTask in your snippet.
Have you tried using String locationProvider = LocationManager.NETWORK_PROVIDER;
to determine if it's the provider that's the issue?
Ivan has mentioned that you won't get updates, but as I understand you're still just looking for the last known location.

Mapbox - Use gps location

I develop an Android app.
I want to stock the gps location and draw a line on the map with these datas, like "draw my course".
What's the best way ?
I designed my map with TileMill.
Where can I stock my data and use it with mapbox?
This is my code :
public class GPSActivity extends Activity{
private LocationManager manager = null;
private MyLocationListener listener;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.location);
listener = new MyLocationListener(textView);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener(textView);
manager.requestLocationUpdates(LocationManager
.GPS_PROVIDER, 5000, 10,listener);
}
public class MyLocationListener implements LocationListener
{
TextView textView;
public MyLocationListener(TextView textView)
{
this.textView = textView;
}
#Override
public void onLocationChanged(Location location) {
this.textView.setText(location.toString());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
--> With this code, I have the location. I would like to stock longitude and latitude and use these with mapbox. What's the best way to stock these datas?
I start to design my map on map box : https://a.tiles.mapbox.com/v3/malicia.hh3dgalc/page.html?secure=1#13/48.1169/-1.6803
It will be an interactive map, I want to draw an itinerary with the datas stocked.
Can someone help me?

How to supply location services to diffent activities on Android

I am currently working on an Android app and I am new to the field.
I want to do the following:
Create a class that encapsulates the required features to let an activity know the users location and deliver a map to the activity
This should accomplish the following:
I have a class that connects to the location services to get information and other activities can use this class to get a map (fragment) along with other information (lat long etc) for programmatic use.
I cannot figure it out...I do not want my stuff to an Activity itself
But it seems as if the whole Google Location API of the Play services relies on it being a FragmentActivity (whatever that is)
Any ideas?
PS: I need to maintain support for 2.3.3
UPDATE
I made it to implement a class extending SupportMapFragment (shortened), but I am having trouble with the error handling for the GMS. Works fine on my Galaxy Note 3 but the emulator has an older version of GMS which (due to currently crappy errorhandling) eventually leads to a NullPointer Exception:
public class LocationFragment extends SupportMapFragment implements GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
view = inflater.inflate(R.layout.map_fragment, container, false);
initilizeMap();
configureLocationClient();
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
// Start with updates turned off
updatesRequested = false;
map.getUiSettings().setMyLocationButtonEnabled(true);
locationClient = new LocationClient(activity.getBaseContext(), this, this);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
checkGooglePlayServices();
}
private boolean checkGooglePlayServices() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity.getBaseContext());
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d(TAG + ".servicesConnected()", "Google Play services is available.");
// Continue
return true;
// Google Play services was not available for some reason
} else {
Log.d(TAG + ".servicesConnected()", "Google Play services is unavailable or outdated: " + resultCode);
// Get the error dialog from Google Play services
try {
GooglePlayServicesUtil.getErrorDialog(resultCode, activity, CONNECTION_FAILURE_RESOLUTION_REQUEST).show();
} catch (Exception e) {
Log.e("Error: GooglePlayServiceUtil: ", "" + e);
}
/**
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(resultCode, activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(activity.getSupportFragmentManager(),"Location Updates");
}*/
return false;
}
}
The corresponding Activity is:
public class LocationTest extends FragmentActivity implements LocationListener {
private static final String TAG = LocationTest.class.getSimpleName();
private int count = 0;
private TextView lat;
private TextView lng;
private TextView quality;
private TextView conState;
private TextView refreshCount;
private TextView distance;
private LocationFragment locFrag;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationtest);
FragmentManager fManager = getSupportFragmentManager();
locFrag = new LocationFragment();
FragmentTransaction ft = fManager.beginTransaction();
ft.replace(R.id.map, locFrag);
ft.addToBackStack(null);
ft.commit();
locFrag.setGoal(Double.valueOf(8.83749747285), Double.valueOf(53.0663656578));
lat = (TextView) findViewById(R.id.curLat);
lng = (TextView) findViewById(R.id.curLng);
quality = (TextView) findViewById(R.id.curQuality);
conState = (TextView) findViewById(R.id.conState);
refreshCount = (TextView) findViewById(R.id.count);
distance = (TextView) findViewById(R.id.distance);
}
public void refreshLocation(View v) {
locFrag.refreshLocation(v);
}
public void toggleUpdates(View v) {
locFrag.toggleUpdates(v);
}
public void onLocationChanged(Location location) {
// Let the location parent know about the location change
// super.onLocationChanged(location);
count++;
lat.setText(Double.toString(locFrag.getCurrentLatitude()));
lng.setText(Double.toString(locFrag.getCurrentLongitude()));
quality.setText(Float.toString(locFrag.getAccuracy()));
conState.setText(Boolean.toString(locFrag.isConnected()));
refreshCount.setText(Integer.toString(count));
distance.setText(Float.toString(locFrag.getDistance()));
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart()");
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause()");
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop()");
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume()");
}
}
I wonder if it is possible to get the ErrorDialog suggested by google to work from that SupportMapFragment to be able to handle the error or else stop the inflation of the fragment and return to the previous activity
any help appreciated :)
Use this code in present class which is capturing the location
currentLocation is the location Object
Intent intent = new Intent(this,target.class)
Bundle b = new Bundle();
b.putParcelable("Location", currentLocation);
i.putExtra("Location", b);
startActivity(i);
Receive Activity code:
b = getArguments();
Location location = b.getParcelable("Location");
By this way you can pass the location.I think it may be useful to you.

Categories

Resources