null pointer exception on location change - android

I researched for this Nullpointer Exception. After googling i found most of them were due to null references to the UI elements. But mine does not have any. I just can't get the reason for the null pointer. I directly tested it on my android phone running 2.3.7. And yes, i added the permissions in the manifest file.
package com.GodTM.projectshoppers;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
public class HomeActivity extends Activity {
private ImageButton get;
private ImageView quit,settings;
private LocationManager locMan;
public LocationListener LocLis;
public Location currLoc;
private double[] passloc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
get=(ImageButton)findViewById(R.id.homeGetButton);
settings = (ImageView)findViewById(R.id.homeSettingsButton);
quit = (ImageView)findViewById(R.id.homeExitButton);
Criteria crit=new Criteria();
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LocLis = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null){
currLoc.setLatitude(location.getLatitude());
currLoc.setLongitude(location.getLongitude());
}
}
};
//Criteria crit = new Criteria();
if(currLoc !=null){
passloc[0] = currLoc.getLatitude();
passloc[1] = currLoc.getLongitude();
Toast.makeText(getApplicationContext(), "Lat:" + currLoc.getLatitude() + "\nLong:" + currLoc.getLongitude(), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Not Available", Toast.LENGTH_SHORT).show();
}
get.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(currLoc!=null){
Intent i = new Intent(HomeActivity.this, Screen2.class);
i.putExtra("Loc", passloc);
startActivity(i);
}
else{
Toast.makeText(getApplicationContext(), "Location Not Available", Toast.LENGTH_SHORT).show();
}
}
});
settings.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent j = new Intent(this, screen4.class);
// startActivity(j);
}
});
quit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
#Override
public void onResume(){
super.onResume();
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER , 0, 0, LocLis);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}

currLoc is never initalized. Since location and currLoc are both Location you can change
if(location != null){
currLoc.setLatitude(location.getLatitude());
currLoc.setLongitude(location.getLongitude());
}
with
currLoc = location;

You didn't initialize passLoc. And you call getLastKnownLocation without saving the location itself.

Related

Google Map API 2 not showning current location

I am try to showing current location using android google map api 2, I run this on my phone which is wifi enable.
But it always shows Longitude and Latitude 0.0 , 0.0 .
Here is my code
package com.google.map;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.map.R;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.FragmentManager;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener{
private GoogleMap googlemap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isGooglePlay())
{
setContentView(R.layout.activity_main);
setUpMap();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if(item.getItemId() == R.id.action_legalnotices)
{
startActivity(new Intent(this, LegalNoticesActivity.class));
}
return super.onOptionsItemSelected(item);
}
private boolean isGooglePlay()
{
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if(status == ConnectionResult.SUCCESS)
{
return true;
}
else
{
((Dialog)GooglePlayServicesUtil.getErrorDialog(status, this, 10)).show();
Toast.makeText(getApplicationContext(), "Google play is not available.", Toast.LENGTH_LONG).show();
}
return false;
}
#SuppressLint("NewApi") private void setUpMap()
{
if(googlemap == null)
{
googlemap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
if(googlemap != null)
{
// map code
googlemap.setMyLocationEnabled(true);
googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LocationManager lo = (LocationManager) getSystemService(LOCATION_SERVICE);
String provider = lo.getBestProvider(new Criteria(),true);
if(provider == null)
{
onProviderDisabled(provider);
}
else
{
onProviderEnabled(provider);
}
Location loc = lo.getLastKnownLocation(provider);
if(loc != null)
{
onLocationChanged(loc);
}
googlemap.setOnMapLongClickListener(onLongClickMapSettings());
}
}
}
private OnMapLongClickListener onLongClickMapSettings() {
// TODO Auto-generated method stub
return new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng arg0) {
// TODO Auto-generated method stub
Log.i(arg0.toString(),"Long Click");
}
};
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latlng = new LatLng(location.getLatitude(),location.getLongitude());
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
googlemap.moveCamera(CameraUpdateFactory.zoomTo(5));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Location lo = new Location(provider);
LatLng latlng = new LatLng(lo.getLatitude(),lo.getLongitude());
Log.i(latlng.toString(),"Current Location" );
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
googlemap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 5));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Here is the Log cat value of my android application.
05-07 22:16:31.636: I/lat/lng: (0.0,0.0)(17967): Current Location
Move your Log.i(latlng.toString(),"Current Location" ); code to the onLocationChanged-method, you don't have a location yet in onProviderEnabled.
mMap.setMyLocationEnabled(true); // just add one line it wil work.

in gsp even I change latitude and longitude emuletar still show the same location why it reacts like that? and how I correct it?

this my code and it loade normali but when I change latitude and longitude it not show the corresponding location. I use emulatar to test the programe. I change latitude and longitude by using emulator control.
package com.rumes.gspuse;
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 android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class Main extends MapActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapView map=(MapView) findViewById(R.id.map);
map.setBuiltInZoomControls(true);
final MapController controller=map.getController();
LocationManager manager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener listner=new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
controller.setCenter(new GeoPoint((int)location.getLatitude(), (int)location.getLongitude()));
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,listner);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
You need latitudeE6 and longitudeE6, that's why you don't see any difference in map!
if(location != null) // avoid crash (check for null)..
controller.setCenter(new GeoPoint((int)(location.getLatitude() * 1E6), (int)(location.getLongitude() * 1E6)));

Finding current location from background service android

I want to find current location and compare it with some data in my database through a background service activity...but not getting any idea on how to do it...so please give me some advice...this is how I am doing currently
package com.example.alert;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class service extends Service{
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
Toast.makeText(this, "Background Service Created", Toast.LENGTH_LONG).show();
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
}
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
LocationListener ll = new MyLocationListener();
//lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5*60*10000, 0, ll);
lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll);
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
if(loc!=null)
{
double x;
String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
/* cr.moveToFirst();
while(!cr.isAfterLast()) {
al.add(cr.getString(cr.getColumnIndex(dbAdapter.KEY_NAME))); //add the item
cr.moveToNext();
}*/
// lm.addProximityAlert(loc.getLatitude(), loc.getLongitude(), 10009,, intent)
//for loop, alerters retrieving one by one
// x= calcDistance(loc.getLatitude(),loc.getLongitude(),z,y);
// if(x<1){
// Intent myIntent = new Intent(ViewAlerters.this,CallMode.class);
// startActivity(myIntent);
}
}
public void onProviderDisabled(String arg0) {
// 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
}
}
}
Reto Meier (Android Developer Relations) did a whole lot of work in this area, I suggest you check it out.
Blogged here http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html
Sample code here https://code.google.com/p/android-protips-location/

Toast is not working

So i am just trying to get location of user and show it in a toast...but its not working at all...i also tried just to show toast when activity starts but it is not working even at that time
Here's my code
package com.example.alert;
import com.example.alert.CurrentLocation.MyLocationListener;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class ViewAlerters extends Activity{
private Button addButton;
private Button removeButton;
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.view_alerters);
Toast.makeText( ViewAlerters.this,"Hello",Toast.LENGTH_SHORT).show();
LocationListener ll=new MyLocationListener();
//lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5*60*10000, 0, ll);
lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll);
setUpViews();
}
private void setUpViews() {
Toast.makeText( getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
addButton = (Button) findViewById(R.id.add_button);
//alerterText = (TextView) findViewById(R.id.alert_list_text);
removeButton = (Button)findViewById(R.id.remove_button);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ViewAlerters.this,AddAlerter.class);
startActivity(intent);
}
});
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
if(loc!=null)
{
double x;
String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
/* cr.moveToFirst();
while(!cr.isAfterLast()) {
al.add(cr.getString(cr.getColumnIndex(dbAdapter.KEY_NAME))); //add the item
cr.moveToNext();
}*/
// lm.addProximityAlert(loc.getLatitude(), loc.getLongitude(), 10009,, intent)
//for loop, alerters retrieving one by one
// x= calcDistance(loc.getLatitude(),loc.getLongitude(),z,y);
// if(x<1){
// Intent myIntent = new Intent(ViewAlerters.this,CallMode.class);
// startActivity(myIntent);
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Disabled - #From :Alert Me",Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Enabled - #From :Alert Me",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
public double calcDistance(double latA, double longA, double latB, double longB) {
double theDistance = (Math.sin(Math.toRadians(latA)) * Math.sin(Math.toRadians(latB)) + Math.cos(Math.toRadians(latA)) * Math.cos(Math.toRadians(latB)) * Math.cos(Math.toRadians(longA - longB)));
return new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09*1.6093);
}
}
Don't use getApplicationContext:
Toast.makeText( this,"Hello",Toast.LENGTH_SHORT).show();
Refer to this question about the differences in the Contexts: difference and when to use getApplication(), getApplicationContext(), getBaseContext() and someClass.this
Toast.makeText( ViewAlerters.this,"Hello",Toast.LENGTH_SHORT).show();

application has stopped unexpectedly in android emulator

I am looking for the optimized way to get user's location and I found the sample example here, which was answered by Mr. Fedor on on Jun 30 '10
I did the same way as he explained in his code, the only difference is that I am using the gotLocation callback method of abstract class result. In this method I am tring to show the Provider name as a msg using Toast.makeText. When I run this code, nothing get displayed on my emulator and after few seconds it show the message "Application has stopped unexpectedly android emulator". I increase the time, which was set in the timer1.schedule method, but no luck.
I am just stating development in android platform, so I don't have enough knowledge about the same, so can anybody help me to resolve this issue.
Below is my code
file Name: UserLocation.java
package com.ideafarms.android.mylocation;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class UserLocation{
Timer timer1;
LocationManager locMgr;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
LocationListener locationListenerGps = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
timer1.cancel();
locationResult.gotLocation(location);
locMgr.removeUpdates(this);
locMgr.removeUpdates(locationListenerNetwork);
}
};
LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
timer1.cancel();
locationResult.gotLocation(location);
locMgr.removeUpdates(this);
locMgr.removeUpdates(locationListenerGps);
}
};
public boolean getLocation(Context context, LocationResult result){
// Use LocationResult callback class to pass location value from UserLocation to User code
locationResult = result;
if(locMgr == null){
locMgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Handle exception if provider is not permitted
try{
gps_enabled = locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){
}
try{
network_enabled = locMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){
}
// don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if(network_enabled){
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
}
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
return true;
}
class GetLastLocation extends TimerTask {
#Override
public void run() {
// TODO Auto-generated method stub
locMgr.removeUpdates(locationListenerGps);
locMgr.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled){
gps_loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(network_enabled){
net_loc=locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
// if there are both values use the latest one
if(gps_loc!=null && net_loc!= null){
if(gps_loc.getTime()>net_loc.getTime()){
locationResult.gotLocation(gps_loc);
}else{
locationResult.gotLocation(net_loc);
}
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
and
package com.ideafarms.android.mylocation;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.ideafarms.android.mylocation.UserLocation.LocationResult;
public class MyLocation extends Activity {
/** Called when the activity is first created. */
TextView myLoc ;
public LocationResult locResult = new LocationResult(){
#Override
*public void gotLocation(Location location) {
// TODO Auto-generated method stub
Toast msg = Toast.makeText(MyLocation.this, location.getProvider(), Toast.LENGTH_LONG);
//msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}*
};
boolean loc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
UserLocation usrLocation = new UserLocation();
myLoc = (TextView)findViewById(R.id.myLocation);
loc = usrLocation.getLocation(this, locResult);
}
}
I have marked the code in italic where I am having problem.
Thanks
Take a look here: http://developer.android.com/guide/developing/tools/emulator.html
You need to emulate an gps device in order to get location data from the emulator.

Categories

Resources