How to make the mapview get from current location? - java

As title, how to make the mapview zoom into the current location? By the way, I can get the current Log and Lon in getLocation(). Just don't know how to implement into the map. Thanks in advance someone who can help me.. I'm new to the android studio. This problem have make me confuse few day already.
package com.example.edward.neweventmanagementsystem;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Places;
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.MapView;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class StaffAttendanceCheckIn extends AppCompatActivity {
private TextView mtxtTime, mtxtDate, txtDisplayName;
private Spinner eventSpinner;
private static final int REQUEST_LOCATION = 1;
TextView textLocation;
LocationManager locationManager;
String latitude,longitude;
MapView mapview;
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_staff_attendance_check_in);
mtxtDate = (TextView) findViewById(R.id.txtCurrentDate);
mtxtTime = (TextView) findViewById(R.id.txtCurrentTime);
txtDisplayName = (TextView) findViewById(R.id.txtDisplayName);
eventSpinner = (Spinner) findViewById(R.id.eventSpinner);
mapview = (MapView) findViewById(R.id.mapview);
mapview.onCreate(savedInstanceState);
SimpleDateFormat date = new SimpleDateFormat("EEEE dd MMM yyyy", Locale.ENGLISH);
String currentDate = date.format(new Date());
SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");
String currentTime = time.format(new Date());
mtxtDate.setText(currentDate);
mtxtTime.setText(currentTime);
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser() ;
txtDisplayName.setText(currentFirebaseUser.getDisplayName());
/**
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("EventName");
System.out.println("Test Script: " + myRef); */
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
textLocation = (TextView)findViewById(R.id.location);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
getLocation();
}
}
// #Override
// public void onClick(View view) {
//
// }
private void getLocation() {
if (ActivityCompat.checkSelfPermission(com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);
if (location != null) {
double latti = location.getLatitude();
double longi = location.getLongitude();
latitude = String.valueOf(latti);
longitude = String.valueOf(longi);
textLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);
float ZOOM_MAP = 17.0f;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(latLng, ZOOM_MAP);
map.animateCamera(myLocation);
// CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(latLng, ZOOM_MAP);
// System.out.println("Test Script" + myLocation);
// map.animateCamera(myLocation);
} else if (location1 != null) {
double latti = location1.getLatitude();
double longi = location1.getLongitude();
latitude = String.valueOf(latti);
longitude = String.valueOf(longi);
textLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);
} else if (location2 != null) {
double latti = location2.getLatitude();
double longi = location2.getLongitude();
latitude = String.valueOf(latti);
longitude = String.valueOf(longi);
textLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);
}else{
Toast.makeText(this,"Unble to Trace your location",Toast.LENGTH_SHORT).show();
}
}
}
protected void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please Turn ON your GPS Connection")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
#Override
protected void onDestroy(){
super.onDestroy();
mapview.onDestroy();
}
#Override
public void onLowMemory(){
super.onLowMemory();
mapview.onLowMemory();
}
#Override
protected void onPause(){
super.onPause();
mapview.onPause();
}
#Override
protected void onResume(){
super.onResume();
mapview.onResume();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapview.onSaveInstanceState(outState);
}
}

It's very easy you just need to do like:
CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(yourLatLng, ZOOM_MAP);
mMap.animateCamera(myLocation);
ZOOM_MAP its float
Update ----
mapview.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(yourLatLng, ZOOM_MAP);
googleMap.animateCamera(myLocation);
}
});

Related

How to add marker in google map when i recieve longitude and latitude from sms

So basically I am making an app in which I would get an SMS which will contain a latitude and longitude from which I need to add a new marker on the map. But I am unable to do so as I cannot add marker outside the onMapReady function. Any suggestion on how to add marker outside the onMapReady function?
the maps activity is as follow
package com.example.rajen.railwaycrackk;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
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.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
boolean sms_Perm=true;
private GoogleMap mMap;
boolean mapstart=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (ContextCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MapsActivity.this, Manifest.permission.RECEIVE_SMS)) {
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.RECEIVE_SMS}, 1);
} else {
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.RECEIVE_SMS}, 1);
}
}
// 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);
if (mMap!=null) {
// GoogleMap map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
// .getMap();
Log.d("1", "entered into truee");
this.mMap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
}
}
#Override
public void onRequestPermissionsResult(int requestcode, String[] permissions, int[] grantResults) {
switch (requestcode) {
case 1: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
sms_Perm = true;
}
} else {
Toast.makeText(this, "No permission granted", Toast.LENGTH_SHORT).show();
sms_Perm = false;
}
}
}
}
public void onMapReady(GoogleMap googleMap) {
this.mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(20.5937, 78.9629);
this.mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
this.mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mapstart=true;
SmsReceiver myMapReceiver = new SmsReceiver(googleMap);
IntentFilter filter = new IntentFilter(SmsReceiver.ADD_MARKER);
filter.addCategory(Intent.CATEGORY_DEFAULT);
LocalBroadcastManager.getInstance(this).registerReceiver(myMapReceiver, filter);
}
public String LoadInt(String key){
String savedValue;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
savedValue = sharedPreferences.getString(key,null);
return savedValue;
}
}
My SMS broadcast receiver is as follows
package com.example.rajen.railwaycrackk;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* Created by rajen on 29-01-2018.
*/
public class SmsReceiver extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public static final String ADD_MARKER = "some.unique.string.ADD_MARKER";
private GoogleMap mMap;
public SmsReceiver (GoogleMap mMap) {
this.mMap = mMap;
}
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
if (intent.getAction().compareTo(ADD_MARKER) == 0) {
double lat = intent.getDoubleExtra("lat", 0);
double lng = intent.getDoubleExtra("lng", 0);
}
// do something with map using lat/lng
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"senderNum: " + senderNum + ", message: " + message, duration);
toast.show();
// LatLng position = new LatLng(20.5937, 78.9629);
// MapsActivity.plotOnMap(position);
} // end for loop
} // bundle is null
Intent broadcastIntent = new Intent();
// get 'lat' and 'lng' from message
broadcastIntent.setAction(SmsReceiver.ADD_MARKER);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra("lat", 10);
broadcastIntent.putExtra("lng", 10);
LocalBroadcastManager.getInstance(context.getApplicationContext()).sendBroadcast(broadcastIntent);
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
}
Use a broadcast receiver attached to your map activity....
Create a BroadcastReceiver subclass as follows:
public class MapRequestReceiver extends BroadcastReceiver {
public static final String ADD_MARKER = "some.unique.string.ADD_MARKER";
private GoogleMap mMap;
public MapRequestReceiver (GoogleMap mMap) {
this.mMap = mMap;
}
public void onReceive(Context context, Intent intent) {
if (intent.getAction().compareTo(ADD_MARKER) == 0) {
double lat = intent.getDoubleExtra("lat", 0);
double lng = intent.getDoubleExtra("lng", 0);
// do something with map using lat/lng
}
}
}
In your map activity 'onMapReady' register the local broadcast receiver:
public void onMapReady(GoogleMap googleMap) {
// ... other stuff...
// check if it already exists in which case do nothing or
// unregister it first using LocalBroadcastManager.
MapRequestReceiver myMapReceiver = new MapRequestsReceiver(googleMap);
IntentFilter filter = new IntentFilter(MapRequestReceiver.ADD_MARKER);
filter.addCategory(Intent.CATEGORY_DEFAULT);
LocalBroadcastManager.getInstance(this).registerReceiver(myMapReceiver, filter);
}
... and where you receive the SMS:
Intent broadcastIntent = new Intent();
// get 'lat' and 'lng' from message
broadcastIntent.setAction(MapRequestsReceiver.ADD_MARKER);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra("lat", lat);
broadcastIntent.putExtra("lng", lng);
LocalBroadcastManager.getInstance( getApplicationContext() ).sendBroadcast(broadcastIntent);
You may find you'll want to do more things than ADD_MARKER so just update MapRequestReceiver with more actions (strings) and update 'onReceive'.

How to get city information in android by longitude and latitude

I am making android app now. I got some problem about getting locations.
In my code, I made my app get longitude and latitude by GPS. However, I have continued to fail to get city name by longitude and latitude. I don't know why my code goes to Exception even though there are no wrong things in my code.
Here is my code for getting city name
ackage org.androidtown.getcurrentlocation;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class GetCurrentLocation extends AppCompatActivity implements View.OnClickListener {
private LocationManager locationManager = 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
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_current_location);
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);
locationManager = (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();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {return;}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
}
else{
alertbox("GPS Status!!", "Your GPS is : OFF");
}
}
private Boolean displayGpsStatus(){
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
if(gpsStatus){
return true;
}
else{
return false;
}
}
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){
Intent myIntent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
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 longtitude = "Longtitude: "+loc.getLongitude();
Log.v(TAG, longtitude);
String latitude = "Latitude: "+loc.getLatitude();
Log.v(TAG, latitude);
String cityName = "default";
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
// addresses
try{
List<Address> 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 = longtitude + "\n" + latitude +
"\n\nMy Current City is : "+ cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider){
}
#Override
public void onProviderEnabled(String provider){
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
}
}
On the above code, this part is main code to get city name by longitude and latitude. There is no problem to get longitude and latitude. The only problem is to get city name.
String cityName = "default";
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
// addresses
try{
List<Address> 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 = longtitude + "\n" + latitude +
"\n\nMy Current City is : "+ cityName;
editLocation.setText(s);
}
Thank you for reading my question. Have a great day(?) midnight.
First thing you shouldn't call getFromLocation from main thread as this method is synchronous and may take a long time to do its work, so you should not call it from the main, user interface (UI) thread of your app. you should use Intent service class.
Here is code for it:
public class GetAddressService extends IntentService {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
protected ResultReceiver mReceiver;
//protected DataEntry.AddressResultReceiver mReceiver;
private static final String TAG = "GetAddressService";
public GetAddressService() {
super("GetAddressService");
}
#Override
protected void onHandleIntent(Intent intent) {
mReceiver = intent.getParcelableExtra(Constants.RECEIVER);
Log.e(TAG,"mReceiver"+mReceiver);
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
String errorMessage = "";
// Get the location passed to this service through an extra.
Location mCurrentLocation = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
try {
addresses = geocoder.getFromLocation(mCurrentLocation.getLatitude(),
mCurrentLocation.getLongitude(), 1);
} catch (IOException e) {
errorMessage = "Service error: ";
Log.e(TAG, errorMessage, e);
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = "invalid_lat_long_used";
Log.e(TAG, errorMessage + ". " +
"Latitude = " + mCurrentLocation.getLatitude() +
", Longitude = " +
mCurrentLocation.getLongitude(), illegalArgumentException);
}
// Handle case where no address was found.
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = "no_address_found";
Log.e(TAG, errorMessage);
}
deliverResultToReceiver(Constants.FAILURE_RESULT,errorMessage);
}else {
String cityName = addresses.get(0).getLocality();
String countryName = addresses.get(0).getCountryName();
String rLocation = cityName + "," + countryName;
Log.e(TAG, "location: " + rLocation);
deliverResultToReceiver(Constants.SUCCESS_RESULT,rLocation);
}
}
//To deliver the result back to the activity which started the service
private void deliverResultToReceiver(int resultCode, String message) {
//mReceiver = new ResultReceiver(this);
Bundle bundle = new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY, message);
mReceiver.send(resultCode, bundle);
Log.e(TAG,"Delivering result"+message);
}
}
//Constant class to store all constants in one place
public final class Constants {
public static final int SUCCESS_RESULT = 0;
public static final int FAILURE_RESULT = 1;
public static final String PACKAGE_NAME =
"your package name";
public static final String RECEIVER = PACKAGE_NAME + ".RECEIVER";
public static final String RESULT_DATA_KEY = PACKAGE_NAME +
".RESULT_DATA_KEY";
public static final String LOCATION_DATA_EXTRA = PACKAGE_NAME +
".LOCATION_DATA_EXTRA";
}
//call this GetAddressService from your activity
private AddressResultReceiver mResultReceiver;
private class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc){
Intent intent = new Intent(this,GetAddressService.class);
intent.putExtra(Constants.RECEIVER,mResultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA,loc);
startService(intent);
}
//class to receive the address back from the service
class AddressResultReceiver extends ResultReceiver{
/**
* Create a new ResultReceive to receive results. Your
* {#link #onReceiveResult} method will be called from the thread running
* <var>handler</var> if given, or from an arbitrary thread if null.
*
* #param handler
*/
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
Log.e(TAG,"Address is:"+mAddressOutput);
}
}

Android - Where to put removeUpdates for Location Manager

I have following code (I know that some of that may be redundant, if yes, please let me know). What I can't do is to stop the invoking updating the location again and again. I tried some different ways where to stop it (they are present in the code but commented). Sometimes i get
java.lang.RuntimeException: Unable to start activity ComponentInfo{jangcy.emergency/jangcy.emergency.ReportStartActivity}: java.lang.IllegalArgumentException: invalid listener: null
and sometimes
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.location.LocationManager.removeUpdates(android.location.LocationListener)' on a null object reference
If I try to stop it with some int (like is done now), it doesn't really stop. If I remove the if, it stops before it sends location to DB.
Any help please?
package jangcy.emergency;
import android.*;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class ReportStartActivity extends AppCompatActivity {
private String user;
TextView textView;
private double latitude = 500;
private double longitude = 500;
double old_longitude = 499;
double old_latitude = 499;
LocationManager locationManager;
LocationListener locationListener;
SharedPreferences sharedPref;
private int idZgloszenia;
public int counter = 0;
private static final String url_start_report = "http://192.168.0.12:80/emergency/start_report.php";
private StringRequest request;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_start);
requestQueue = Volley.newRequestQueue(this);
textView = (TextView) findViewById(R.id.testTextView);
textView.setText("jangcy");
sharedPref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
user = sharedPref.getString("loginKey", null);
int ik = geoLocation();
if (ik == 5){
locationManager.removeUpdates(locationListener);
locationManager = null;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.INTERNET
}, 10);
return;
}
} else {
//configureButton();
}
}
public int geoLocation()
{
final int[] do_zwrotu = new int[1];
textView.setText(String.valueOf(counter));
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
textView.setText(String.valueOf(longitude) + " " + String.valueOf(latitude));
if (longitude >= -180 && longitude <= 180 && latitude >= -90 && latitude <= 90) {
do_zwrotu[0] = 5;
textView.setText(String.valueOf(longitude) + " " + String.valueOf(latitude) + user);
startReport(user, longitude, latitude);
/*locationManager.removeUpdates(locationListener);
locationManager = null;*/
/*locationManager.removeUpdates(this);
locationManager = null;*/
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent in = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(in);
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
return do_zwrotu[0];
}
private void startReport(final String user, final double longitude, final double latitude) {
request = new StringRequest(Request.Method.POST, url_start_report, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
System.out.println(response);
JSONObject jsonObject = new JSONObject(response);
int success = jsonObject.getInt("success");
if (success == 1) {
/*
locationManager.removeUpdates(locationListener);
locationManager = null;*/
Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
//idZgloszenia = jsonObject.getInt("id_zgloszenia");
//textView.setText(idZgloszenia);
} else {
Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("gps_x", Double.toString(longitude));
hashMap.put("gps_y", Double.toString(latitude));
hashMap.put("uzytkownik", user);
return hashMap;
}
};
requestQueue.add(request);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 10:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
//configureButton();
return;
}
}
private void configureButton() {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
textView.setText("jangcy2");
}
}

Retrofit response method parsing JSON from google map api doesn't work

The loop inside the retrofitResponse method does not loops which it was suppose to do. It was suppose to fetch json data from google map url.
package com.webstarts.byteglory.shomadhan;
import android.*;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.location.Location;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
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;
import com.webstarts.byteglory.shomadhan.POJO.Example;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
public class StartActivity extends FragmentActivity implements ConnectionCallbacks, OnConnectionFailedListener, com.google.android.gms.location.LocationListener, OnMapReadyCallback {
protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
protected static final String TAG = "Location Services Test";
private Button search_location_button;
private Button search_area_button;
private Button toilet_status_button;
protected LatLng latlng;
protected LocationRequest mLocationRequest;
private GoogleMap mMap;
private int PROXIMITY_RADIUS = 10000;
Marker mCurrLocationMarker;
boolean mapReady = false;
private Marker mPerth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
search_location_button = (Button) findViewById(R.id.search_location_button);
search_area_button = (Button) findViewById(R.id.search_area_button);
toilet_status_button = (Button) findViewById(R.id.toilet_status_button);
locationApiClient();
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
search_location_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Log.i(TAG, String.valueOf(latlng.latitude));
// Uri gmmIntentUri = Uri.parse("geo:"+String.valueOf(latlng.latitude)+","+String.valueOf(latlng.longitude)+"?z=15&q=public toilets");
// Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
// mapIntent.setPackage("com.google.android.apps.maps");
// startActivity(mapIntent);
retrofitResponse();
// Marker loc = mMap.addMarker(new MarkerOptions().position(latlng)
// .title("You are here now 23"));
// mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15));
//
// // Zoom in, animating the camera.
// mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
// Log.i(TAG, String.valueOf(latlng.latitude));
}
});
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
protected synchronized void locationApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
#Override
public void onConnected(Bundle connectionHint) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null) {
latlng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
}
else {
Toast toast = Toast.makeText(this, "Turn on your location service", Toast.LENGTH_LONG);
toast.show();
finish();
}
}
public void onLocationChanged(Location location) {
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
/*
* Called by Google Play services if the connection to GoogleApiClient drops because of an
* error.
*/
public void onDisconnected() {
Log.i(TAG, "Disconnected");
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
private void retrofitResponse() {
String url = "https://maps.googleapis.com/maps/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitMaps service = retrofit.create(RetrofitMaps.class);
Call<Example> call = service.getNearbyPlaces("restaurents", latlng.latitude + "," + latlng.longitude, PROXIMITY_RADIUS);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Response<Example> response, Retrofit retrofit) {
try {
mMap.clear();
// This loop will go through all the results and add marker on each location.
Log.i("ishan", String.valueOf(response.body().getResults().size()));
for (int i = 0; i < response.body().getResults().size(); i++) {
Double lat = response.body().getResults().get(i).getGeometry().getLocation().getLat();
Double lng = response.body().getResults().get(i).getGeometry().getLocation().getLng();
String placeName = response.body().getResults().get(i).getName();
String vicinity = response.body().getResults().get(i).getVicinity();
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, lng);
// Position of Marker on Map
markerOptions.position(latLng);
// Adding Title to the Marker
markerOptions.title(placeName + " : " + vicinity);
// Adding Marker to the Camera.
Marker m = mMap.addMarker(markerOptions);
// Adding colour to the marker
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Log.i("ishan", String.valueOf(i));
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
#Override
public void onMapReady(GoogleMap map) {
mapReady=true;
mMap = map;
// //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) {
// }
// }
}
}
This is the interface of the retrofit. It has just the GET as it just reads data from map url.
package com.webstarts.byteglory.shomadhan;
import com.webstarts.byteglory.shomadhan.POJO.Example;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Query;
public interface RetrofitMaps {
/*
* Retrofit get annotation with our URL
* And our method that will return us details of student.
*/
#GET("api/place/nearbysearch/json?sensor=true&key=AIzaSyABCGHHSFDGSDsdfGADFnM")
Call<Example> getNearbyPlaces(#Query("type") String type, #Query("location") String location, #Query("radius") int radius);
}
I have just looped inside the onResponse retrofit function like this:
public void onResponse(Call call, Response response) {
/* implement the toast */
/* =new ArrayList<User>(); */
ArrayList<User> test;
test=response.body().getUsers();
String jax= test.get(0).getFarm_name();
//Toast.makeText(MarkerDemoActivity.this, "farm name is "+jax, Toast.LENGTH_LONG).show();
//LatLng m_cord,String farm_name,String desc
int i = 0;
while ( test.size()>i) {
String farm_name = test.get(i).getFarm_name();
String desc1 = test.get(i).getOwner_tel();
String desc2 = test.get(i).getFarm_type();
String cords = test.get(i).getM_cord();
//split the co-ords
String[] latlong = cords.split(",");
double latitude = Double.parseDouble(latlong[0]);
double longitude = Double.parseDouble(latlong[1]);
LatLng location = new LatLng(latitude, longitude);
//do the loop here
// Add lots of markers to the map. LatLng m_cord,String farm_name,String desc
addMarkersToMapJax(location, farm_name, desc1 + desc2);
i++;
}
}
I created a marker function to load the co-ordinates:
private void addMarkersToMapJax(LatLng m_cord,String farm_name,String desc) {
// Uses a colored icon.
mArc = mMap.addMarker(new MarkerOptions()
.position(m_cord)
.title(farm_name)
.snippet(desc)

Not getting user location using GPS_PROVIDER / NETWORK_PROVIDER

I am trying to implement a simple location app that will show the user location from GPS (if GPS on) on a button click and the user location from NETWORK_PROVIDER on another button click. What I am trying to do is given below-
AppLocationService.java
package com.android.imran.userlocation;
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;
public class AppLocationService extends Service implements LocationListener{
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if(locationManager.isProviderEnabled(provider))
{
locationManager.requestLocationUpdates(provider,MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MainActivity.java
package com.android.imran.userlocation;
import android.location.Location;
import android.location.LocationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView showLocation;
Button getLocationGPS;
Button getLocationNW;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showLocation=(TextView)findViewById(R.id.showLocation);
getLocationGPS=(Button)findViewById(R.id.getLocationGPS);
getLocationNW=(Button)findViewById(R.id.getLocationNW);
getLocationGPS.setOnClickListener(this);
getLocationNW.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.getLocationGPS:
Location gpsLocation = new AppLocationService(getApplicationContext()).getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
showLocation.setText("Latitude: " + latitude + "\nLongitude: " + longitude);
Toast.makeText(getApplicationContext(), "Mobile Location (GPS): \nLatitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_LONG).show();
}
break;
case R.id.getLocationNW:
Location nwLocation = new AppLocationService(getApplicationContext()).getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
showLocation.setText("Latitude: " + latitude + "\nLongitude: " + longitude);
Toast.makeText(getApplicationContext(), "Mobile Location (NW): \nLatitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_LONG).show();
}
break;
}
}
}
This app doesn't show any output.
You can get the location from onLocationChanged method that you override
#Override
public void onLocationChanged(Location location) {
// Listen for location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Toast.makeText(getApplicationContext(), "Mobile Location (GPS): \nLatitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_LONG).show();
}
EDIT :
Simple code sample of how I got the location -
MainActivity.java
private LocationManager locationManager;
private double longitudeGPS, latitudeGPS;
private TextView locationView;
private final LocationListener locationListenerGPS = new LocationListener() {
public void onLocationChanged(Location location) {
longitudeGPS = location.getLongitude();
latitudeGPS = location.getLatitude();
runOnUiThread(new Runnable() {
#Override
public void run() {
String loc = longitudeGPS + " , " + latitudeGPS;
locationView.setText(loc);
Toast.makeText(NewComplaintActivity.this, "GPS Provider update", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationView = (TextView) findViewById(R.id.location_view);
if (!checkLocation()){
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000 * 60, 10, locationListenerGPS);
}
}
private boolean checkLocation() {
if (!isLocationEnabled())
// ask user to enable location
return isLocationEnabled();
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
Don't forget to add
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Categories