I need to find the least distant pharmacy and add its id to a table in the database.
public class gpslocation implements LocationListener {
private final Context mContext;
protected LocationManager locationManager;
boolean checkGPS = false;
boolean checkNetwork = false;
boolean canGetLocation = false;
Location loc;
double latitude;
double longitude;
String city;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
public gpslocation(Context mContext) {
this.mContext = mContext;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
checkGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
checkNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!checkGPS && !checkNetwork) {
Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show();
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (checkNetwork) {
Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show();
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
} catch (SecurityException e) {
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (checkGPS) {
Toast.makeText(mContext, "GPS", Toast.LENGTH_SHORT).show();
if (loc == null) {
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
} catch (SecurityException e) {
Log.d("Exce", e + "");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return loc;
}
public double getLongitude() {
if (loc != null) {
longitude = loc.getLongitude();
}
return longitude;
}
public double getLatitude() {
if (loc != null) {
latitude = loc.getLatitude();
// loc.
}
return latitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS Not Enabled");
alertDialog.setMessage("Do you wants to turn On GPS");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void stopUsingGPS() {
if (locationManager != null) {
// locationManager.removeUpdates(this);
}
}
#Override
public void onLocationChanged(Location location) {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(mContext, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
// Only if available else return NULL
Toast.makeText(mContext, "Longitude:" + Double.toString(longitude) + "\nLatitude:" + Double.toString(latitude), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
// Boolean checkgps = true;
// String gps = String.valueOf(checkgps);
}
this is my code to find latitude and longitude in Android Studio.
package DatabasePackage;
import java.sql.ResultSet;
import org.json.JSONArray;
import org.json.JSONObject;
public class locationcalculation {
double distance;
boolean b;
int i;
ConnectionClass con=new ConnectionClass();
public String getlocation(String lat1,String lon1){
String a="";
String se="Select * from tbl_pharmacy ";
ResultSet rs=con.selectCommand(se);
JSONArray ja = new JSONArray();
JSONObject job;
try{
while(rs.next()){
String lattitude=rs.getString("lattitude");
String longitude=rs.getString("longitude");
double dis=Calculation(lat1, lattitude, lon1, longitude);
distance=dis;
if(dis<=10){
job=new JSONObject();
job.put("distance", distance);
job.put("id", rs.getString("phar_id"));
ja.put(job);
break;
}
else if(dis<5){
break;
}
}
}catch(Exception ex){
}
return ja.toString();
}
public double Calculation(String latt1,String latt2,String longg1,String longg2){
String j="";
final int R = 6371; // Radius of the earth
double lat1=Integer.parseInt(latt1);
double lat2=Integer.parseInt(latt2);
double lon1=Integer.parseInt(longg1);
double lon2=Integer.parseInt(longg2);
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1))
* Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1))
* Math.cos(deg2rad(lat2))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
}
This is my java class (written in NetBeans) to find the distance between two pairs of latitude and longitude. one pair is to be obtained from the android device and other pair from the heidisql database.
String Dis=distance.getlocation(latt, lon);
String str1="insert into
tbl_prescription(prescription,user_id)values('"+value[0]+"','1')";
// String str1="insert into
tbl_prescription(prescription)values('"+value[0]+"')";
// System.out.println(str1
//out.println(str1);
boolean status=con.executeCommand(str1);
this is where i have to call the function getLocation()(also written in NetBeans but in a different jsp page) that is defined in the java class. But I do not know how to get the value from the android device to this function call. Can someone solve this for me?
Related
This question already has answers here:
The application may be doing too much work on its main thread
(21 answers)
Closed 1 year ago.
As I am new to android I couldn't fix this skipped 1000+ frames issue.Help me to sort out this and help me to add loading progress bar while this skipping frames action takes place before opening map. This is my map code.
RouteMap.java
public class RouteMap extends android.support.v4.app.FragmentActivity
implements OnClickListener, OnInfoWindowClickListener,
DirecitonReceivedListener, OnMapReadyCallback {
public List<String> destinations;
ImageView img_home, img_menu;
private GoogleMap mMap;
ProgressDialog prgDialog;
model modelData;
private Button btnDirection;
double latitude, longitude;
LinearLayout linear_back;
LatLng startPosition, start;
String startPositionTitle;
Vibrator vibrator;
String startPositionSnippet;
Double desc1_long, desc1_lat;
LatLng destinationPosition1;
String destinationPositionTitle;
String destinationPositionSnippet;
MarkerOptions mDestination1, mStart;
ToggleButton tbMode;
GPSTracker gps;
Geocoder gCoder;
ArrayList<Address> addresses = null;
ArrayList<Address> adres2 = null;
SupportMapFragment mapFragment;
public final static double AVERAGE_RADIUS_OF_EARTH = 6371;
TextView back_txt;
openMap openMap;
String mapStatus = "start";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_map);
back_txt = (TextView) findViewById(R.id.txt_back);
try {
back_txt = (TextView) findViewById(R.id.txt_back);
modelData = model.getInstance();
vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
gps = new GPSTracker(RouteMap.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
gCoder = new Geocoder(RouteMap.this);
addresses = (ArrayList<Address>) gCoder.getFromLocation(latitude, longitude, 1);
tbMode = (ToggleButton) findViewById(R.id.tbMode);
mapFragment = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map));
mapFragment.getMapAsync(this);
btnDirection = (Button) findViewById(R.id.btnDirection);
btnDirection.setOnClickListener(this);
tbMode.setChecked(true);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
}
}
public int calculateDistance(double userLat, double userLng, double venueLat, double venueLng) {
final int R = 6371;
try {
Double latDistance = deg2rad(venueLat - userLat);
Double lonDistance = deg2rad(venueLng - userLng);
Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(deg2rad(userLat)) * Math.cos(deg2rad(venueLat))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
double height = 0 - 0;
distance = Math.pow(distance, 2) + Math.pow(height, 2);
return (int) Math.sqrt(distance);
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Please Check your Destination's GeoCode ", Toast.LENGTH_LONG).show();
}
return 0;
}
private double deg2rad(double deg) {return (deg * Math.PI / 180.0);}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap=googleMap;
//setUpMap();
try {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
mMap.setMyLocationEnabled(true);
mMap.setIndoorEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setAllGesturesEnabled(true);
String[] arr = new String[modelData.outletList.size()];
for(int i=0;i<modelData.outletList.size();i++)
{
String str1 = modelData.outletList.get(i)[2];
String str2 = modelData.outletList.get(i)[3];
String newString = str1+","+str2;
arr[i] = newString;
}
String[] latTempArr = arr;
String strKey = "";
double curLatitude = latitude;
double curLongtitude = longitude;
double desLat;
double desLng;
Map<String, Integer> final_arr = new HashMap<String, Integer>();
Map<String, Integer> final_arr2 = new HashMap<String, Integer>();
List<Integer> intTempArr = new ArrayList<Integer>();
List<Integer> intTempArr2 = new ArrayList<Integer>();
for(int j=0;j<arr.length;j++)
{
intTempArr = new ArrayList<Integer>();
for (int k=0;k<latTempArr.length;k++)
{
String[] arr_temp = latTempArr[k].split(",");
//System.out.println(arr_temp[0]);
desLat = Double.parseDouble(arr_temp[0]);
desLng = Double.parseDouble(arr_temp[1]);
int temp = calculateDistance(curLatitude,curLongtitude,desLat,desLng);
intTempArr.add(temp);
final_arr.put(latTempArr[k],temp);
}
Collections.sort(intTempArr);
Integer[] array = new Integer[intTempArr.size()];
intTempArr.toArray(array);
for (Map.Entry<String, Integer> entry : final_arr.entrySet()) {
try{
if (entry.getValue().equals(array[0])) { //get next best path
List<String> list = new ArrayList<String>(Arrays.asList(latTempArr)); // remove the best path to find next one
list.remove(entry.getKey());
latTempArr = list.toArray(new String[0]);
String[] arr_temp2 = entry.getKey().split(",");
//System.out.println(arr_temp[0]);
curLatitude = Double.parseDouble(arr_temp2[0]);
curLongtitude = Double.parseDouble(arr_temp2[1]);
strKey = entry.getKey();
intTempArr2.add(entry.getValue());
final_arr2.put(strKey,entry.getValue());
}
}
catch(Exception e)
{
}
}
//System.out.println(intTempArr);
}
//int i = 0;
destinations = new ArrayList<String>();
for(int i =0;i<intTempArr2.size();i++) {
for(String Key : final_arr2.keySet()) {
//System.out.println();
if(final_arr2.get(Key) == intTempArr2.get(i)) {
destinations.add(Key);
break;
}
}
}
System.out.println(destinations);
for(int i = 0;i < destinations.size();i++) {
//Toast.makeText(getApplicationContext(), " ListItem : " + i, Toast.LENGTH_LONG).show();
String desti1 = destinations.get(i);
String[] des = desti1.split(",");
desc1_lat = Double.parseDouble(des[0]);
desc1_long = Double.parseDouble(des[1]);
startPosition = new LatLng(latitude, longitude);
startPositionTitle = addresses.get(0).getLocality();
startPositionSnippet = addresses.get(0).getAddressLine(1)+"," +" "+ addresses.get(0).getAddressLine(2);
try {
adres2 = (ArrayList<Address>) gCoder.getFromLocation(desc1_lat, desc1_long, 1);
} catch (IOException e) {
e.printStackTrace();
}
destinationPosition1 = new LatLng(desc1_lat, desc1_long);
destinationPositionTitle = adres2.get(0).getLocality();
destinationPositionSnippet =adres2.get(0).getAddressLine(1)+"," +" "+adres2.get(0).getAddressLine(2);
// mMap.setOnInfoWindowClickListener(this);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View v = getLayoutInflater().inflate(R.layout.marker, null);
TextView info= (TextView) v.findViewById(R.id.info);
info.setText(marker.getSnippet().toString());
return v;
}
});
mDestination1 = new MarkerOptions()
.position(destinationPosition1)
.title(destinationPositionTitle)
.snippet(destinationPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin1));
mStart = new MarkerOptions()
.position(startPosition)
.title(startPositionTitle)
.snippet(startPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin2));
mMap.addMarker(mDestination1);
mMap.addMarker(mStart);
latitude = desc1_lat;
longitude = desc1_long;
LatLng locations = new LatLng(latitude,longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locations, 5.5f));
}
}catch (Exception ex)
{
/*Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();*/
}
}
public void clearMap() {
mMap.clear();
}
#Override
public void onClick(View v) {
try
{
Locale mLocale = new Locale("en");
Log.d("Display language = ", "" + mLocale.getDisplayLanguage());
gCoder = new Geocoder(RouteMap.this,mLocale);
gps = new GPSTracker(RouteMap.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
for(int i = 0;i<destinations.size();i++) {
String desti1 = destinations.get(i);
String[] des = desti1.split(",");
desc1_lat = Double.parseDouble(des[0]);
desc1_long = Double.parseDouble(des[1]);
startPosition = new LatLng(latitude, longitude);
startPositionTitle = addresses.get(0).getLocality();
startPositionSnippet = addresses.get(0).getAddressLine(1)+","+" "+addresses.get(0).getAddressLine(2);
destinationPosition1 = new LatLng(desc1_lat, desc1_long);
destinationPositionTitle = adres2.get(0).getLocality();
destinationPositionSnippet =adres2.get(0).getAddressLine(1)+","+""+ adres2.get(0).getAddressLine(2);
mMap.setOnInfoWindowClickListener(this);
mStart = new MarkerOptions()
.position(startPosition)
.title(startPositionTitle)
.snippet(startPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin1));
mDestination1 = new MarkerOptions()
.position(destinationPosition1)
.title(destinationPositionTitle)
.snippet(destinationPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin2));
if (v == btnDirection) {
// clearMap();
mMap.addMarker(mDestination1);
mMap.addMarker(mStart);
if (tbMode.isChecked()) {
new GetRotueListTask(RouteMap.this, startPosition,
destinationPosition1, GMapV2Direction.MODE_DRIVING, this)
.execute();
} else {
new GetRotueListTask(RouteMap.this, startPosition,
destinationPosition1, GMapV2Direction.MODE_WALKING, this)
.execute();
}
}
latitude = desc1_lat;
longitude = desc1_long;
}
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
}
}
#Override
public void OnDirectionListReceived(List<LatLng> mPointList) {
try
{
if (mPointList != null) {
PolylineOptions rectLine = new PolylineOptions().width(10).color(
Color.RED);
for (int i = 0; i < mPointList.size(); i++) {
rectLine.add(mPointList.get(i));
}
mMap.addPolyline(rectLine);
gps = new GPSTracker(RouteMap.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
start = new LatLng(latitude, longitude);
CameraPosition mCPFrom = new CameraPosition.Builder()
.target(start).zoom(15.5f).bearing(0).tilt(25)
.build();
final CameraPosition mCPTo = new CameraPosition.Builder()
.target(destinationPosition1).zoom(15.5f).bearing(0)
.tilt(50).build();
changeCamera(CameraUpdateFactory.newCameraPosition(mCPFrom),
new CancelableCallback() {
#Override
public void onFinish() {
changeCamera(CameraUpdateFactory
.newCameraPosition(mCPTo),
new CancelableCallback() {
#Override
public void onFinish() {
LatLngBounds bounds = new LatLngBounds.Builder()
.include(start)
.include(
destinationPosition1)
.build();
changeCamera(
CameraUpdateFactory
.newLatLngBounds(
bounds, 50),
null, false);
}
#Override
public void onCancel() {
}
}, false);
}
#Override
public void onCancel() {
}
}, true);
}
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Please Check your Data Connection", Toast.LENGTH_LONG).show();
}
}
private void changeCamera(CameraUpdate update, CancelableCallback callback,
boolean instant) {
if (instant) {
mMap.animateCamera(update, 1, callback);
} else {
mMap.animateCamera(update, 4000, callback);
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onInfoWindowClick(Marker marker) {
}
private class openMap extends AsyncTask<String, Void, String>
{
ProgressDialog mProgressDialog;
Context ctx;
public openMap(Context ctx)
{
this.ctx=ctx;
mProgressDialog = new ProgressDialog(RouteMap.this);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Loading Map..Please wait....");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
// Toast.makeText(getApplicationContext(), "Syncing DB...", Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... urls)
{
return "Success";
}
#Override
protected void onPostExecute(String result)
{
mProgressDialog.dismiss();
try
{
if(result.equalsIgnoreCase("Success")) {
}
else
{
Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
}
}catch (Exception e){}
}
}
}
From this code above what changes should I make to fix the Skipped
1000+ frames issue and also help me add loader before opening the
map...
Geocoder.getFromLocation() is an expensive call that does a network call to Google's servers, so don't make it on the UI thread.
Have a look at Processes and Threads in the android developer docs for various ways of making the request in the background.
The code that you write in OnMapReady function is to much, please remove that code from there I can see there are more then 4 "for" loops in onMapReady, move that part to to some where else like OnCreate() create all maps and lists that you want.
Just ues OnMapReady function for placing markers
i have two AsyncTask which works with Current user location data, the first goes well without any problem, but the second, stop the app works and app will crash.
notice that, just in real device the first task will works but in virtual devices even the first didn't work :|
code of mainActivity:
public class MainActivity extends AppCompatActivity {
Button btnShowLocation;
public static TextView txtTemperature;
public static TextView txtWindSpeed;
public static TextView txtHumidity;
public static TextView txtSummary;
public static TextView txtCityName;
GpsTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button)findViewById(R.id.btnupdate);
txtTemperature = (TextView) findViewById(R.id.txtTemperature);
txtWindSpeed = (TextView) findViewById(R.id.txtWindSpeed);
txtHumidity = (TextView) findViewById(R.id.txthumidity);
txtSummary = (TextView) findViewById(R.id.txtSummary);
txtSummary = (TextView) findViewById(R.id.txtCityName);
//find geoLocation
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gps = new GpsTracker(MainActivity.this);
if(gps.canGetLocation()){
Double lat = gps.getLatitude();
Double lng = gps.getLongtitude();
Toast.makeText(getApplicationContext(),
"Your location is -\nLat:"+lat+"\nLng:"+lng,
Toast.LENGTH_LONG).show();
String url = "https://api.forecast.io/forecast/KEY/"+lat+","+lng+"?units=ca";
JsonTask task = new JsonTask(getApplicationContext());
task.execute(url);
String url2 = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lng;
CityNameTask city = new CityNameTask(getApplicationContext());
city.execute(url2);
}
else {
gps.showSettingsAlert();
}
}
});
}
}
the First AsyncTask which work fine:
class JsonTask extends AsyncTask<String, String, String> {
private Context mContext;
public JsonTask (Context context){
mContext = context;
}
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
String data = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
//Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
try{
JSONObject jsonObject= new JSONObject(line).getJSONObject("currently");
data=
jsonObject.getString("temperature")+","+
jsonObject.getString("windSpeed")+","+
jsonObject.getString("humidity")+","+
jsonObject.getString("summary");
}
catch(JSONException e)
{
}
}
return data.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String string = result;
String[] parts = string.split(",");
String temperature = parts[0];
String windSpeed = parts[1];
String humidity = parts[2];
String summary = parts[3];
MainActivity.txtTemperature.setText(temperature);
MainActivity.txtWindSpeed.setText(windSpeed);
MainActivity.txtHumidity.setText(humidity);
MainActivity.txtSummary.setText(summary);
}
}
the second Task which fails:
class CityNameTask extends AsyncTask<String, String, String> {
private Context mContext;
public CityNameTask (Context context){
mContext = context;
}
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
String data = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
}
Log.d("Response: ", "> " + line);
try {
JSONObject jsonRootObject = new JSONObject(line);
JSONArray jsonArray = jsonRootObject.optJSONArray("results");
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
data = jsonObject.getString("formatted_address");
}
} catch (JSONException e) {e.printStackTrace();}
return data.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
MainActivity.txtCityName.setText(result);
}
}
-- edited: logcat:
06-03 22:00:07.998 2804-2804/com.mortezaaghili.havamoon E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mortezaaghili.havamoon, PID: 2804
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.mortezaaghili.havamoon.GpsTracker.getLatitude(GpsTracker.java:131)
at com.mortezaaghili.havamoon.MainActivity$1.onClick(MainActivity.java:54)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
edited again:
this is GPSTracker class:
public class GpsTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
Double latitude;
Double longtitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GpsTracker(Context context){
this.context = context;
getLocation();
}
public Location getLocation(){
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled){}
else{
this.canGetLocation = true;
if(isNetworkEnabled){
try {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this);
if (locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longtitude = location.getLongitude();
}
}
}
catch (SecurityException e)
{
}
}
if(isGPSEnabled){
if (location == null){
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this);
if (locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longtitude = location.getLongitude();
}
}
}
catch (SecurityException e)
{
}
}
}
}
}
catch (Exception e){
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
if (locationManager != null){
try{
locationManager.removeUpdates(GpsTracker.this);
}
catch(SecurityException e){
}
}
}
public double getLatitude(){
if (locationManager != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongtitude(){
if (locationManager != null) {
longtitude = location.getLongitude();
}
return longtitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is setting");
alertDialog.setMessage("GPS is not enabled. do you want go to settings?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#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) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
What it seems like is that your location variable is not initialized from the GpsTracker class.
Therefore when you are extending Service class and implementing LocationListener you would have overridden a method called getLocation(), which should return Location object, but in your case is returning null.
If you could just post the code for that file, or debug it on your own.
probably your GpsTracker class must include something like:
public double getLatitude() {
if(location != null) { // here must be checked if location is available and it's not null, coz now you probably get crash coz this has not been checked
latitude = location.getLatitude();
}
return latitude;
}
In order to avoid getting Null Locations you need to use google play locations API
which is recommended by google.
Also Try
String line = "";
String data = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
}
At the end of this loop the line object is null
So save a copy of the last line element in some variable and
Then apply the following code on that.
Log.d("Response: ", "> " + line);
try {
JSONObject jsonRootObject = new JSONObject(line);
JSONArray jsonArray = jsonRootObject.optJSONArray("results");
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
data = jsonObject.getString("formatted_address");
}
The relavent part of the stack trace is:
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object
reference at com.mortezaaghili.havamoon.GpsTracker.getLatitude(GpsTracker.java:131)
Broken code mentioned:
public double getLatitude(){
if (locationManager != null){
latitude = location.getLatitude();
}
return latitude;
}
You're checking for a null locationManager but then calling a method on location which may have been null from the big try/catch swallowing in the getLocation() setup method called during the GPSTracker constructor.
Check for location null instead:
public double getLatitude(){
if (location != null){
latitude = location.getLatitude();
}
return latitude;
}
I have implemented a mini project and there i need to display currency symbol based on Location.
ex: If i am in India it should display rupee symbol if USA $ symbol, I have implemented but it always gives Pound symbol
My Code:
LocationManager locationManager = (LocationManager) getSystemService(ListActivity.LOCATION_SERVICE);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
Geocoder code = new Geocoder(ListActivity.this);
try {
List<Address> addresses = code.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
Address obj = addresses.get(0);
String cc = Currency.getInstance(obj.getLocale()).getSymbol();
Log.d("Currency Symbol : ", cc);
} catch (IOException e) {
e.printStackTrace();
}
}
I needed to show currency symbol of respective country and get country are from GPS i searched lot finally came up with below code its working properly so i want to share this code others could not waste there time
here you need first country code like IN,US from latitude longitude we get full address
Please check GPS permission in manifest file before run code.
below are the some permissions
need GPSTracker.java file code create GPSTracker java file and write below code. in this some red line dont worry it affect nothing
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS status
boolean isGPSEnabled = false;
// Flag for network status
boolean isNetworkEnabled = false;
// Flag for GPS status
boolean canGetLocation = false;
Location location; // Location
double latitude; // Latitude
double longitude; // Longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
* */
public void stopUsingGPS() {
if (locationManager != null) {
//locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the Settings button.
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// On pressing the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#
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;
}
}
here is mainactivity.java class
public class MainActivity extends AppCompatActivity {
public static SortedMap < Currency, Locale > currencyLocaleMap;
TextView t;
Geocoder geocoder;
private static final Map < String, Locale > COUNTRY_TO_LOCALE_MAP = new HashMap < String, Locale > ();
static {
Locale[] locales = Locale.getAvailableLocales();
for (Locale l: locales) {
COUNTRY_TO_LOCALE_MAP.put(l.getCountry(), l);
}
}
public static Locale getLocaleFromCountry(String country) {
return COUNTRY_TO_LOCALE_MAP.get(country);
}
String Currencysymbol = "";
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.text);
GPSTracker gpsTracker = new GPSTracker(MainActivity.this);
geocoder = new Geocoder(MainActivity.this, getLocaleFromCountry(""));
double lat = gpsTracker.getLatitude();
double lng = gpsTracker.getLongitude();
Log.e("Lat long ", lng + "lat long check" + lat);
currencyLocaleMap = new TreeMap < Currency, Locale > (new Comparator < Currency > () {
public int compare(Currency c1, Currency c2) {
return c1.getCurrencyCode().compareTo(c2.getCurrencyCode());
}
});
for (Locale locale: Locale.getAvailableLocales()) {
try {
Currency currency = Currency.getInstance(locale);
currencyLocaleMap.put(currency, locale);
Log.d("locale utill", currency + " locale1 " + locale.getCountry());
} catch (Exception e) {
Log.d("locale utill", "e" + e);
}
}
try {
List < Address > addresses = geocoder.getFromLocation(lat, lng, 2);
Address obj = addresses.get(0);
Currencysymbol = getCurrencyCode(obj.getCountryCode());
Log.e("getCountryCode", "Exception address " + obj.getCountryCode());
Log.e("Currencysymbol", "Exception address " + Currencysymbol);
} catch (Exception e) {
Log.e("Exception address", "Exception address" + e);
// Log.e("Currencysymbol","Exception address"+Currencysymbol);
}
t.setText(Currencysymbol);
}
public String getCurrencyCode(String countryCode) {
String s = "";
for (Locale locale: Locale.getAvailableLocales()) {
try {
if (locale.getCountry().equals(countryCode)) {
Currency currency = Currency.getInstance(locale);
currencyLocaleMap.put(currency, locale);
Log.d("locale utill", currency + " locale1 " + locale.getCountry() + "s " + s);
s = getCurrencySymbol(currency + "");
}
} catch (Exception e) {
Log.d("locale utill", "e" + e);
}
}
return s;
}
public String getCurrencySymbol(String currencyCode) {
Currency currency = Currency.getInstance(currencyCode);
System.out.println(currencyCode + ":-" + currency.getSymbol(currencyLocaleMap.get(currency)));
return currency.getSymbol(currencyLocaleMap.get(currency));
}
}
You can use this to get locale of your Location
Locale locale= getResources().getConfiguration().locale;
Currency currency=Currency.getInstance(locale);
String symbol = currency.getSymbol();
Refernce : Getting Current Locale
i am trying to make an application where it show the 5 closest places with multiple markers from my current location. On other topics i saw many examples, but, no one explained how to create app with multiple markers or HashMap where show the nearest place. Please help me to solve it.
Here is my Main activity.java
public class MainActivity extends Activity
{
private GoogleMap mMap;
private ArrayList<MyMarker> mMyMarkersArray = new ArrayList<MyMarker>();
private HashMap<Marker, MyMarker> mMarkersHashMap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMarkersHashMap = new HashMap<Marker, MyMarker>();
mMyMarkersArray.add(new MyMarker("Restaurant Zaplet", "Telephone: \n Address: ", "iconZaplet", Double.parseDouble("43.381499"), Double.parseDouble("19.808931")));
mMyMarkersArray.add(new MyMarker("Restaurant Oresac", "Telephone: \n Address: ","iconOresac", Double.parseDouble("43.796009"), Double.parseDouble("21.745934")));
mMyMarkersArray.add(new MyMarker("Restaurant Obilic","Telephone: \n Address: ", "iconObilic", Double.parseDouble("42.547670"), Double.parseDouble("19.660000")));
mMyMarkersArray.add(new MyMarker("Restaurant Dva sesira","Telephone: \n Address: XII vek", "iconDvaSesira", Double.parseDouble("41.486736"), Double.parseDouble("20.731670")));
mMyMarkersArray.add(new MyMarker("Manastir Lipov Lad", "Telephone: \n Address: ","iconLipovLad", Double.parseDouble("44.850546"), Double.parseDouble("20.479869")));
mMyMarkersArray.add(new MyMarker("Restaurant Slodes", "Telephone: nepoznato \n Address: ", "iconSlodes", Double.parseDouble("41.503238"), Double.parseDouble("19.791890")));
setUpMap();
plotMarkers(mMyMarkersArray);
}
private void plotMarkers(ArrayList<MyMarker> markers)
{
if(markers.size() > 0)
{
for (MyMarker myMarker : markers)
{
MarkerOptions markerOption = new MarkerOptions().position(new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude()));
markerOption.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_restaurant));
Marker currentMarker = mMap.addMarker(markerOption);
mMarkersHashMap.put(currentMarker, myMarker);
mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
}
}
}
private int manageMarkerIcon(String markerIcon)
{
if (markerIcon.equals("iconZaplet"))
return R.drawable.zaplet;
else if(markerIcon.equals("iconOresac"))
return R.drawable.oresac;
else if(markerIcon.equals("iconObilic"))
return R.drawable.obilic;
else if(markerIcon.equals("iconLipovLad"))
return R.drawable.lipovlad;
else if(markerIcon.equals("iconSlodes"))
return R.drawable.slodes;
else
return R.drawable.icondefault;
}
private void setUpMap()
{
if (mMap == null)
{
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap != null)
{
mMap.setMyLocationEnabled(true);
LocationManager lm = (LocationManager) getSystemService (LOCATION_SERVICE);
String provider = lm.getBestProvider(new Criteria (), true);
if (provider == null) {
onProviderDisabled (provider);
}
Location loc = lm.getLastKnownLocation(provider);
if (loc != null) {
onLocationChanged (loc);
}
mMap.setOnMapLongClickListener(onLongClickMapSettings ());
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
{
#Override
public boolean onMarkerClick(com.google.android.gms.maps.model.Marker marker)
{
marker.showInfoWindow();
return true;
}
});
}
else
Toast.makeText(getApplicationContext(), "Unable to create Maps", Toast.LENGTH_SHORT).show();
}
}
private OnMapLongClickListener onLongClickMapSettings() {
// TODO Auto-generated method stub
return new OnMapLongClickListener () {
#Override
public void onMapLongClick(LatLng arg0) {
// TODO Auto-generated method stub
Log.i(arg0.toString(), "User long clicked");
}
};
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latlng = new LatLng (location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter
{
public MarkerInfoWindowAdapter()
{
}
#Override
public View getInfoWindow(Marker marker)
{
return null;
}
#SuppressLint("InflateParams") #Override
public View getInfoContents(Marker marker)
{
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
MyMarker myMarker = mMarkersHashMap.get(marker);
ImageView markerIcon = (ImageView) v.findViewById(R.id.marker_icon);
TextView markerLabel = (TextView)v.findViewById(R.id.marker_label);
TextView anotherLabel = (TextView)v.findViewById(R.id.another_label);
markerIcon.setImageResource(manageMarkerIcon(myMarker.getmIcon()));
markerLabel.setText(myMarker.getmLabel());
anotherLabel.setText(myMarker.getmIstorijat());
return v;
}
}
}
Here is code of MyMarker.java
> public class MyMarker
{
private String mLabel;
private String mIstorijat;
private String mIcon;
private Double mLatitude;
private Double mLongitude;
public MyMarker(String label, String istorijat, String icon, Double latitude, Double longitude)
{
this.mLabel = label;
this.mIstorijat = istorijat;
this.mLatitude = latitude;
this.mLongitude = longitude;
this.mIcon = icon;
}
public String getmLabel()
{
return mLabel;
}
public void setmLabel(String mLabel)
{
this.mLabel = mLabel;
}
public String getmIstorijat()
{
return mIstorijat;
}
public void setmIstorijat(String mIstorijat)
{
this.mIstorijat = mIstorijat;
}
public String getmIcon()
{
return mIcon;
}
public void setmIcon(String icon)
{
this.mIcon = icon;
}
public Double getmLatitude()
{
return mLatitude;
}
public void setmLatitude(Double mLatitude)
{
this.mLatitude = mLatitude;
}
public Double getmLongitude()
{
return mLongitude;
}
public void setmLongitude(Double mLongitude)
{
this.mLongitude = mLongitude;
}
}
I'm sorry but I don't really understand your problem here. It seems that you know how to recover the map marker with you MyMarker object using HashMap. And you are also able to create all the markers you need. Since your question is about creating an application with HashMap and multiple markers, it seems that you already have done that. Unless your code doesn't work but in this situation it would be helpfull if you told us about what it does exactly.
I'm not sure about what you are asking, but I believe that you have 5 marker, and you want to get the closest one. If your question is how to do that then I think you just have to loop on every marker and calculate their distance with the user's position to find the smallest one.
If you don't know how to calculate the distance, I personnaly use the distanceTo(Location) method of Location. Maybe it is not the best code but here is what it looks like :
public static double distanceTo(LatLng from, LatLng to) {
Location locationA = new Location("");
locationA.setLatitude(from.latitude);
locationA.setLongitude(from.longitude);
Location locationB = new Location("");
locationB.setLatitude(to.latitude);
locationB.setLongitude(to.longitude);
return locationA.distanceTo(locationB) / 1000;
}
You can for example do something like that :
Marker closest = null;
double minDistance;
for(Marker m : mMarkersHashMap.keySet()){
double distance = distanceTo(currentPos, m.getPosition())
if(closest == null || minDistance > distance){
closest = m;
minDistance = distance;
}
}
Wrote it quickly and haven't tested it but if you want to do it for the 5 closest markers I think this works :
Marker[] closest = new Marker[5];
double[] minDistance = new double[5];
for(Marker m : mMarkersHashMap.keySet()){
double distance = distanceTo(currentPos, m.getPosition())
for(int i = 4; i >=0; i--){
if(closest[i] == null || minDistance[i] > distance){
if(i < 4){
closest[i+1] = closest[i];
minDistance[i+1] = minDistance[i];
}
closest[i] = m;
minDistance[i] = distance;
} else {
break;
}
}
}
I am trying to build an app for an individual project. I have a database of latitude and longitude coordinates with associated levels of radioactivity. The app checks the users location and checks the distance between them and the points in the database. If this distance is less than say 15 meters, it will trigger a warning light.
I was able to get the app to read in the database and store it in an arraylist of classes. I was also able to get the GPS to update location every 2 meters. I want to add a for loop in the onLocationChange method so that the app checks against the database but I am not sure how to do this... how can I pass the "dataPoints" arraylist to the locationlistener method so that the onLocationChange can access it?? Is this completed incorrect? I have included my code below:
public class MainActivity extends Activity{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 2, mLocationListener);
//read in datapoints from text file in assets folder and store in class "radioactivityData" in arrayList "dataPoints"
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(getAssets().open("combinedorderedData.txt")));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
//Define and initialize the ArrayList
ArrayList<radioactivityData> dataPoints = new ArrayList<radioactivityData>(); //The ArrayList stores strings
String inLine; //Buffer to store the current line
try {
while ((inLine = reader.readLine()) != null) //Read line-by-line, until end of file
{
String[] parts = inLine.split(" ");
radioactivityData rad = new radioactivityData();
rad.setlatitude(Double.parseDouble(parts[0]));
rad.setlongitude(Double.parseDouble(parts[1]));
rad.setradioactivity(Integer.parseInt(parts[2]));
dataPoints.add(rad);
}
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //We've finished reading the file
}
//I think I just need to pass the dataPoints array to the LocationListener method... how? is this wrong?
LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
//Here I want to calculate the distance between current location and the data in the dataPoints array
for(int i=0; i<dataPoints.size(); i++){
if(getdistance(dataPoints.get(i).getlatitude(), dataPoints.get(i).getlongitude(),
location.getLatitude(), location.getLongitude())<15 && dataPoints.get(i).getradiation()>5000)
{
txtLat.setText("Turn on the green LED!");
break;
}
else
{
txtLat.setText("No radioactive areas nearby!");
}
}
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
private double getDistance(double lat1, double lon1, double lat2, double lon2){
double theta, dist;
theta = lon1 - lon2;
dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
dist = dist * 1.609344 * 1000;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180);
}
private double rad2deg(double rad) {
return (rad * 180 / Math.PI);
}
};
}
Here is the radioactivityData class in case that would be helpful
public class radioactivityData {
private double latitude;
private double longitude;
private int radioactivity;
public double getlatitude()
{
return latitude;
}
public void setlatitude(double latitude) {
this.latitude = latitude;
}
public double getlongitude()
{
return longitude;
}
public void setlongitude(double longitude) {
this.longitude = longitude;
}
public int getradioactivity()
{
return radioactivity;
}
public void setradioactivity(int radioactivity) {
this.radioactivity = radioactivity;
}
}
from onLocationChanged call a method to which you will pass current location in that method itself get All Location with which you want to compare.