Android compass showing only view but not moving as expected on a few devices.
This is getting frustrating now. I just completed an app which shows a compass. It was working fine on my Samsung s4 and a few other devices, but when I send the apk file for testing the worst just came out that compass is not working on a few devices, including client device. Till then, I have tried 2, 3 different type of codes which I found on stackoverflow and a few other sites. All of them are working fine on my s4 but not on the client's device.
I'm sharing this code.
I've tested this code in some android 6.0 devices too and it was working just fine. I'm totally not getting where's the error.
Any help will be highly appreciated
public class QiblaActivity extends AppCompatActivity implements SensorEventListener {
private ImageView qiblaNSEW, qiblaIcon;
private float currentDegree = 0f;
private float currentDegree1 = 0f;
RelativeLayout back_Rel, bulb_Rel;
// device sensor manager
private SensorManager mSensorManager;
TextView degreeTV;
AdRequest adRequest;
double angle;
GPSTracker gpsTracker;
Location location;
private static final int PERMS_REQUEST_CODE = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qibla);
Utils.statusBarColor(getWindow(), QiblaActivity.this);
back_Rel = (RelativeLayout) findViewById(R.id.back_Rel);
bulb_Rel = (RelativeLayout) findViewById(R.id.bulb_Rel);
bulb_Rel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(QiblaActivity.this, QuranBulbActivity.class);
startActivity(intent);
}
});
back_Rel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
}
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (hasPermissions())
{
gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation()) {
startQibla();
}
}
else
{
requestPerms();
}
} else {
gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation()) {
startQibla();
} else {
gpsTracker.showSettingsAlert();
}
}
}
private void startQibla() {
qiblaNSEW = (ImageView) findViewById(R.id.qibla_n_s_e_w);
qiblaIcon = (ImageView) findViewById(R.id.qibla_icon);
degreeTV = (TextView) findViewById(R.id.degree_TV);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
setAds();
angle = getAngle();
gpsTracker = new GPSTracker(this);
location = gpsTracker.getLocation();
Log.d("angle", angle + "");
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_GAME);
/* mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE),
SensorManager.SENSOR_DELAY_NORMAL);*/
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
float degree = Math.round(sensorEvent.values[0]);
degreeTV.setText((Float.toString(Math.round(degree - angle)) + "").replace(".0", "").replace("-", ""));
// create a rotation animation (reverse turn degree degrees)
RotateAnimation ra = new RotateAnimation(
currentDegree,
-degree,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF,
0.5f);
// how long the animation will take place
ra.setDuration(210);
// set the animation after the end of the reservation status
ra.setFillAfter(true);
// Start the animation
qiblaNSEW.startAnimation(ra);
currentDegree = -degree;
float tempDegreeNorth = degree;
if (tempDegreeNorth > 180) {
tempDegreeNorth = 360 - tempDegreeNorth;
} else {
tempDegreeNorth = 0 - tempDegreeNorth;
}
Log.d(" north - angle - total", tempDegreeNorth + " - " + angle + " - " + Math.round(tempDegreeNorth + angle));
RotateAnimation raa = new RotateAnimation(
Math.round(tempDegreeNorth + angle),
0.0f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF,
0.5f);
// how long the animation will take place
raa.setDuration(210);
// set the animation after the end of the reservation status
raa.setFillAfter(true);
qiblaIcon.startAnimation(raa);
currentDegree1 = -tempDegreeNorth;
}
private double getAngle() {
GPSTracker gpsTracker = new GPSTracker(this);
double lat1 = toRad(gpsTracker.getLocation().getLatitude());
double lat2 = toRad(21.4266700);
double lon1 = toRad(gpsTracker.getLocation().getLongitude());
double lon2 = toRad(39.8261100);
double dLon = (lon2 - lon1);
double y = sin(dLon) * cos(lat2);
double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
double brng = Math.toDegrees(atan2(y, x));
brng = (brng + 360);
brng = (brng > 360) ? (brng - 360) : brng;
return brng;
}
double toRad(double value) {
value = value * Math.PI / 180;
return value;
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
private void setAds() {
final AdView adViews = (AdView) this.findViewById(R.id.adView);
adRequest = new AdRequest.Builder()
.addTestDevice("253A8ECF2C80597926D6578953E69959").build();
adViews.loadAd(adRequest);
}
private boolean hasPermissions() {
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
for (String perms : permissions) {
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)) {
return false;
}
}
return true;
}
private void requestPerms() {
String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode) {
case PERMS_REQUEST_CODE:
for (int res : grantResults) {
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed) {
//user granted all permissions we can perform our task.
} else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
Toast.makeText(this, "GPS Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
}
I am using a plasio turbo x to test my osmdroid sample. I am also testing using a moto g. In moto g the map rotation which is according to the compass head up is working fine, but in plasio one the compass starts to spin and map also spins, they don't get stable. You can see the logcat here(it is very big, stackoverflow not letting me add it here).
Following is my class in which I have used compass:
public class MainActivity extends FragmentActivity implements LocationListener, IOrientationConsumer,MapEventsReceiver {
private CompassOverlay mCompassOverlay = null;
private MyLocationNewOverlay mLocationOverlay;
IOrientationProvider compass = null;
int deviceOrientation = 0;
MapView mMapView;
float gpsspeed;
float gpsbearing;
float lat = 0;
float lon = 0;
float alt = 0;
long timeOfFix = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
final double lat1 = Double.parseDouble(intent.getStringExtra("lat1"));
final double long1 = Double.parseDouble(intent.getStringExtra("long1"));
final double lat2 = 25.633;
final double long2 = 71.094;
//important! set your user agent to prevent getting banned from the osm servers
org.osmdroid.tileprovider.constants.OpenStreetMapTileProviderConstants.setUserAgentValue(BuildConfig.APPLICATION_ID);
mMapView = (MapView) findViewById(R.id.map);
mMapView.setTileSource(TileSourceFactory.MAPNIK);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
mCompassOverlay = new CompassOverlay(this, new InternalCompassOrientationProvider(this),
mMapView);
mCompassOverlay.enableCompass();
mMapView.getOverlays().add(this.mCompassOverlay);
addOverlays();
GeoPoint startPoint = new GeoPoint(lat1, long1);
IMapController mapController = mMapView.getController();
mapController.setZoom(9);
mapController.setCenter(startPoint);
Marker startMarker = new Marker(mMapView);
startMarker.setPosition(startPoint);
startMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
mMapView.getOverlays().add(startMarker);
RoadManager roadManager = new OSRMRoadManager(this);
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
waypoints.add(startPoint);
GeoPoint endPoint = new GeoPoint(lat2, long2);
Marker endMarker = new Marker(mMapView);
endMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
mMapView.getOverlays().add(endMarker);
waypoints.add(endPoint);
Road road = roadManager.getRoad(waypoints);
Polyline roadOverlay = RoadManager.buildRoadOverlay(road);
mMapView.getOverlays().add(roadOverlay);
mMapView.invalidate();
}
public void addOverlays() {
mLocationOverlay = new MyLocationNewOverlay(mMapView);
mLocationOverlay.setEnableAutoStop(false);
mLocationOverlay.enableFollowLocation();
mLocationOverlay.enableMyLocation();
this.mMapView.getOverlayManager().add(mLocationOverlay);
mMapView.setBuiltInZoomControls(true);
mMapView.setMultiTouchControls(true);
mMapView.setTilesScaledToDpi(true);
}
#Override
protected void onResume() {
super.onResume();
//lock the device in current screen orientation
int orientation;
int rotation = ((WindowManager) this.getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
switch (rotation) {
case Surface.ROTATION_0:
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
this.deviceOrientation = 0;
break;
case Surface.ROTATION_90:
this.deviceOrientation = 90;
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
break;
case Surface.ROTATION_180:
this.deviceOrientation = 180;
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
break;
default:
this.deviceOrientation = 270;
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
break;
}
this.setRequestedOrientation(orientation);
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) this);
} catch (Exception ex) {
}
compass = new InternalCompassOrientationProvider(this);
compass.startOrientationProvider(this);
mMapView.getController().zoomTo(14);
}
#Override
public void onLocationChanged(Location location) {
if (mMapView == null)
return;
//after the first fix, schedule the task to change the icon
//mMapView.getController().setCenter(new GeoPoint(location.getLatitude(), location.getLongitude()));
mMapView.invalidate();
gpsbearing = location.getBearing();
gpsspeed = location.getSpeed();
lat = (float) location.getLatitude();
lon = (float) location.getLongitude();
alt = (float) location.getAltitude(); //meters
timeOfFix = location.getTime();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
protected void onPause() {
super.onPause();
compass.stopOrientationProvider();
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
lm.removeUpdates(this);
} catch (Exception ex) {
}
//unlock the orientation
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
Float trueNorth = 0f;
#Override
public void onOrientationChanged(final float orientationToMagneticNorth, IOrientationProvider source) {
GeomagneticField gf = new GeomagneticField(lat, lon, alt, timeOfFix);
trueNorth = orientationToMagneticNorth + gf.getDeclination();
gf=null;
synchronized (trueNorth) {
if (trueNorth > 360.0f) {
trueNorth = trueNorth - 360.0f;
}
//use gps bearing instead of the compass
if (gpsspeed > 0.01f) {
float t = (360 - gpsbearing - this.deviceOrientation);
if (t < 0) {
t += 360;
}
if (t > 360) {
t -= 360;
}
mMapView.setMapOrientation(t);
} else {
//this part adjusts the desired map rotation based on device orientation and compass heading
float t = (360 - trueNorth - this.deviceOrientation);
if (t < 0) {
t += 360;
}
if (t > 360) {
t -= 360;
}
mMapView.setMapOrientation(t);
}
this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (this!=null ) {
Toast.makeText(MainActivity.this, "GPS Speed: " + gpsspeed + "m/s GPS Bearing: " + gpsbearing +
"\nDevice Orientation: " + (int) deviceOrientation + " Compass heading: " + (int) orientationToMagneticNorth + "\n" +
"True north: " + trueNorth.intValue() + " Map Orientation: " + (int) mMapView.getMapOrientation() + "\n", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public boolean singleTapConfirmedHelper(GeoPoint geoPoint) {
return false;
}
#Override
public boolean longPressHelper(GeoPoint geoPoint) {
return false;
}
}
I am trying to create the setting panel at the info window such that we can use the slider inside the info window to adjust something. When it comes to the implementation and execution , I have found that the info window is always gaining the onclick focus. There are n NO any responses by clicking the sliders inside the info window. Woudl you please tell me how to make slider controls to be focused when the user clicks and drag the info windows
?
The below is my code :
package com.larry.proto.maptest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader.TileMode;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.os.Vibrator;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
public class MainActivity extends FragmentActivity implements LocationListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
Location myLocation;
LocationManager lm;
private ArrayList<Checkpoint> cpList = new ArrayList<Checkpoint> ();
private ArrayList<Marker> thisMarkerList = new ArrayList<Marker> ();
private List<LatLng> ppoints = new ArrayList<LatLng> ();
private int requestCode;
private LatLng globalPoint;
private String infoDesp;
private String infoLat;
private String infoLong;
private Marker mSelectedMarker;
private boolean mRefreshingInfoWindow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
SupportMapFragment sFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
myMap = sFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
lm = (LocationManager) getSystemService (LOCATION_SERVICE);
String provider = lm.getBestProvider(new Criteria(), true);
Location loc = lm.getLastKnownLocation(provider);
if(loc!=null)
{
onLocationChanged(loc);
}
SharedPreferences prefs = getApplicationContext().getSharedPreferences("MyPref", 0);
String restoredLat = prefs.getString("lat", null);
String restoredLng = prefs.getString("lng", null);
String restoredText = prefs.getString("title", null);
myMap.setOnMapLongClickListener(setting());
myMap.getUiSettings().setRotateGesturesEnabled(false);
if(null!=restoredText){
double lat = null!=restoredLat ? Double.parseDouble(restoredLat) : null;
double lng = null!= restoredLng ? Double.parseDouble(restoredLng) : null;
LatLng posi = new LatLng(lat, lng);
myMap.addMarker(new MarkerOptions().position(posi).title(restoredText)
.snippet(String.valueOf(restoredLat) + "," +
String.valueOf(restoredLng))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
CameraPosition cameraPosition = new CameraPosition.Builder().target(posi).zoom(14).build();
myMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
private OnMapLongClickListener setting() {
// TODO Auto-generated method stub
return new OnMapLongClickListener(){
#Override
public void onMapLongClick(LatLng point) {
// TODO Auto-generated method stub
globalPoint = point;
requestCode = 0;
Intent mIntent = new Intent();
mIntent.setClass(MainActivity.this, SliderActivity.class);
startActivityForResult(mIntent, requestCode);
}};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS", Toast.LENGTH_LONG)
.show();
} else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latlng = new LatLng(location.getLatitude() , location.getLongitude());
myMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
myMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
private void addMarkersToMap() {
myMap.clear();
ppoints.clear();
LatLng ll;
for (int i = 0; i < cpList.size(); i++) {
ll = new LatLng(cpList.get(i).getPoint().latitude, cpList.get(i).getPoint().longitude);
ppoints.add(ll);
}
int length = ppoints.size();
LatLng first = null ;
if(length >2){
for( int i = 0 ; i < ppoints.size() -1 ; i++){
first = ppoints.get(0);
LatLng pt = ppoints.get(i);
LatLng ptNext = ppoints.get(i+1);
DrawArrowHead(myMap, pt, ptNext , Color.RED , cpList.get(i).getDesp() , i+1 , true);
createDashedLine(myMap, pt, ptNext , Color.RED);
}
List<LatLng> current = ppoints.subList(ppoints.size()-2, ppoints.size());
for( int i = 0 ; i < current.size() -1 ; i++){
first = ppoints.get(0);
LatLng pt = current.get(i);
LatLng ptNext = current.get(i+1);
DrawArrowHead(myMap, pt, ptNext , Color.BLUE , cpList.get(i).getDesp() ,i+1 , false);
createDashedLine(myMap, pt, ptNext , Color.BLUE);
}
myMap.addMarker(new MarkerOptions().position(new LatLng(first.latitude ,
first.longitude )).title("Starting Point")
.snippet(String.valueOf(first.latitude) + "," +
String.valueOf(first.longitude))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}else if( length ==1){
for( int i = 0 ; i < ppoints.size() ; i++){
myMap.addMarker(new MarkerOptions().position(new LatLng(ppoints.get(i).latitude ,
ppoints.get(i).longitude )).title("Starting Point")
.snippet(String.valueOf(ppoints.get(i).latitude) + "," +
String.valueOf(ppoints.get(i).longitude))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
}
else{
myMap.addPolyline(new PolylineOptions().width(5).color(Color.BLUE).addAll(ppoints));
for( int i = 0 ; i < ppoints.size() -1 ; i++){
first = ppoints.get(0);
LatLng pt = ppoints.get(i);
LatLng ptNext = ppoints.get(i+1);
DrawArrowHead(myMap, pt, ptNext , Color.BLUE , cpList.get(i).getDesp() , i+1 , true);
createDashedLine(myMap, pt, ptNext , Color.BLUE);
}
myMap.addMarker(new MarkerOptions().position(new LatLng(first.latitude ,
first.longitude )).title("Starting Point")
.snippet(String.valueOf(first.latitude) + "," +
String.valueOf(first.longitude))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
}
private final double degreesPerRadian = 180.0 / Math.PI;
private void DrawArrowHead(GoogleMap mMap, LatLng from, LatLng to , int color, String desp , int number , boolean boolR){
double bearing = GetBearing(from, to);
double adjBearing = Math.round(bearing / 3) * 3;
while (adjBearing >= 120) {
adjBearing -= 120;
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url;
Bitmap image = null;
try {
String name = "dir_" + String.valueOf((int)adjBearing) + ".png";
String link = "http://www.google.com/intl/en_ALL/mapfiles/" + name;
Log.d("ling k" , link);
url = new URL(link);
try {
String imageName = link.substring(link.lastIndexOf("/"), link.length());
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + imageName );
if(!file.exists()){
startService(new Intent(MainActivity.this , ImageIntentService.class).putExtra("urlpath", link));
Options mBitmapOptions = new BitmapFactory.Options();
mBitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_4444;
mBitmapOptions.inDither = true;
mBitmapOptions.inPurgeable = true;
mBitmapOptions.inInputShareable = true;
Rect rec = new Rect();
rec.set(-1, -1, -1, -1);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream() , rec , mBitmapOptions);
image = getResizedBitmap(image , image.getHeight()*2 , image.getWidth()*2);
}else{
Options mBitmapOptions = new BitmapFactory.Options();
mBitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_4444;
mBitmapOptions.inDither = true;
mBitmapOptions.inPurgeable = true;
mBitmapOptions.inInputShareable = true;
Rect rec = new Rect();
rec.set(-1, -1, -1, -1);
try {
image = BitmapFactory.decodeStream(new FileInputStream(file), null, mBitmapOptions);
image = getResizedBitmap(image , image.getHeight()*2 , image.getWidth()*2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (image != null){
float anchorX = 0.5f;
float anchorY = 0.5f;
int offsetX = 0;
int offsetY = 0;
int width = image.getWidth();
int height = image.getHeight();
if (bearing >= 292.5 && bearing < 335.5){
offsetX = 24;
offsetY = 24;
offsetX = width;
offsetY = height;
}
else if (bearing >= 247.5 && bearing < 292.5){
offsetX = 24;
offsetY = 12;
offsetX = width;
offsetY = height/2;
}
else if (bearing >= 202.5 && bearing < 247.5){
offsetX = 24;
offsetY = 0;
offsetX = width;
offsetY = 0;
}
else if (bearing >= 157.5 && bearing < 202.5){
offsetX = 12;
offsetY = 0;
offsetX = width/2;
offsetY = 0;
}
else if (bearing >= 112.5 && bearing < 157.5){
offsetX = 0;
offsetY = 0;
}
else if (bearing >= 67.5 && bearing < 112.5){
offsetX = 0;
offsetY = 12;
offsetX = 0;
offsetY = height/2;
}
else if (bearing >= 22.5 && bearing < 67.5){
offsetX = 0;
offsetY = 24;
offsetX = 0;
offsetY = height;
}
else {
offsetX = 12;
offsetY = 24;
offsetX = width/2;
offsetY = height;
}
Bitmap wideBmp;
Canvas wideBmpCanvas;
Rect src, dest;
wideBmp = Bitmap.createBitmap(image.getWidth() *2, image.getHeight() * 2, image.getConfig());
wideBmpCanvas = new Canvas(wideBmp);
src = new Rect(0, 0, image.getWidth(), image.getHeight());
dest = new Rect(src);
dest.offset(offsetX, offsetY);
Paint maskedPaint = new Paint();
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
ColorMatrix cm = new ColorMatrix();
cm.set(new float[] {
1, 0, 0, 0, r,
0, 1, 0, 0, g,
0, 0, 1, 0, b,
0, 0, 0, 1, 0 }); // last line is antialias
maskedPaint.setColorFilter(new ColorMatrixColorFilter(cm));
maskedPaint.setShader(new BitmapShader(image, TileMode.REPEAT, TileMode.REPEAT));
// color
wideBmpCanvas.drawBitmap(image, src, dest, maskedPaint);
if(boolR == true){
Paint stroke = new Paint();
stroke.setColor(Color.YELLOW);
stroke.setAntiAlias(false);
stroke.setStrokeWidth(8);
stroke.setTextSize(60);
wideBmpCanvas.drawText(String.valueOf(number),
(float)wideBmpCanvas.getWidth()/2, (float)wideBmpCanvas.getHeight()/2, stroke);
}
infoDesp = desp;
infoLat =String.valueOf(to.latitude);
infoLong = String.valueOf(to.longitude);
mMap.setInfoWindowAdapter(new CustomInfoAdapter());
mMap.addMarker(new MarkerOptions()
.position(to).title(desp)
.snippet(String.valueOf(to.latitude) + "," + String.valueOf(to.longitude))
.icon(BitmapDescriptorFactory.fromBitmap(wideBmp))
.anchor(anchorX, anchorY));
}
}
class CustomInfoAdapter implements InfoWindowAdapter{
#Override
public View getInfoContents(Marker arg0) {
View marker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).
inflate(R.layout.custom_marker_layout, null);
if (!mRefreshingInfoWindow) {
mSelectedMarker = arg0;
TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
TextView lat1 = (TextView) marker.findViewById(R.id.textView1);
TextView long1 = (TextView) marker.findViewById(R.id.textView2);
SeekBar sk = (SeekBar) marker.findViewById(R.id.seekBar1);
numTxt.setText(arg0.getTitle());
lat1.setText(String.valueOf(arg0.getPosition().latitude));
long1.setText(String.valueOf(arg0.getPosition().longitude));
sk.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
if(progress==25){
Vibrator v = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
}
}
});
sk.requestFocus();
}else{
refreshInfoWindow();
}
return marker;
}
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
private void refreshInfoWindow() {
if (mSelectedMarker == null) {
return;
}
mRefreshingInfoWindow = true;
mSelectedMarker.showInfoWindow();
mRefreshingInfoWindow = false;
}
}
private double GetBearing(LatLng from, LatLng to){
double lat1 = from.latitude * Math.PI / 180.0;
double lon1 = from.longitude * Math.PI / 180.0;
double lat2 = to.latitude * Math.PI / 180.0;
double lon2 = to.longitude * Math.PI / 180.0;
double angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ),
Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
if (angle < 0.0)
angle += Math.PI * 2.0;
angle = angle * degreesPerRadian;
return angle;
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
public void writeToFile(Checkpoint cp , String vertical , String circle , File f){
OutputStreamWriter outStreamWriter = null;
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(f, true);
outStreamWriter = new OutputStreamWriter(outStream);
outStreamWriter.write(new char[]{});
outStreamWriter.append(cp.getDesp());
outStreamWriter.append('\n');
outStreamWriter.append(String.valueOf(cp.getPoint().latitude));
outStreamWriter.append('\n');
outStreamWriter.append(String.valueOf(cp.getPoint().longitude));
outStreamWriter.append('\n');
outStreamWriter.append("the vertical slider value is :" + vertical);
outStreamWriter.append('\n');
outStreamWriter.append("the circle slider value is :" + circle);
outStreamWriter.append('\n');
outStreamWriter.flush();
outStreamWriter.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void createDashedLine(GoogleMap map, LatLng latLngOrig, LatLng latLngDest, int color){
double difLat = latLngDest.latitude - latLngOrig.latitude;
double difLng = latLngDest.longitude - latLngOrig.longitude;
double zoom = map.getCameraPosition().zoom;
double divLat = difLat / (zoom * 2);
double divLng = difLng / (zoom * 2);
LatLng tmpLatOri = latLngOrig;
for(int i = 0; i < (zoom * 2); i++){
LatLng loopLatLng = tmpLatOri;
if(i > 0){
loopLatLng = new LatLng(tmpLatOri.latitude + (divLat * 0.25f), tmpLatOri.longitude + (divLng * 0.25f));
}
Polyline polyline = map.addPolyline(new PolylineOptions()
.add(loopLatLng).add(new LatLng(tmpLatOri.latitude + divLat, tmpLatOri.longitude + divLng))
.color(color).width(5f));
tmpLatOri = new LatLng(tmpLatOri.latitude + divLat, tmpLatOri.longitude + divLng);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode ==0){
if(resultCode ==RESULT_OK){
String change01 = data.getStringExtra("change01");
String change02 = data.getStringExtra("change02");
Toast.makeText(MainActivity.this , change01 + " " + change02 , Toast.LENGTH_SHORT).show();
Checkpoint cp = new Checkpoint("Destination", globalPoint, 0);
Log.d("lati long" , String.valueOf(globalPoint.latitude) + ":" + String.valueOf(globalPoint.longitude));
cpList.add(cp);
File dir = new File( Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + "NOVAX" );
if(!dir.exists()){
dir.mkdirs();
}
Checkpoint lastlyAdded = cpList.get(cpList.size() -1 );
writeToFile(lastlyAdded , change01 , change02 , new File(dir.getAbsolutePath()+ File.separator + "text.txt" ));
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.putString("title", lastlyAdded.getDesp());
editor.putString("lat", String.valueOf(lastlyAdded.getPoint().latitude));
editor.putString("lng", String.valueOf(lastlyAdded.getPoint().longitude));
editor.commit();
for(int i = 0 ; i < cpList.size() ; i ++){
Checkpoint cPoint = cpList.get(i);
if(!cPoint.getPoint().equals(lastlyAdded.getPoint())){
cPoint.setState(1);
cPoint.setDesp("Checkpoint "+String.valueOf(i+1) );
}
}
addMarkersToMap();
}
}
}
}
According to Google's documentation, custom info windows are not real windows, but instead a rendered image inserted into the map view. The only items in a google map that can gain focus seem to be the markers themselves. The info windows an take a onClickListener though. Here's the relevant info. Look at the note in the Custom Info Windows section in their docs.
Note: The info window that is drawn is not a live view. The view is rendered as an image (using View.draw(Canvas)) at the time it is returned. This means that any subsequent changes to the view will not be reflected by the info window on the map. To update the info window later (for example, after an image has loaded), call showInfoWindow(). Furthermore, the info window will not respect any of the interactivity typical for a normal view such as touch or gesture events. However you can listen to a generic click event on the whole info window as described in the section below.
There may be a way to use a FrameLayout and a view overtop, acting like a custom info window, but that's more of a hack than a supported solution.
I've recently been working on simple speed calculations for an application I'm working on, but the code I have takes far too long to retrieve the location, and I know that questions like this have been asked before, but none of the answers seem to retrieve the results I'm looking for. So, how can I make this code have gps fixes within a matter of seconds, and is it even possible?
My LocationListener:
package me.dylan.acf;
import java.text.DecimalFormat;
import java.util.ArrayList;
import android.app.NotificationManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.text.format.Time;
import android.widget.TextView;
public class GPSManager implements LocationListener {
ArrayList<Double> avgspeeds = new ArrayList<Double>();
TextView debug;
NotificationManager mngr;
double avgspeed;
long lastTime = 0;
GraphView view;
Location lastloc;
int earthRadius = 6371;
long delaytime = 30;
ArrayList<Double> allspeeds = new ArrayList<Double>();
public GPSManager(TextView view) {
debug = view;
Location location = ACF.instance.lmanager
.getLastKnownLocation(ACF.instance
.getProperLocationsServices(ACF.instance
.getApplicationContext()));
if (location != null) {
double speed = location.getSpeed();
lastloc = location;
debug.setText("Average Speed: " + avgspeed + "\nCurrent speed: "
+ speed + "\nLocation updates: " + avgspeeds.size());
}
}
#Override
public void onLocationChanged(Location location) {
// DecimalFormat format = new DecimalFormat("0.00");
double speed = location.getSpeed();
if (lastloc != null) {
double latDist = Math.toRadians(location.getLatitude()
- lastloc.getLatitude());
double lonDist = Math.toRadians(location.getLongitude()
- lastloc.getLongitude());
double lat1 = Math.toRadians(location.getLatitude());
double lat2 = Math.toRadians(lastloc.getLatitude());
double a = Math.sin(latDist / 2) * Math.sin(latDist / 2)
+ Math.sin(lonDist / 2) * Math.sin(lonDist / 2)
* Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
speed = (dist * 0.621371) / Math.abs(System.currentTimeMillis() - lastTime * 60 * 60 * 60);
lastTime = System.currentTimeMillis();
}
allspeeds.add(speed);
if (allspeeds.size() > 30) {
allspeeds.remove(0);
}
avgspeed = 0;
for (double d : allspeeds) {
avgspeed += d;
}
avgspeed /= allspeeds.size();
// avgspeed = Double.parseDouble(format.format(avgspeed));
avgspeeds.add(avgspeed);
lastloc = location;
debug.setText("Average Speed: " + avgspeed + "\nCurrent speed: "
+ speed + "\nLocation updates: " + avgspeeds.size());
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Where I call it:
public void updateWithProperService() {
lmanager.requestSingleUpdate(
getProperLocationsServices(getApplicationContext()), GPSmngr,
null);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
updateWithProperService();
}
}, 10000);
}
public String getProperLocationsServices(Context context) {
if (lmanager == null)
lmanager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
int minTime = 3000;
/*
* boolean isGPS = false; boolean isNetwork = false; try { isGPS =
* lmanager.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch
* (Exception e) { e.printStackTrace(); } try { isNetwork = lmanager
* .isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch
* (Exception e) { e.printStackTrace(); }
*/
List<String> matchingProviders = lmanager.getAllProviders();
Location bestResult = null;
long bestTime = 0;
for (String provider : matchingProviders) {
Location location = lmanager.getLastKnownLocation(provider);
if (location != null) {
// float accuracy = location.getAccuracy();
long time = location.getTime();
// float bestAccuracy;
/*
* if ((time > minTime && accuracy < bestAccuracy )) {
* bestResult = location; bestTime = time; } else
*/if (time < minTime &&
/* bestAccuracy == Float.MAX_VALUE && */time < bestTime) {
bestResult = location;
bestTime = time;
}
}
}
if (bestResult != null)
return bestResult.getProvider();
else
return LocationManager.NETWORK_PROVIDER;
}
google has released a nice API on their recent Google IO 2013 event:
https://developers.google.com/events/io/sessions/324498944
you should check it out and see how you can minimize your code.
do note that it requires that the device would have the play store app for this to work.
this method has many advantages over using the normal location sensors (battery, speed , accuracy,...) .
gps needs about 15 seconds if it was disabled before and when using Assisted GPS.
you cannot improve that.
Whitout AGPS it needs 25-35 seconds, under good conditions.
The term is called "Time to First fix" (TTF).
I have five fixed GPS locations in my application. When you come near them, it will be stored in the application and unlock a medal of some sort. I have used SharedPreferences for my quiz and medals, but I am a little unsure on how to store GPS in SharedPreferences as well. This is my code so far.
package com.example.norskattraksjon;
import java.util.ArrayList;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
public class MyLocationListener implements LocationListener {
private ArrayList<GeoPoint> gplist;
public MyLocationListener(ArrayList<GeoPoint> gpList2) {
gplist = gpList2;
}
public void onLocationChanged(Location location) {
System.out.println("Den kommer hits");
for(GeoPoint gp : gplist){
//SÂ henter vi ut latitude og longitude.
//Det forvirrende her er at klassen "Location" bruker float-koordinater
//mens "GeoPoint" bruker mikrokoordinater. Dermed m man konvertere mellom de.
float latitude = (float) (gp.getLatitudeE6() / 1E6);
float longitude = (float) (gp.getLongitudeE6() / 1E6);
//Vi lager en "location" for hvert av punktene i gplist, utifra latitude og longitude.
Location test = new Location("tester");
test.setLatitude(latitude);
test.setLongitude(longitude);
//location.distanceTo() er en metode som sjekker avstanden til punkter.
//Her skal distansen vÊre under 10 000 meter.
if(location.distanceTo(test) <= 70){
//Om distansen er under 10 000m, s lager du en toast som gir den faktiske avstanden til punktet.
System.out.println("Her er du");
SharedPreferences prefs = getSharedPreferences("com.example.norskattraksjon",
Context.MODE_PRIVATE);
// Lagre en tekst... først trenger vi en editor
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("location", true);
//Lagrer verdien
editor.commit();
};
}
};
private SharedPreferences getSharedPreferences(String string,
int modePrivate) {
// TODO Auto-generated method stub
return null;
}
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
}
}
And this is my other coherent code;
package com.example.norskattraksjon;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class MainActivityMap extends MapActivity {
private MapController mc;
MapOverlays overlay;
ArrayList<GeoPoint> gplist;
List<Overlay> overlayList;
LocationListener mlocListener; //Denne klassen lytter etter lokasjonen din
LocationManager mlocManager; //Mens denne kobler deg opp mot telefonens GPS.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("WEEEEEEE");
setContentView(R.layout.mapview);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mc = mapView.getController();
gplist = new ArrayList<GeoPoint>();
overlayList = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.ic_launcher);
overlay = new MapOverlays(drawable, this);
double lat = 60.39403;
double lon = 5.330579;
GeoPoint point = new GeoPoint ((int) (lat * 1E6), (int) (lon*1E6));
gplist.add(point);
OverlayItem punkt1 = new OverlayItem(point, "Du har kommet til!", "Domkyrkja i Bergen!");
double lat2 = 60.702251;
double lon2 = 5.333685;
GeoPoint point1 = new GeoPoint ((int) (lat2 * 1E6), (int) (lon2 *1E6));
gplist.add(point1);
OverlayItem punkt2 = new OverlayItem(point1, "Her ble", "Noen som drepte kongen begravd");
double lat3 = 60.37829;
double lon3 = 5.335665;
GeoPoint point3 = new GeoPoint ((int) (lat3 * 1E6), (int) (lon3 *1E6));
gplist.add(point3);
OverlayItem punkt3 = new OverlayItem(point3, "Her ble", "Himmelfarten med tran i maga!");
double lat4 = 60.213789;
double lon4 = 5.369895;
GeoPoint point4 = new GeoPoint ((int) (lat4 * 1E6), (int) (lon4 *1E6));
gplist.add(point4);
OverlayItem punkt4 = new OverlayItem(point4, "Her ble", "Flygelet skapt");
double lat5 = 60.413619;
double lon5 = 5.37579;
GeoPoint point5 = new GeoPoint ((int) (lat5 * 1E6), (int) (lon5 *1E6));
gplist.add(point5);
OverlayItem punkt5 = new OverlayItem(point5, "Her ble", "Bergensbakken bakt");
overlay.addOverlay(punkt1);
overlay.addOverlay(punkt2);
overlay.addOverlay(punkt3);
overlay.addOverlay(punkt4);
overlay.addOverlay(punkt5);
overlayList.add(overlay);
mc.animateTo(point);
mc.setZoom(11);
//Dette er metoden man bruker for  koble opp til mobilens GPS
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//Her lager vi en instans av vÂr egen LocationListener. Dette gj¯r at vi kan bestemme selv hva som skjer
//nÂr man trykker p overlays.
mlocListener = new MyLocationListener(gplist);
//Her sier vi at vÂr LocationListener skal sp¯rre om GPS-signaler fra en GPS_PROVIDER.
//0 stÂr for minimumstiden mellom oppdateringer
//Den andre 0 stÂr for minimumsdistansen mellom oppdateringer
//mLocListener er instansen vi lagde av vÂr egen LocationListener.
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
public GeoPoint newGeo(double x, double y){
int a = (int) (x * 1E6);
int b = (int) (y * 1E6);
GeoPoint z = new GeoPoint(a,b);
return z;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
int latE6 = (int) (lat * 1e6);
int lonE6 = (int) (lon * 1e6);
p.edit().putInt("Lat", latE6).commit();
p.edit().putInt("Long", lonE6).commit();
In the above code lat and lon are your location's latitude and longitude. then you can retrieve them as int variables and get location values by dividing them by 1e6 again.
int lat= p.getInt("Lat", "");
int lon = p.getInt("Long", "");
You can store the Lat and Long directly in the SharedPreference as follows:
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
p.edit().putString("Lat", YOUR_LATTITUDE).commit();
p.edit().putString("Long", YOUR_LONGITUDE).commit(); //SECURITY HAZARD: read below...
Then you can retrieve it like this:
String username = p.getString("Lat", "");
String password = p.getString("Long", "");
Hope it will help you.
make a method like this and just pass values as parameter.
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
you can put long in it. change it to this
private void SavePreferences(String key, long value)
editor.putInt(key,value)