Run a For loop onLocationChanged - java

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.

Related

Passing longitude and latitude to a java class

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?

Skipped 1492 frames! The application may be doing too much work on its main thread.How to show loader while skipping frames in app? [duplicate]

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

How to make android application show the nearest places with multiple markers

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;
}
}
}

How to access a External class member inside a android Service?

Basically I have a android Service LogService which I trigger from my MainActivity. Inside service class I am creating a object of LocationListener class LocationFetcher with the name locationFetcher. The LocationFetcher class has a public string member FormattedResult. Now Inside the LogService.run() I want to fetch FormattedResult periodically. How to do That ?? Below is code for reference.
I have a LocationListener like This:
/*This is relevant content of LocationFetcher.java */
public class LocationFetcher extends TimerTask implements LocationListener{
public String FormattedResult;
private boolean availableFlag;
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
this.availableFlag=true;
this.FormattedResult=String.format(Locale.ENGLISH, "Lat=\t%f\nLong=\t%f", arg0.getLatitude(),arg0.getLongitude());
Log.d("LocationFetcher",this.FormattedResult);
}
#Override
public void run() {
// TODO Auto-generated method stub
Log.d("LocationFetcher","This is Timer Run !!!");
}}
My android service is like this :
/* This is the relevant pert from LogService.java file*/
public class LogService extends Service{
private Logger logger;
private LocationFetcher locationFetcher;
public LocationManager locationManager;
private Timer timer1;
#Override
public int onStartCommand(Intent intent,int flags, int startId){
super.onStartCommand(intent, flags, startId);
if(!this.running){
this.logger = new Logger(); //Initiated member from subclass
this.logger.start(); //Started
this.timer1 = new Timer(); //Timer for timed job
this.locationFetcher = new LocationFetcher();//THIS IS MY EXTERNAL CLASS in "LocationFetcher.java"
//I am using GPS data.
this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if(this.locationFetcher != null){//NULLPointerException is thrown if I REMOVE this if ??WHY
this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this.locationFetcher);
this.timer1.scheduleAtFixedRate(this.locationFetcher, 5000, 2000);
//Below Line still throws NullPointrException ??WHY
//this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this.locationFetcher);
}else{
Log.d("GPS-Logger"," Found Null LocationFlecther !");
}
}
public void run(){
LogService ll = LogService.this;
LocationManager mgr = ll.locationManager; //THIS IS MY QUESTION
// HOW DO I ACCESS THE GPS LOCATION STORED in locationmanager.FormattedResult
// Which is a string
// //////////////////////////////////////////////////////////////////////////
while(ll.isActive){
try {
String temp ;
if(!temp.isEmpty()){
Log.d("GPS-Logger","data is :"+temp);
}
Log.d("GPS-Logger","data is :");
Thread.sleep(5000);
sec +=1 ;
if(sec >= 12){
Log.d("GPS-Logger","Sending Data Here");
sec = 0;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
ll.isActive=false;
Log.d("GPS-Logged","EXIT Request Received");
}
}
}
I know that I have asked multiple Questions above but I didn't knew how to separate them.
NEED HELP!!!
You can have the location Fetcher modified as "LocationListenerClass" shown below:
The main concern to see in the modified class are as follows:
1.I have used a singleton class for registering and removing location updates from overall area.(i.e say our service etc).
2.You should initialize the location string say (FormattedResult as in you case ) from both onLocationChngaed() and getCurrentLocation(). Because onLocationChngaed() will only call when the distance and time changed as provided in requestLocationUpdates study more about this.
public class LocationListenerClass implements LocationListener{
private static LocationListenerClass instance;
private static Context context;
private LocationManager myLocationManager;
private LocationListener myLocationListener;
private Double latitude = 0d;
private Double longitude = 0d;
public static String FormattedResult;
public static LocationListenerClass getInstance(Context context) {
LocationListenerClass.context = context;
if (null == instance) {
instance = new LocationListenerClass();
}
return instance;
}
public void getCurrentLocation() {
try {
myLocationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 30000, 100,
this);
Location location;
location = myLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
myLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 30000, 100,
myLocationListener);
location = myLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location != null) {
try {
latitude = location.getLatitude();
Data.CURENT_LATITUDE = latitude;
Log.v(ConstantLib.LOG, " latitude : "
+ Data.CURENT_LATITUDE);
longitude = location.getLongitude();
Data.CURENT_LONGITUDE = longitude;
Log.v(ConstantLib.LOG, " longitude : "
+ Data.CURENT_LONGITUDE);
**FormattedResult=String.format(Locale.ENGLISH, "Lat=\t%f\nLong=\t%f", latitude(),longitude());
Log.d("LocationFetcher",this.FormattedResult);**
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void removeLocationUpdates() {
try {
if (myLocationManager != null) {
myLocationManager.removeUpdates(myLocationListener);
}
} catch (Exception e) {
}
}
public void onLocationChanged(Location location) {
try {
if (location != null) {
Data.CURENT_LATITUDE = location.getLatitude();
Log.v(ConstantLib.LOG, "LOCATION CHANGED" + " latitude : "
+ Data.CURENT_LATITUDE);
longitude = location.getLongitude();
Data.CURENT_LONGITUDE = location.getLongitude();
Log.v(ConstantLib.LOG, "LOCATION CHANGED" + " longitude : "
+ Data.CURENT_LONGITUDE);
**FormattedResult=String.format(Locale.ENGLISH, "Lat=\t%f\nLong=\t%f", latitude(),longitude());
Log.d("LocationFetcher",this.FormattedResult);**
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}

Android - Calculate Distance Using Haversine Formula (Using GPS , Lat and Long)

I need some help :) I am assign with a project to come out with the distance / speed and time. I have already come out with the Timer. However, the distance is giving me some problem. The distance does not changed at all from I travel from one place to another.
//GPS
private static Double EARTH_RADIUS = 6371.00; // Radius in Kilometers default
private static final String DEBUG_TAG = "GPS";
private String[] location;
private double[] coordinates;
private double[] gpsOrg;
private double[] gpsEnd;
private LocationManager lm;
private LocationListener locationListener;
private double totalDistanceTravel;
private boolean mPreviewRunning;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waterspill);
/*getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);*/
mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
distanceCal=new LocationUtil(EARTH_RADIUS);
totalDistanceTravel=0;
// ---Additional---
//mapView = (MapView) findViewById(R.id.mapview1);
//mc = mapView.getController();
// ----------------
txtTimer = (TextView) findViewById(R.id.Timer);
gpsOnOff = (TextView) findViewById(R.id.gpsOnOff);
disTrav = (TextView) findViewById(R.id.disTrav);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(startButtonClickListener);
stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(stopButtonClickListener);
testButton = (Button) findViewById(R.id.testButton);
testButton.setOnClickListener(testButtonClickListener);
startButton.setEnabled(false);
stopButton.setEnabled(false);
getLocation();
}
public void getLocation()
{
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0,locationListener);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,locationListener);
}
private OnClickListener startButtonClickListener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
gpsOrg=coordinates;
totalDistanceTravel=0;
Toast.makeText(getBaseContext(),
"Start Location locked : Lat: " + gpsOrg[0] +
" Lng: " + gpsOrg[1],
Toast.LENGTH_SHORT).show();
if (!isTimerStarted)
{
startTimer();
isTimerStarted = true;
}
stopButton.setEnabled(true);
}
};
private OnClickListener stopButtonClickListener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
gpsEnd=coordinates;
//gpsEnd = new double[2];
//gpsEnd[0]=1.457899;
//gpsEnd[1]=103.828659;
Toast.makeText(getBaseContext(),
"End Location locked : Lat: " + gpsEnd[0] +
" Lng: " + gpsEnd[1],
Toast.LENGTH_SHORT).show();
double d = distFrom(gpsOrg[0],gpsOrg[1],gpsEnd[0],gpsEnd[1]);
totalDistanceTravel+=d;
disTrav.setText(Double.toString(d));
}
};
public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = EARTH_RADIUS;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
return new Float(dist).floatValue();
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc) {
if(coordinates!=null)
{
double[] coordinatesPrev=coordinates;
double d = distFrom(coordinatesPrev[0],coordinatesPrev[1],coordinates[0],coordinates[1]);
totalDistanceTravel+=d;
}
else
{
coordinates = getGPS();
}
startButton.setEnabled(true);
}
private double[] getGPS() {
List<String> providers = lm.getProviders(true);
double[] gps = new double[2];
//Loop over the array backwards, and if you get an accurate location, then break out the loop
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
String s = providers.get(i);
Log.d("LocServ",String.format("provider (%d) is %s",i,s));
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
Log.d("LocServ",String.format("Lat %f, Long %f accuracy=%f",gps[0],gps[1],l.getAccuracy()));
gpsOnOff.setText("On");
}
}
return gps;
}
Is there anything wrong with my codes. Please advice and Thanks a lot for your help :)
Test your formula with this: The distance between {-73.995008, 40.752842}, and {-73.994905, 40.752798} should be 0.011532248670891638 km.

Categories

Resources