android


Not getting Latitude and Longitude in android


I have searched on Google regarding this issue but didn't get the
solution.I am trying to get Longitude and Latitude of device location.
User will click the image from Camera and at that time I have to get
the Lat,Long of the device using GPS and display that. But is is not
working.
Here is my code:-
public class MainActivity extends Activity {
EditText editAddress,editName;
ImageView ivPhoto;
Button btnTakePic,btnNext1;
Bitmap bitMap;
static int TAKE_PICTURE = 1;
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected double latitude,longitude;
protected boolean gps_enabled,network_enabled;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editAddress = (EditText)findViewById(R.id.edtAddress);
editName = (EditText)findViewById(R.id.edtName);
ivPhoto = (ImageView)findViewById(R.id.ivPhoto);
btnTakePic = (Button)findViewById(R.id.btnTakePic);
btnNext1 = (Button)findViewById(R.id.btnNext1);
btnTakePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,TAKE_PICTURE);
}
});
btnNext1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent nextIntent = new Intent(MainActivity.this,ContactPersonDetail.class);
startActivity(nextIntent);
}
});
}
private void GetLocationLatLong() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!=null){
String message = String.format("Current Location \\n Longitude: %1$s \\n Latitude: %2$s",location.getLongitude(), location.getLatitude());
Toast.makeText(MainActivity.this,message,Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == TAKE_PICTURE && resultCode== RESULT_OK && intent != null){
// get bundle
Bundle extras = intent.getExtras();
// get bitmap
bitMap = (Bitmap) extras.get("data");
ivPhoto.setImageBitmap(bitMap);
GetLocationLatLong();
}
}
private class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
String message = String.format("New Location \n Longitude: %1$s \n Latitude: %2$s", location.getLongitude(), location.getLatitude() );
longitude = location.getLongitude();
latitude = location.getLatitude();
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
Log.d("Longittuteeeeeeeeeeee",message);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, "Provider status changed",Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,"Provider enabled by the user. GPS turned on", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Provider disabled by the user. GPS turned off", Toast.LENGTH_LONG).show();
}
}
}
These are the permissions used in manifest :-
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
<uses-permission android:name="android.permission.INTERNET"/>
In these permission, two permissions (ACCESS_MOCK_LOCATION,CONTROL_LOCATION_UPDATES) are giving error.
errors in permission:-
uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"
Mock locations should only be requested in a test or debug-specific
manifest file (typically src/debug/AndroidManifest.xml) less...
(Ctrl+F1) Using a mock location provider (by requiring the permission
android.permission.ACCESS_MOCK_LOCATION) should only be done in debug
builds (or from tests). In Gradle projects, that means you should only
request this permission in a test or debug source set specific
manifest file. To fix this, create a new manifest file in the debug
folder and move the element there. A typical path to
a debug manifest override file in a Gradle project is
src/debug/AndroidManifest.xml.
Please let me know what I mistake I am doing here.
This part of your GetLocationLatLong function must be in your onCreate method:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
You should set requestLocationUpdates before that method. The rest should work fine.
Also, you don't need these permissions:
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
Try using this. I'm currently using this one to get the device's current location.
public class GPSHelper {
private Context mContext;
// flag for GPS Status
private boolean isGPSEnabled = false;
// flag for network status
private boolean isNetworkEnabled = false;
private LocationManager locationManager;
private double latitude;
private double longitude;
public GPSHelper(Context context) {
mContext = context;
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
}
public LatLng getMyLocation() {
List<String> providers = locationManager.getProviders(true);
Location l = null;
for (int i = 0; i < providers.size(); i++) {
l = locationManager.getLastKnownLocation(providers.get(i));
if (l != null)
break;
}
if (l != null) {
latitude = l.getLatitude();
longitude = l.getLongitude();
}
return new LatLng(latitude, longitude);
}
public boolean isGPSenabled() {
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return (isGPSEnabled || isNetworkEnabled);
}
/**
* Function to get latitude
*/
public double getLatitude() {
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
return longitude;
}
}
Usage:
GPSHelper gpsHelper = new GPSHelper(getActivity());//I'm creating this object inside a fragment
LatLng currentLatLng = gpsHelper.getMyLocation();
currentLat = currentLatLng.latitude;
currentLng = currentLatLng.longitude;
Permissions:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Related Links

Why is onUpgrade() not being invoked on Android sqlite database?
Need to find whether checkbox in listview is checked or not
Android: failed to setLocale() when constructing, closing the database
Android Table Layout with 5x5 dimension
switching activity comes to error
Faster way to open cached bitmaps in the default gallery
NullPointerException Android
Changing the size of a SurfaceView
How to arrange my layout for a large text in android?
Automatically adding a calendar feed (.ics) to android/iphone though link or barcode
How to switch between activity in android if one of activity is called by an handler
JSoup get absolute url of an image with special characters
How to set spinnerMode in codebehind
android application sending small cmds via socket
how to create my own fingerprint for google maps embeded android application for public use
Opening tel: & mailto: links in Android WebViewClient

Categories

HOME
android
uml
go
search
checkstyle
github-for-windows
phpmyadmin
twig
newrelic
scripting
big-o
gembox-spreadsheet
x264
code-coverage
google-admin-sdk
jax-ws
trac
arangodb
jquery-ui-sortable
ibeacon-android
heap
activecollab
emoji
ipmitool
frequency-distribution
3nf
coin3d
symfony-console
articulate-storyline
ember-cli
dataflow-diagram
ios10.2
easeljs
roundup
xunit
mount
syntax-highlighting
gpio
licensing
angularjs-components
progress-bar
intersystems-cache
wcag
uitapgesturerecognizer
volatile
zend-debugger
clickjacking
linkedhashmap
android-gridview
reason
graphhopper
odroid
typesafe-config
urlsession
spring-mvc-test
hackintosh
portforwarding
contract
facebook-social-plugins
vaadin-elements
nanoc
spring-integration-sftp
launchctl
rserve
colorbar
cup
janus
structuremap4
filenet
testrail
rmongo
donations
slackware
usart
pure-css
atlas
mapxtreme
microstation
xcode-server
spring-cloud-feign
resourcemanager
jodd
scaffolding
respondcms
php-socket
turbo-prolog
upx
cortex-m
nullable
kendo-upload
dynatree
r-package
.bash-profile
dnssec
ansi
j-security-check
procedural-programming
crowd
contrast
trdion2011
ss7
mt4j
visual-studio-express
rolify
process-explorer
merb
mysql-error-2013
monotouch.dialog
web-farm
paginator
predicatebuilder
saxparseexception
catransform3d
cgbitmapcontextcreate
build-environment
lobo-cobra
xpsdocument
technical-debt
xslcompiledtransform

Resources

Encrypt Message