I have created a custom layout for my alertdiaog : alertdialog.setView(inflater.inflate(R.layout.custom_gps,null));
I want to replace the default Ok and cancel buttons with my buttons, since it's not possible to use findViewById in a service class, I wanted to know if there is a workaround to handle the clicks on my custom buttons.
I took a look at some old questions but i did not find (yet) any trick to make that happen. Can you guys help ?
I have another workaround on my mind, and it is to extend Activity instead of Service (whice will make findViewByID available, but what changes do i have to apply on my class to start a Service from an activity ?
Any help or indication is welcome !
public class GPSTracker extends Service implements LocationListener {
private final Context mcontext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude,longitude;
private Button ok_button,cancel_button;
//the minimum distance to change updates in meters :
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
//the minimum time between updates (milliseconds) :
private static final long MIN_TIME_BETWEEN_UPDATE = 600000; // 10min
protected LocationManager locationmanager;
public GPSTracker (Context context){
this.mcontext = context;
getLocation();
}
public Location getLocation(){
try {
locationmanager = (LocationManager) mcontext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationmanager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationmanager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationmanager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BETWEEN_UPDATE,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationmanager != null) {
location = locationmanager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationmanager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BETWEEN_UPDATE,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationmanager != null) {
location = locationmanager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/*
function to get latitude :
*/
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
/*
function to get longitude :
*/
public double getLongitude(){
if (location != null){
longitude = location.getLongitude();
}
return longitude;
}
/**
*
* function to check if gps is enabled
* #return boolean
*
*/
public boolean canGetlocation(){
return this.canGetLocation;
}
/*
function to show settings alert.
*/
public void showSettingsAlert(){
AlertDialog.Builder alertdialog = new AlertDialog.Builder(mcontext);
LayoutInflater inflater = LayoutInflater.from(mcontext);
inflater = (LayoutInflater)mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
alertdialog.setView(inflater.inflate(R.layout.custom_gps,null));
/*alertdialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mcontext.startActivity(intent);
}
});
// on pressing cancel button
/* alertdialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
*/
alertdialog.show();
}
public void stopUsingGPS(){
if(locationmanager != null){
locationmanager.removeUpdates(GPSTracker.this);
}
}
}
You can create a simple class in which you have a method which show the dialog and you need to call that method very simple.ex-
public class AlertDialog {
public static void showdialog(Context context) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Android custom dialog example!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
now in your service you can directly call this method by passing the context.
like-
AlertDialog.showdialog(context);
Related
The GPS class and MainActivity both worked fine until we tried to add a second page. We've tried using intents and fragments and have spent way too many hours/days on trying to figure this out.
We keep getting NullPointerExceptions for either the onClickListener() in MainActivity and when updating any textviews from the GPS class. We know it has something to do with how the fragments work but we're not sure how to fix this.
This is our MainActivity class
public class MainActivity extends ActionBarActivity {
// Get buttons and text fields
public Button showLocation;
// TextViews
public static TextView showLatitude;
public static TextView showLongitude;
public static TextView showDistance;
// GPS class
GPS gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
showLocation = (Button) findViewById(R.id.btnShowLocation);
showLatitude = (TextView) findViewById(R.id.txtLatitude);
showLongitude = (TextView) findViewById(R.id.txtLongitude);
showDistance = (TextView) findViewById(R.id.txtDisplayDistance);
// Create gps
gps = new GPS(MainActivity.this);
// show location button click event
showLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
gps.setTotalDistance(0.0);
}
});//END LISTENER
}// END ONCREATE
public void nextPage(View view) {
// In response to button
Intent intent = new Intent(this, ResourcePage.class);
// Set activity intent
startActivity(intent);
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
And this is the GPS class
public class GPS extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS/Network/Location status
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
// Location Class
Location location;
// Latitude and longitude save points
private double startLatitude = 0;
private double endLatitude = 1.0;
private double startLongitude = 0;
private double endLongitude = 1.0;
private double totalDistance = 0;
// Results Array
private float[] results = new float[1];
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_FOR_UPDATES = 10; // meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BETWEEN_UPDATES = 1000; // 1 second
// Location Manager
protected LocationManager locationManager;
// Interface
public GPS(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Checking Flags
if (!isGPSEnabled && !isNetworkEnabled) {
// ^no network provider is enabled do nothing/go on^
}
else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BETWEEN_UPDATES, MIN_DISTANCE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
startLatitude = location.getLatitude();
startLongitude = location.getLongitude();
} //END OF LAST IF BLOCK
} //END OF SECOND IF BLOCK
} //END OF "FIRST" IF BLOCK
// if GPS Enabled get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BETWEEN_UPDATES, MIN_DISTANCE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
startLatitude = location.getLatitude();
startLongitude = location.getLongitude();
}
}
}
}
}//END OF ELSE BLOCK
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
// Call to remove updates from listener
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPS.this);
}
}
public double getLatitude(){
if(location != null){
startLatitude = location.getLatitude();
}
// Return latitude
return startLatitude;
}
public double getLongitude(){
if(location != null){
startLongitude = location.getLongitude();
}
// Return longitude
return startLongitude;
}
//Function to check GPS/wifi are enabled
public boolean canGetLocation() {
//return boolean
return this.canGetLocation;
}
// Function to show settings alert dialog if gps is off
public void showSettingsAlert(){
// On pressing Settings button will launch Settings Options
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// Settings button listener/press
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
// Called from listener on gps change of X
#Override
public void onLocationChanged(Location location) {
//Display Latitude and Longitude
if(location != null){
startLatitude = location.getLatitude();
startLongitude = location.getLongitude();
MainActivity.showLatitude.setText(String.valueOf(startLatitude));
MainActivity.showLongitude.setText(String.valueOf(startLongitude));
}
// Get distance between
Location.distanceBetween(startLatitude, startLongitude, endLatitude,endLongitude, results);
// Convert to miles Add distance to total
totalDistance = totalDistance + results[0] * 0.000621371192;
// Display the total
MainActivity.showDistance.setText(String.format("%.2f", totalDistance));
// Move old values to End locations
endLatitude = startLatitude;
endLongitude = startLongitude;
}
// Function to clear total distance (Testing)
public void setTotalDistance(Double savedData){
totalDistance = savedData;
MainActivity.showDistance.setText(String.valueOf(totalDistance));
}
public double getTotalDistance(){
return totalDistance;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
For the layout files we have activity_main.xml which is empty, fragment_main.xml which has all our text fields and buttons and then fragment_resource.xml which has nothing but a textview so we knew things would appear on it.
If you say all your views belong to the fragment then initialize views in fragment not in Activity.
The Activity layout does not have the views and findViewById looks for a view in the current inflated layout. So the initialization fails leading to NullPointerException when you use the view objects.
TextView showLatitude;
TextView showLongitude;
TextView showDistance;
GPS gps;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
showLocation = (Button)rootView.findViewById(R.id.btnShowLocation);
showLatitude = (TextView) rootView.findViewById(R.id.txtLatitude);
showLongitude = (TextView) rootView.findViewById(R.id.txtLongitude);
showDistance = (TextView) rootView.findViewById(R.id.txtDisplayDistance);
gps = new GPS(getActivity()); // wrong bind the service to the activtiy
showLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
gps.setTotalDistance(0.0); // remove this
}
});
return rootView;
}
Also you have
public class GPS extends Service
Its a Service class. You need to bind the service to Activity. But you dogps = new GPS(getActivity());
Replace this:
setContentView(R.layout.activity_main);
By:
setContentView(R.layout.fragment_main);
You have the problem in this method
public void setTotalDistance(Double savedData){
totalDistance = savedData;
MainActivity.showDistance.setText(String.valueOf(totalDistance));
}
You can't just call the MainActivity that way it will return NULL
Pointer exception for showDistance Variable.Because its not a static
class.So you want to do like this.
public void setTotalDistance(Double savedData){
totalDistance = savedData;
((this.mContext)MainActivity).showDistance.setText(String.valueOf(totalDistance));
}
Surely this will make some sense.
can anyone guide on how to check internet connection setting with condition? I need something similar to this set of code.
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
Below is my code and I would like to replace GPS checking into internet connection checking.
public class MainActivity extends FragmentActivity implements LocationListener, LocationSource{
private GoogleMap map;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locationManager != null)
{
boolean gpsIsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkIsEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(gpsIsEnabled)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000L, 10F, this);
else if(networkIsEnabled)
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000L, 10F, this);
}
setUpMapIfNeeded();
}
//after user install/update Google Play Service, user might return to this activity
//to stop or resume the activity, onPause and onResume is needed
#Override
public void onPause()
{
if(locationManager != null)
{
locationManager.removeUpdates(this);
}
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
setUpMapIfNeeded();
if(locationManager != null)
{
map.setMyLocationEnabled(true); //detect current location
}
}
you can use something like this..
public boolean isOnline(final Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
Builder dialogb = new AlertDialog.Builder(context);
if (netInfo != null && netInfo.isConnected()) {
return true;
}
dialogb.setTitle("No Internet.. :(");
dialogb.setMessage("We need internet to work. Kindly switch it on.");
dialogb.setPositiveButton("Turn on", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_WIRELESS_SETTINGS);
context.startActivity(myIntent);
//get gps
}
});
dialogb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialogb.show();
return false;
}
i have a main activity whit navigation drawer (whit frame layout)
private void selectItem(int position) {
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
switch (position) {
case 0:
MapFragment mapFragment= new MapFragment();
/**
// Creating a Bundle object
Bundle data = new Bundle();
// Setting the index of the currently selected item of mDrawerList
data.putInt("position", position);
// Setting the position to the fragment
mapFragment.setArguments(data);
// Creating a fragment transaction
ft = fragmentManager.beginTransaction();
*/
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, mapFragment);
ft.commit();
break;
case 1:
GpsDatiFragment gpsFragment= new GpsDatiFragment();
ft.replace(R.id.content_frame,gpsFragment);
ft.commit();
break;
case 2:
AltroFragment altroFragment= new AltroFragment();
ft.replace(R.id.content_frame, altroFragment);
ft.commit();
break;
case 3:
finish();
default:
break;
}
here all ok, In One fragment there is the map and in another there is a details of gps and location (altitude, latitude, time to fix ecc)....then i have create a service that implement location listener and i'll want that it send info of onlocationchanded and gpsstatus to fragment 1 (map whit location) and 2 (altitude speed latitude time to fix) but i dont know how to do.....how sync the info for both fragment??? thanks
edit:
this is my service
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
String provider;
Criteria criteria;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 400; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
//locationManager.addGpsStatusListener(this);
//Criteria criteria= new Criteria();
//criteria.setAccuracy(Criteria.ACCURACY_FINE);
//provider= locationManager.getBestProvider(criteria, false);
//location= locationManager.getLastKnownLocation(provider);
//locationManager.requestLocationUpdates(provider, 400, 1, this);
if (isGPSEnabled){
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}else{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
}else if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
/*
public boolean canGetLocation() {
return this.canGetLocation;
}*/
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
//getLocation();
}
#Override
public void onProviderDisabled(String provider) {
getLocation();
//locationManager.requestLocationUpdates(locationManager.NETWORK_PROVIDER, 400, 1, this);
}
#Override
public void onProviderEnabled(String provider) {
getLocation();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
and this is my fragment for map:
public class MapFragment extends SupportMapFragment {
GoogleMap mapView;
Intent intent;
// GPSTracker class
GPSTracker gps;
Location location ;
#Override
public void onCreate(Bundle arg0) {
super.onCreate(arg0);
// create class object
getActivity().startService(new Intent(getActivity(), GPSTracker.class));
}
#Override
public View onCreateView(LayoutInflater mInflater, ViewGroup arg1,
Bundle arg2) {
return super.onCreateView(mInflater, arg1, arg2);
}
#Override
public void onInflate(Activity arg0, AttributeSet arg1, Bundle arg2) {
super.onInflate(arg0, arg1, arg2);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
gps = new GPSTracker(getActivity());
// check if GPS enabled
//location = gps.getLocation();
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
mapView = getMap();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.draggable(true);
markerOptions.position(new LatLng(latitude, longitude));
markerOptions.icon(BitmapDescriptorFactory.defaultMarker());
mapView.addMarker(markerOptions);
// \n is for new line
Context context = getActivity().getApplicationContext();
Toast.makeText(context, "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
// gps.showSettingsAlert();
}
}
this is fragment for deatils:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container, false);
longitudeField= (TextView) rootView.findViewById(R.id.textView4);
altitudine= (TextView) rootView.findViewById(R.id.textView6);
precisione= (TextView) rootView.findViewById(R.id.textView8);
speed= (TextView) rootView.findViewById(R.id.textView10);
timeFix= (TextView) rootView.findViewById(R.id.textView12);
satFixed= (TextView) rootView.findViewById(R.id.textView14);
elencoSat= (TextView) rootView.findViewById(R.id.textView15);
latitudeField= (TextView) rootView.findViewById(R.id.textView2);
gps= new GPSTracker(getActivity());
update();
return rootView;
}
/* Request updates at startup */
#Override
public void onResume() {
super.onResume();
//update();
//locationManager.requestLocationUpdates(provider, 400, 1, this);
}
public void update(){
location = gps.getLocation();
lat= location.getLatitude();
lng= location.getLongitude();
pre= (int) location.getAccuracy();
vel= location.getSpeed();
latitudeField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
//altitudine.setText(String.valueOf(alt)+" metri");
precisione.setText(String.valueOf(pre)+" metri");
speed.setText(String.valueOf(vel)+" km/h");
}
}
You are creating a new fragment every time selectItem() method is called. Instead of doing that you should rather use method findFragmentByTag() to obtain fragment you created earlier and create new one only if there is no such fragment.
Then you can simply store in your activity the variable for each fragment and pass required information to selected fragments.
the method startSightManagement() is called twice throug my program, so i have two location Manager objects.
private void startSightManagement() {
String locationService = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(locationService);
// Get the GPS provider and request location updates
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 2000, 2, this);
// Obtain last known location and update the UI accordingly
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
sightManager = new SightManager(this);
// Set up the first sight
setSight();
}
my onPause() Activity with removeUpdates(this)-->This only removes one instance, how do i remove the other one??
protected void onPause() {
myLocationOverlay.disableMyLocation();
locationManager.removeUpdates(this);
locationManager=null;
// TODO Auto-generated method stub
super.onPause();
//Shutdown TTS everytime when activity is paused(Tolga)
if (mTts != null) {
mTts.stop();
}
// Unregister the proximity intent receiver. This also prevents the app from
// leaking when it is closed.
if (proximityIntentReceiver!=null) {
unregisterReceiver(proximityIntentReceiver);
}
}
Second problem is: app crashes when gps isnt enabled on start and i click yes when asked if gps should be enabled. when i remove these two lines everything works fine:
locationManager.removeUpdates(this);
locationManager=null;
here is the buildAlert method if gps isnt enabled on start:
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("GPS ist deaktiviert. Standorteinstellungen anzeigen?")
.setCancelable(false)
.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), ENABLE_GPS_SUB);
}
})
.setNegativeButton("Nein", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
finish();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
I have a problem with setting GPS service . I want to check if GPS is enable . If it is disable , it will display a dialog to user turn it on . The problem is it not wait for user enable GPS and get location .
I have a class
public class GPSTracker extends Service implements LocationListener{
private final Context mContext;
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_FOR_UPDATE = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATE = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context ctx) {
this.mContext = ctx;
getLocation();
}
public Location getLocation()
{
try {
locationManager = (LocationManager)mContext.getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnable)
{
showSettingsGPSAlert();
}
else if(!isNetworkEnable)
{
showSettingsNetWorkAlert();
}
else
{
this.canGetLocation = true;
if(isNetworkEnable)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATE,
MIN_DISTANCE_FOR_UPDATE, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnable) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATE,
MIN_DISTANCE_FOR_UPDATE, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}catch (Exception ex)
{
Log.e("<<Location Error>>",ex.getMessage());
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public boolean canGetGPS() {
return this.isGPSEnable;
}
public boolean canGetNetwork() {
return this.isNetworkEnable;
}
public void showSettingsGPSAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startService(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public void showSettingsNetWorkAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("NetWork is settings");
// Setting Dialog Message
alertDialog.setMessage("NetWork is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
And I have class to use it
public class RestaurantListFragment extends ListFragment {
private ArrayList<Restaurant> restaurants;
private SQLDataHelper dataHelper;
private GPSTracker gps;
private double UserLatitude;
private double UserLongitude;
private ProgressDialog progressBar;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.restaurant_list, null);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
gps = new GPSTracker(getActivity());
UserLatitude = gps.getLatitude();
UserLongitude = gps.getLongitude();
Toast.makeText(getActivity(),UserLatitude + "|" + UserLongitude,Toast.LENGTH_SHORT).show();
dataHelper = new SQLDataHelper(getActivity(), "restaurantDB");
restaurants = new ArrayList<Restaurant>();
dataHelper.openDB();
Cursor cursor = dataHelper.query("Restaurant", new String[]{"Id", "ResName", "Logo", "Address", "Latitude", "Longitude"}, null
, null, null, null, null);
if (cursor.moveToFirst()) {
do {
Restaurant restaurant = new Restaurant();
restaurant.setId(cursor.getInt(0));
restaurant.setResName(cursor.getString(1));
restaurant.setLogo(cursor.getString(2));
restaurant.setAddress(cursor.getString(3));
restaurants.add(restaurant);
} while (cursor.moveToNext());
}
//Collections.sort(restaurants);
RestaurantAdapter restaurantAdapter = new RestaurantAdapter(getActivity(),restaurants);
setListAdapter(restaurantAdapter);
}
}
It works fine when GPS is enable . I want the user can turn it on first . After that it show user location . Then it can query database and setListAdapter . Thanks for any suggestion .