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();
Related
I am trying to create an android program to get the location
but unfortunately its throwing the exception as unfortunately APP is stopped
Can you suggest me please .code is the following
package com.example.ngo;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity
implements OnClickListener {
private LocationManager locationMangaer=null;
private LocationListener locationListener=null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to"+
" see the changes in coordinates."+"\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager
.GPS_PROVIDER, 5000, 10,locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----Method to Check GPS is enable or disable ----- */
#SuppressLint("NewApi") private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext()
.getContentResolver();
boolean gpsStatus = Settings.Secure
.isLocationProviderEnabled(contentResolver,
LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#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
}
}
}
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.
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)));
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/
i am trying google maps api on my android phone via following code. My app locating my phone and working great but gps notification icon not blinking. How can i blink gps icon when locating my phone.
Thanks For Replies.
Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
And The Code :
import java.util.List;
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.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
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.provider.Settings;
import android.widget.EditText;
import android.widget.Toast;
public class main extends MapActivity {
MapController mControl;
GeoPoint geoP;
MapView mapV;
MyLocationOverlay compass;
EditText etext;
String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etext = (EditText) findViewById(R.id.latLong);
mapV = (MapView) findViewById(R.id.mapView);
mapV.displayZoomControls(true);
mapV.setBuiltInZoomControls(true);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean enable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enable) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
Criteria criteria = new Criteria();
//criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Double lat = location.getLatitude() * 1E6;
Double longi = location.getLongitude() * 1E6;
geoP = new GeoPoint(lat.intValue(), longi.intValue());
List<Overlay> mapOverlays = mapV.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
compass = new MyLocationOverlay(this, mapV);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(geoP, "Hola, Mundo!","I'm in Mexico City!");
itemizedoverlay.addOverlay(overlayitem);
mapV.getOverlays().add(compass);
mapOverlays.add(itemizedoverlay);
mControl = mapV.getController();
mControl.animateTo(geoP);
mControl.setZoom(5);
mControl.setCenter(geoP);
locationManager.requestLocationUpdates(provider, 0, 0,
new LocationListener() {
public void onStatusChanged(String provider, int status,
Bundle extras) {
if (status == LocationProvider.AVAILABLE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.AVAILABLE",
Toast.LENGTH_SHORT).show();
} else if (status == LocationProvider.TEMPORARILY_UNAVAILABLE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.TEMPORARILY_UNAVAILABLE",
Toast.LENGTH_SHORT).show();
} else if (status == LocationProvider.OUT_OF_SERVICE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.OUT_OF_SERVICE",
Toast.LENGTH_SHORT).show();
}
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(),
"Location Changed", Toast.LENGTH_SHORT).show();
}
});
//etext.setText(String.valueOf(lat) + "," + String.valueOf(longi));
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
compass.disableCompass();
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
compass.enableCompass();
}
protected boolean isRouteDisplayed() {
return false;
}
t0mm13b, working on my handset but GPS notification icon not blinking. Virtual Device means Emulator. I solved problem.
Code :
package com.yunusoksuz.gmapstest;
import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class YnsmapsActivity extends Activity implements LocationListener {
/** Called when the activity is first created. */
private LocationManager locationManager;
private Location location;
private String provider;
private Double lat, longi;
private Criteria criteria;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv1);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
public void onLocationChanged(Location location) {
Toast.makeText(
this,
"Lat : " + location.getLatitude() + " LONG : "
+ location.getLongitude(), Toast.LENGTH_SHORT).show();
tv.setText("Lat : " + location.getLatitude() + " LONG : "
+ location.getLongitude());
}
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
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
}
}
Now gps notification blinking.