How to get latitude and longitude while collecting sensor data? - java

I am working on an app that collects Accelerometer, magnetometer data every 20 milliseconds and it saves the data to a csv file.
What I want to do is collect precise latitude and longitude too at the time of data collection so that I can create a heat map (eg. of house).
I am not an android expert. So, I don't know much on how to implement this feature. Is it possible to get coordinate data every 20 milliseconds during indoor data collection?
Below is my current work. Please help me with how can I get real time lat, long and save it to my csv file and what changes I should make?
public class MainActivity extends AppCompatActivity implements SensorEventListener
{
private SensorManager sensorManager;
private Sensor magnetic;
private int counter = 1;
private boolean recording = false;
private boolean counterOn = false;
private float magValues[] = new float[3];
private Context context;
private static final int REQUESTCODE_STORAGE_PERMISSION = 1;
Collection<String[]> magneticData = new ArrayList<>();
private CsvWriter csvWriter = null;
public static DecimalFormat DECIMAL_FORMATTER;
TextView stateText;
EditText fileIDEdit;
TextView magText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(listenerStartButton);
findViewById(R.id.button2).setOnClickListener(listenerStopButton);
fileIDEdit = (EditText)findViewById(R.id.editText);
magText = (TextView) findViewById(R.id.textView3);
stateText = (TextView) findViewById(R.id.textView);
stateText.setText("Stand by");
context = this;
// Sensor
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
magnetic = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
symbols.setDecimalSeparator('.');
DECIMAL_FORMATTER = new DecimalFormat("#.000", symbols);
}
private View.OnClickListener listenerStartButton = new View.OnClickListener() {
#Override
public void onClick(View v) {
recording = true;
stateText.setText("Recording started");
stateText.setTextColor(Color.parseColor("#FF0000"));
}
};
private int REQUEST_CODE = 1;
private View.OnClickListener listenerStopButton = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(recording == true)
{
recording = false;
counter = 0;
String value = fileIDEdit.getText().toString();
stateText.setText("Recording Stopped");
stateText.setTextColor(Color.parseColor("#0000FF"));
if (storagePermitted((Activity) context)){
csvWriter = new CsvWriter();
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "magnetic" + value + ".csv");
//File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "magnetic" + value + ".csv");
try {
csvWriter.write(file, StandardCharsets.UTF_8, magneticData);
Toast.makeText(MainActivity.this, "File is recorded in memory.", Toast.LENGTH_LONG).show();
} catch (IOException io) {
Log.d("Error", io.getLocalizedMessage());
}
}
}
else{
Toast.makeText(MainActivity.this, "Nothing to save. Recording was not started.", Toast.LENGTH_LONG).show();
}
}
};
#Override
protected void onResume(){
super.onResume();
sensorManager.registerListener(this, magnetic, SensorManager.SENSOR_DELAY_GAME);
}
#Override
public void onSensorChanged(SensorEvent event) {
long timeInMillisec = (new Date()).getTime() + (event.timestamp - System.nanoTime()) / 1000000L;
if(recording) {
float x = 0;
float y = 0;
float z = 0;
double magnitude = 0;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
// New Code:
x = event.values[0];
y = event.values[1];
z = event.values[2];
magnitude = Math.sqrt((x * x) + (y + y)
+ (z * z));
//magText.setText("Magnetometer: " + timeInMillisec+" X= " + roundThis(event.values[0]) + " Y= " + roundThis(event.values[1]) + " Z= " + roundThis(event.values[2]));
magText.setText("Magnetometer: X= " + x + " Y= " + y + " Z= " + z + " Magnitude: " + DECIMAL_FORMATTER.format(magnitude) + "\u00b5Tesla");
Log.d("Record", "Magnetometer" + String.valueOf(counter));
magValues = event.values;
}
//magneticData.add(new String[]{String.valueOf(timeInMillisec), String.valueOf(magValues[0]), String.valueOf(magValues[1]), String.valueOf(magValues[2])});
#SuppressLint("SimpleDateFormat") SimpleDateFormat logLineStamp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS", Locale.getDefault());
//logLineStamp.setTimeZone(TimeZone.getTimeZone("UTC"));
magneticData.add(new String[]{logLineStamp.format(new Date(timeInMillisec)), String.valueOf(x), String.valueOf(y), String.valueOf(z), String.valueOf(magnitude)});
counter++;
}
}
// Checks if the the storage permissions are given or not by the user
// It will request the use if not
private static boolean storagePermitted(Activity activity){
// Check read write permission
Boolean readPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
Boolean writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (readPermission && writePermission){
return true;
}
ActivityCompat.requestPermissions(activity, new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUESTCODE_STORAGE_PERMISSION);
return false;
}
public static float roundThis(float value){
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(4, RoundingMode.HALF_UP);
return bd.floatValue();
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}

Related

How can I show a variable from another class in a textview in Android studio java?

So I have a GPS tracking app and I want to show my data (distance, speed etc) in one of the UI.
My LocationService.java tracks all the metrics in a foreground service:
public class LocationService extends Service implements LocationListener{
public ArrayList<Location> lastLocationResultArray = new ArrayList<>();
public float distance;
public float distanceKm;
public float ascent;
public float descent;
public float currentSpeed;
Location changedLocation;
double currentAltitude;
public float averageSpeed;
private static DecimalFormat df1 = new DecimalFormat("#");
private static DecimalFormat df2 = new DecimalFormat("#.#");
private static DecimalFormat df3 = new DecimalFormat("#.##");
public static final String EXTRA_DISTANCE = "com.example.iathleticsrecorder.EXTRA_DISTANCE";
public LocationCallback locationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if(locationResult != null && locationResult.getLastLocation() != null){
Location actualLocation = locationResult.getLastLocation();
double latitude = locationResult.getLastLocation().getLatitude();
double longitude = locationResult.getLastLocation().getLongitude();
double altitude = locationResult.getLastLocation().getAltitude();
double speed = locationResult.getLastLocation().getSpeed();
Log.d("LOCATION_UPDATE", latitude + ", " + longitude + ", " + altitude + ", " + locationResult);
currentSpeed = (float) (speed*3.6f);
changedLocation = actualLocation;
if(!lastLocationResultArray.isEmpty()) {
distance += changedLocation.distanceTo(lastLocationResultArray.get(lastLocationResultArray.size() - 1));
distanceKm = distance/1000;
Location lastlocation = lastLocationResultArray.get(lastLocationResultArray.size() - 1);
double lastAltitude = lastlocation.getAltitude();
double altitudeChange = altitude-lastAltitude;
if(altitudeChange<-9) {
descent += altitudeChange;
} else if(altitudeChange>9) {
ascent += altitudeChange;
}
}
lastLocationResultArray.add(changedLocation);
Log.d("ENDOFLOOP", distanceKm + ", " + distance + ", " + ascent + ", " + descent + ", " + currentSpeed + " ," + averageSpeed );
}
}
};
public String getDistance() {
return df3.format(distance);
}
Here is an example of how all the metrics are added up from the "Log.d (ENDOFLOOP)":
2020-10-05 19:32:55.486 20116-20116/com.example.iathleticsrecorder
D/ENDOFLOOP: 0.0042962608858942986, 4.296261, 4.296261, 22.800003, -22.800003, 0.08298418 ,0.0
So I know that the variables declared at the top of the LocationService-class is changing (as seen in the log.d), but when I try to get the data from the other class, it will only show "0" in the textview's, as if it does not take the updated value from LocationService.class, but only the declared value (even though I have not decared any value, only the variable). Here's a snippet of the code that is connected to the UI in the StartedSession.java:
I declare the LocationService-class:
LocationService mLocationService = new LocationService();
And use a getter to get the value of the float variable via a button:
btUpdateNumbers = findViewById(R.id.btUpdateNumbers);
btUpdateNumbers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtViewDistance.setText(mLocationService.getDistance());
//txtViewCurrentSpeed.setText(mLocationService.getSpeed());
}
});
Why is it only showing "0"?
Use SharedPreferences that will help u in your case.

Why mMap.addMarker (...) and map.getMyLocation(); dont work and stop my app android?

In sqlite the same method work, but I changed the database to Mysql, this method does not work!
i send arraylist(names) from AsyncTask to show method in MapsActivity
and probleme in ligne
myLocation = mMap.getMyLocation();
and
mMap.addMarker(new MarkerOptions().position(dz).title("welcome to")).showInfoWindow();
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
public void mark(Double latitude, Double longitude) {
LatLng dz = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(dz).title("welcome to")).showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dz, 16));
}
public float distanceBetween(Double latitude, Double longitude) {
float result[] = new float[10];
Location myLocation = mMap.getMyLocation();
Double mylatitude = myLocation.getLatitude();
Double mylongitude = myLocation.getLongitude();
myLocation.distanceBetween(mylatitude, mylongitude, latitude, longitude, result);
return result[0];
}
public void show ( ArrayList names) {
ArrayList<String> arrList = new ArrayList<>();
arrList = names;
int c = arrList.size();
Float t[] = new Float[10];
Double company[] = new Double[3];
if (c > 0) {
int n = 0;
int i = 0;
while (c > 0) {
Double latitude = Double.valueOf(arrList.get(n));
Double longitude = Double.valueOf(arrList.get(n + 1));
Double price = Double.valueOf(arrList.get(n + 2));
t[i] = distanceBetween(latitude, longitude);
if (n == 0) {
company[0] = latitude;
company[1] = longitude;
company[2] = price;
}
if ((i > 0) && (t[i] < t[i - 1])) {
t[i] = t[i - 1];
company[0] = latitude;
company[1] = longitude;
company[2] = price;
}
i = i + 1;
n = n + 3;
c = c - 3;
}
mark(company[0], company[1]);
} else {
Toast T = Toast.makeText(this, "product is not available ", Toast.LENGTH_SHORT);
T.show();
}
Toast.makeText(this, "price of product = " + company[2], Toast.LENGTH_LONG).show();
}
}
public class Parser2 extends AsyncTask<Void,Void,Integer> {
Context c;
String data;
ArrayList<String> names=new ArrayList<>();
public Parser2(Context c, String data) {
this.c = c;
this.data = data;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer==1)
{
MapsActivity m =new MapsActivity();
m.show(names);
}else {
Toast.makeText(c,"Unable to Parse2",Toast.LENGTH_SHORT).show();
}
}
private int parse()
{
try
{
JSONArray ja=new JSONArray(data);
JSONObject jo=null;
names.clear();
int i;
for( i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
String latitude=jo.getString("latitude");
String longitude=jo.getString("longitude");
String price=jo.getString("price");
names.add(latitude);
names.add(longitude);
names.add(price);}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
It seems the reason of the problem is because getMyLocation() is null and the algorithm is expecting it not to be null. Please make sure that this object contains value. You can use this code to check the last location of the user:
LocationManager service = (LocationManager)
getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
Hope this information find you helpful and good luck on your project!

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

Java Sensor filter correction

I am engaging with android sensor data filtering. At the same time, I am not good at JAVA. It needs to integrate "FixFilter" class with main source code which starts ENS492SenorsActivity. In this approach, I aimed that filtering data which is taken from accelerometer and orientation sensors. acx is the taken data from accelerometer in the X directiona and orx is the taken data from orientation data in the X direction.
public float FixFilter (double acx, float orx)
{
orx = 0.75*(orx) + 0.25*(acx);
return orx;
}
public class Ens492SenorsActivity extends Activity implements SensorListener
{
final String tag = "IBMEyes";
SensorManager sm = null;
TextView xViewA = null;
TextView yViewA = null;
TextView zViewA = null;
TextView xViewO = null;
TextView yViewO = null;
TextView zViewO = null;
//for gps
TextView xView1 = null;
TextView yView1 = null;
TextView zView1 = null;
private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
private Timer mTimer = new Timer();
private int REFRESH_TIME = 1000;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.main);
xViewA = (TextView) findViewById(R.id.xbox);
yViewA = (TextView) findViewById(R.id.ybox);
zViewA = (TextView) findViewById(R.id.zbox);
xViewO = (TextView) findViewById(R.id.xboxo);
yViewO = (TextView) findViewById(R.id.yboxo);
zViewO = (TextView) findViewById(R.id.zboxo);
xView1 = (TextView) findViewById(R.id.xbox1);
yView1 = (TextView) findViewById(R.id.ybox1);
zView1 = (TextView) findViewById(R.id.zbox1);
locManager = (LocationManager) getSystemService(this.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
init_arr();
}
public static void connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public void ShowMap(View v)
{
String uri = String.format("geo:%f,%f", alig.getLatitude(), alig.getLongitude());
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
this.startActivity(intent);
}
public double DoruksKalman (double v1, double v2, double v3,double v4,double v5,double v6,double v7,double v8,double v9,double v10 )
{
double result = 0;
//result = 10 / ( 1/ v1 + 1/ v2 +1/ v3 +1/ v4 +1/ v5 +1/ v6 +1/ v7 +1/ v8 +1/ v9 +1/ v10);
result = (v1 + v2 + v3 + v4 +v5 + v6 +v7 + v8 +v9 + v10)/10;
return result;
}
public float FixFilter (double acx, float orx)
{
orx = 0.75*(orx) + 0.25*(acx);
return orx;
}
public void SendToServer(View v)
{
Log.i(getClass().getSimpleName(), "send task - start");
try{
connect("http://192.168.1.117/ens4912/process.php?ip=&lat=" +
DoruksKalman(
alig.getLatitude(), alig.getLatitude(),alig.getLatitude(),
alig.getLatitude(),alig.getLatitude(),alig.getLatitude(),
alig.getLatitude(),alig.getLatitude(),alig.getLatitude(),
alig.getLatitude())+
"&lng="+
DoruksKalman(alig.getLongitude(), alig.getLongitude(),alig.getLongitude(), alig.getLongitude(),
alig.getLongitude(), alig.getLongitude(), alig.getLongitude(),
alig.getLongitude(), alig.getLongitude(), alig.getLongitude())+
"&alt="+
DoruksKalman(alig.getAltitude(),alig.getAltitude(),alig.getAltitude(),
alig.getAltitude(),alig.getAltitude(),alig.getAltitude(),
alig.getAltitude(),alig.getAltitude(),alig.getAltitude(),alig.getAltitude())+
"&accel="+
DoruksKalman(acx_arr[0], acx_arr[1],acx_arr[2],acx_arr[3],acx_arr[4],
acx_arr[5],acx_arr[6],acx_arr[7],
acx_arr[8],acx_arr[9])+
"&mag="+
DoruksKalman(orx_arr[0], orx_arr[1], orx_arr[2], orx_arr[3],
orx_arr[4],orx_arr[5],orx_arr[6],
orx_arr[7],orx_arr[8],orx_arr[9])
);//"http://www.google.com");
}
catch (Exception e)
{
double zero =0.0;
e.printStackTrace();
connect("http://192.168.1.117/ens4912/process.php?ip=&lat=" +
zero+
"&lng="+
zero+
"&alt="+
zero+
"&accel="+
DoruksKalman(acx_arr[0], acx_arr[1],acx_arr[2],acx_arr[3],acx_arr[4],
acx_arr[5],acx_arr[6],acx_arr[7],
acx_arr[8],acx_arr[9])+
"&mag="+
DoruksKalman(orx_arr[0], orx_arr[1], orx_arr[2], orx_arr[3],
orx_arr[4],orx_arr[5],orx_arr[6],
orx_arr[7],orx_arr[8],orx_arr[9])
);
}
Log.i(getClass().getSimpleName(), "send task - end");
}
float orx;
float ory;
float orz;
float acx;
float acy;
float acz;
float [] acx_arr = new float[10];
float [] acy_arr = new float[10];
float [] acz_arr = new float[10];
float [] orx_arr = new float[10];
float [] ory_arr = new float[10];
float [] orz_arr = new float[10];
private void init_arr()
{
for(int i = 0;i <10;i++)
{
acx_arr[i] = 1.0f;
acy_arr[i] = 1.0f;
acz_arr[i] = 1.0f;
orx_arr[i] = 1.0f;
ory_arr[i] = 1.0f;
orz_arr[i] = 1.0f;
}
}
int sensorReadCount = 0;
private final float NOISE = (float) 2.0;
private float mLastX, mLastY, mLastZ;
private boolean mInitialized = false;
public void onSensorChanged(int sensor, float[] values) {
Boolean writeIt = false;
synchronized (this) {
//Log.d(tag, "onSensorChanged: " + sensor + ", x: " + values[0] + ", y: " + values[1] + ", z: " + values[2]);
if (sensor == SensorManager.SENSOR_ORIENTATION) {
xViewO.setText("Orientation X: " +
DoruksKalman(orx_arr[0], orx_arr[1],orx_arr[2],orx_arr[3],orx_arr[4],
orx_arr[5],orx_arr[6],orx_arr[7],
orx_arr[8],orx_arr[9]));
yViewO.setText("Orientation Y: " +
DoruksKalman(ory_arr[0], ory_arr[1],ory_arr[2],ory_arr[3],ory_arr[4],
ory_arr[5],ory_arr[6],ory_arr[7],
ory_arr[8],ory_arr[9]));
zViewO.setText("Orientation Z: " +
DoruksKalman(orz_arr[0], orz_arr[1],orz_arr[2],orz_arr[3],orz_arr[4],
orz_arr[5],orz_arr[6],orz_arr[7],
orx_arr[8],orx_arr[9]));
orx = values[0];
ory = values[1];
orz = values[2];
orx_arr[sensorReadCount%10] = orx;
ory_arr[sensorReadCount%10] = ory;
orz_arr[sensorReadCount%10] = orz;
}
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
acx = values[0];
acy = values[1];
acz = values[2];
if (!mInitialized) {
mLastX = acx;
mLastY = acy;
mLastZ = acz;
mInitialized = true;
}
else {
float deltaX = Math.abs(mLastX - acx);
float deltaY = Math.abs(mLastY - acy);
float deltaZ = Math.abs(mLastZ - acz);
if (deltaX < NOISE) deltaX = (float)0.0;
if (deltaY < NOISE) deltaY = (float)0.0;
if (deltaZ < NOISE) deltaZ = (float)0.0;
mLastX = acx;
mLastY = acy;
mLastZ = acz;
if (deltaX > deltaY) {
//iv.setImageResource(R.drawable.horizontal);
writeIt = false;
} else if (deltaY > deltaX) {
//iv.setImageResource(R.drawable.vertical);
writeIt = true;
} else {
//iv.setVisibility(View.INVISIBLE);
writeIt = false;
}
}
xViewA.setText("Accel X: " + acx);
yViewA.setText("Accel Y: " + acy);
zViewA.setText("Accel Z: " + acz);
/*
xViewA.setText("Accel X: " +
DoruksKalman(acx_arr[0], acx_arr[1],acx_arr[2],acx_arr[3],acx_arr[4],
acx_arr[5],acx_arr[6],acx_arr[7],
acx_arr[8],acx_arr[9]));
yViewA.setText("Accel Y: " +
DoruksKalman(acy_arr[0], acy_arr[1],acy_arr[2],acy_arr[3],acy_arr[4],
acy_arr[5],acy_arr[6],acy_arr[7],
acy_arr[8],acy_arr[9]));
zViewA.setText("Accel Z: " +
DoruksKalman(acz_arr[0], acz_arr[1],acz_arr[2],acz_arr[3],acz_arr[4],
acz_arr[5],acz_arr[6],acz_arr[7],
acz_arr[8],acz_arr[9]));
*/
acx_arr[sensorReadCount%10] = acx;
acy_arr[sensorReadCount%10] = acy;
acz_arr[sensorReadCount%10] = acz;
}
}
try
{
if(sensorReadCount % 10 == 0 && writeIt)// sensorReadCount <= 60 * 10 /* write for 10 minutes*/ )
{
WriteToTXT();
}
}
catch(Exception e)
{
e.printStackTrace();
}
sensorReadCount++;
}
public Boolean IsItBumb()
{
return true;
}
public void onAccuracyChanged(int sensor, int accuracy) {
Log.d(tag,"onAccuracyChanged: " + sensor + ", accuracy: " + accuracy);
}
int id = 0;
private void WriteToTXT()
{
id++;
// TO DO
// Buray\FD dolduracaks\FDn\FDz
//sat\FDr sat\FDr
//id - lat - lon -alt - magx - magy - magz - accx - accy -accz - time
double lat;
double lon;
double alt;
double speed;
try
{
lat = alig.getLatitude();
lon = alig.getLongitude();
alt = alig.getAltitude();
speed = alig.getSpeed();
}
catch( Exception e)
{
lat = 0.0;
lon = 0.0;
alt = 0.0;
speed = 0.0;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
String fileName = "doruks_txt";
/*
String sBody = id + " " + lat + " " + lon + " " + alt + " " + orx + " " + ory + " " +
orz + " " + acx + " " + acy + " " + acz + " " + speed + " " + currentDateandTime;
*/
String sBody = lat + "|" + lon + "|" + alt + " " + orx + " " + ory + " " +
orz + " " + acx + " " + acy + " " + acz + " " + speed + " " + currentDateandTime + "|" + id;
generateNoteOnSD(fileName, sBody);
appendLog(sBody);
}
public void appendLog(String text)
{
File logFile = new File("sdcard/mylog.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void generateNoteOnSD(String sFileName, String sBody)
{
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
sm.registerListener(this,
SensorManager.SENSOR_ORIENTATION |
SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop() {
sm.unregisterListener(this);
super.onStop();
}
public Location alig = null;
class MyLocationListener implements LocationListener {
public Location gLoc = null;
public Location mLoc = null;
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
synchronized (this) {
// This needs to stop getting the location data and save the battery power.
//locManager.removeUpdates(locListener);
alig = location;
String longitude = "Longitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String accuracy = "Accuracy: " + location.getAccuracy();
String time = "Time: " + location.getTime();
//editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
//progress.setVisibility(View.GONE);
xView1.setText("X: " + longitude);
yView1.setText("Y: " + latitude);
zView1.setText("Z: " + altitiude);
}
}
}
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