i am new to android.i need to get lattitude and logitude of current location.but it shows null pointer exception in location.here below i added my code.
LocationManager lm;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
location=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
SaveLocation(location);
}
private void SaveLocation(Location location) {
Long time=new GregorianCalendar().getTimeInMillis()+1*60*1000;
Intent intent=new Intent(MainActivity.this,AlarmReceiver.class);
intent.putExtra("lat",location.getLatitude());
intent.putExtra("lon",location.getLongitude());
AlarmManager alarmManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,time,PendingIntent.getBroadcast(this,1,intent,PendingIntent.FLAG_UPDATE_CURRENT));
}
my androidmanifasted file is like
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.gps.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Anyone can help me?
Your location is null because you instantly try to get the last known location after you create a LocationManager. In this time (some milliseconds) your device can't find any locations.
You need a time gap between your initalization of your LocationManager and the getLastKnownLocation-method. I would recommend to put the getLastKnownLocation-method in an OnClick event on a button to create a time gap.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
/....
}
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
location=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
SaveLocation(location);
}
});
Your Location object is null, since there is no last known location stored.
location=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Check if last known location exists.
if(location != null) {
SaveLocation(location);
}
//to find the current latitude and longitude of user
public String getMyLocation(){
locationManager=(LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!=null){
loc[0]=location.getLatitude();
loc[1]=location.getLongitude();
Log.d("STATUS n ", loc[0]+"entered 1"+loc[1]);
}
else {
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null)
{
loc[0]=location.getLatitude();
loc[1]=location.getLongitude();
Log.d("STATUS n","else"+loc[0]+"entered 1"+loc[1] );
}
}
return getPlace(loc);
}
Related
Hello i am new to android development . I want to get my current Location but i need to wait for my listener start working . The problem is that i dont change position so the listener cant work (?) !
Here is the sample of my code
My listener :
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
textView.append(location.getLongitude() + "\n" + location.getLatitude() + "\n");
// just monitoring
lat = location.getLatitude();
lng = location.getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
and i request the updates on this
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300, 0, locationListener);
So if i am not mistaken the gps will take the new position based on time (300ms) or based on distance which is 0 so its gonna work ?? Should i wait some time to start taking it? How long? more than 2 minutes?
I got wi-fi open and gps of course this is my manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Details" />
<activity android:name=".LoginMenu" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity android:name=".Road" />
<activity android:name=".LoopActivity" />
<activity android:name=".Pedestrians"></activity>
</application>
Many Thanks in regards
There are some questions regarding this issue but I could not find any method works without problem. I implemented the version of the project with GPS provider and now I want to implement a version which can find the location of user without GPS, just using network provider such as Wifi. I tried this but it is not working (I could not get the "done" message in any way):
public class MapsActivity extends FragmentActivity {
double latitude;
double longitude;
LocationManager locationManager;
android.location.LocationListener networkLocationListener;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
networkLocationListener = new android.location.LocationListener() {
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("->", "done.");
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocationListener);
}
...
Also, this is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.doruk.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<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_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/orange"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".ConnectionChangeReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
</application>
</manifest>
Can you see the problem? What you advise at this point? Is there a better way?
Dorukhan Arslan
- You can use GoogleclientAPi, as locationmanager has been
Deprecated
-Using FusedLocationAPi it will automatically discover the provider to find the location.
- https://developer.android.com/google/auth/api-client.html have a look
on this
- Here is one exampleprotected void createLocationRequest() {
LocationRequest mLocation = LocationRequest.create();
GoogleAPiClient mgoogle;
/*enter code here
* Set the update interval
*/
mLocation.setSmallestDisplacement(500); // 2km
mLocation.setInterval(180000);// 3 min
mLocationRequest.setFastestInterval(120000);// 2 min
mLocation.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (mgoogle == null) {
mgoogle = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mgoogle.connect();
}
}
It's a sample and implementing OnConnectionFailedListener,
ConnectionCallbacks, com.google.android.gms.location.LocationListener above 3 interfaces you can get the continuos Location.
getLastLocation Method Of LocationRequest Class will give you Location.
onLocationChanged Method will give you Your desired output.
You can use IP address of user for getting approx location.
I want to run demo Google map but it is not showing map. Here is my code.I have checked API key it is correct
package com.example.googlemaps;
import com.google.android.maps.MapActivity;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends MapActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return true;
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.googlemaps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-library android:name="com.google.android.maps" />
<activity
android:name="com.androidhive.googlemaps.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
layout xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:apiKey="#string/Api_key"
/>
This is old way for getting map. Google has updated it now.
use
<fragment
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
in your xml layout.
provide your API key in manifest file as
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="YOUR-API-KEY" />
in your application tag.
also don't extend MapActivity. Instead extend normal Activity
then write below code in your OnCreate
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) {
// Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
// Google Play Services are available
// Getting reference to the SupportMapFragment
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
// Getting Google Map
myMap = fragment.getMap();
// Enabling MyLocation in Google Map
myMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service
// LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
also add following code on OnResume
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
} else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
that's it.
All the best!
Version 1 googlemaps officially depricated.so just use version 2 and add google-play-services libs.surely it will help to get googlemap.
public class MainActivity extends FragmentActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap(); } }
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE"
/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.vogella.android.locationapi.maps.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDeYchyvOUsy_I68_RMtfsI5QVkqweIp9w" />
</application>
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
refer this link,http://www.vogella.com/articles/AndroidGoogleMaps/article.html
I am very new to Android development. So forgive this repetitive question. I've tried many of the solutions on this but none seem to work quite right for me...They all crash on emulator and on my phone.
I'm working on an App and just want to get my GPS Location and then sets the TextView called 'big' to the location's value.
Heres the code. (I have the import statements and everything in my code..I just didnt copy them over
GPSActivity //the activity that starts. the textview R.id.big does exist
public class GPSActivity extends Activity{
private LocationManager manager = null;
private MyLocationListener listener;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new MyLocationListener(textView);
textView = (TextView) findViewById(R.id.big);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener(textView);
manager.requestLocationUpdates(LocationManager
.GPS_PROVIDER, 5000, 10,listener);
}
}
I implemented my own LocationListener that changes my TextView...I'm not sure if I'm really allowed to do this....
public class MyLocationListener implements LocationListener
{
TextView textView;
public MyLocationListener(TextView textView)
{
this.textView = textView;
}
#Override
public void onLocationChanged(Location location) {
this.textView.setText(location.toString());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
Lastly my manifest file. I made sure to include the permissions I needed.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mytestapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar" >
<activity
android:name="com.mytestapp.GPSActivity"
android:permission="ACCESS_FINE_LOCATION"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The problem occurs in GPSActivity when I call requestLocationUpdates(). The app crashes if I leave this line in the code. If I comment it out, the TextView 'big' displays like I would expect it to.
edit: I've also tried creating a LocationListener as an inner-class like I've seen a lot of other people do on SO...and I had the same result (app crash)
Add
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
to your manifest.xml file.
for a complete support of Geolocation using GPS or WiFi use:
<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_GPS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
and for the devices that donĀ“t have support for gps use:
<uses-feature
android:name="android.hardware.location.gps"
android:required="false" />
In addition to the ACCESS_FINE_LOCATION permission try adding
ACCESS_GPS
and they should look like this ...
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Here is code of my Android app.
MainActivity.java
public class MainActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("MyTag", "first");
retrieveLocationButton = (Button) findViewById(R.id.button1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
Log.d("MyTag", "Second");
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.d("MyTag", "Third"+location);
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_LONG).show();
Log.d("MyTag", "Fifth");
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Log.d("MyTag", "sixth");
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MainActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MainActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MainActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
BootReceiver.java
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent){
context.startService(new Intent(context,MainActivity.class));
Log.d("kkkkkkkk","bootReceive");
}
}
AndroidMainfest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pragmatic.pragmaticgps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.REBOOT"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MainActivity"></service>
<receiver
android:name=".receiver..MainActivity"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.REBOOT" />
</intent-filter>
</receiver>
<receiver android:name=".BootReceiver">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
I wanted this App to get GPS cordinates i.e. Latitude/Longitude and display it via a toast (which it does.) I also wanted that whenever the mobile is rebooted this App should start automatically and run in background 24x7 but on a real Android mobile when I switch on the Phone, App craches and a Pop up Appears asking to Force Close it. what is wrong in the code ? Sorry for asking the bug directly but I dont know much about Android.
Thank you.
Feels like the bug lies in here:
context.startService(new Intent(context,MainActivity.class));
You can start MainActivity as a Service since it's not a Service, it's an Activity. To start an Activity you should call
context.startActivity(new Intent(context,MainActivity.class))
Also, in this situation it would be better to organize MainActivity as a Service since it's a pretty bad idea to start an Activity directly from a BroadcastReceiver. Hope this helps.