Hi am running with an issue. I have a gps checking function on my splash screen where after checking my gps connectivity if its state is null it shows an alert.I want to destroy and restart my application after the button click of alert box. Kindly help. here is my code
Geolocationfinder class
package com.driverapp.inis.zuber;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
public class GeoLocationFinder {
private static final String TAG = "GeoLocationFinder";
Timer locationTimer;
LocationManager locationManager;
private static final int min_update_time = 3000; // in msec
private static final int min_distance_for_update = 10; // in meters
LocationResult locationResult;
boolean gps_enabled = Boolean.FALSE;
boolean network_enabled = Boolean.FALSE;
private AlertDialogManager alert;
Context ctx;
public boolean getLocation(Context ctx, LocationResult result) {
this.ctx = ctx;
locationResult = result;
if (locationManager == null) {
locationManager = (LocationManager) ctx
.getSystemService(Context.LOCATION_SERVICE);
}
try {
gps_enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception e) {
/* alert = new AlertDialogManager();
alert.showAlertDialog(ctx, "Error", "GPS enabled exception:", false);*/
Log.d(TAG, "GPS enabled exception: " + e.getMessage());
}
try {
network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception e) {
Log.d(TAG, "Network enabled exception: " + e.getMessage());
}
if (!gps_enabled && !network_enabled) {
alert = new AlertDialogManager();
alert.showAlertDialog(ctx, "Error", "Please Check Your GPS Connection and Try Again", false);
return Boolean.FALSE;
}
if (gps_enabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, min_update_time,
min_distance_for_update, locationListenerGps);
}
if (network_enabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, min_update_time,
min_distance_for_update, locationListenerNetwork);
}
locationTimer = new Timer();
locationTimer.schedule(new GetLastLocation(), 2000);
return Boolean.TRUE;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
locationTimer.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerGps);
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "GPS provider disabled" + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "GPS provider enabled" + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "GPS status changed");
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
locationTimer.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerNetwork);
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "Network provider disabled. " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "Network provider enabled. " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "Network status changed.");
}
};
private class GetLastLocation extends TimerTask {
#Override
public void run() {
locationManager.removeUpdates(locationListenerGps);
locationManager.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled) {
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if (network_enabled) {
net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
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;
}
else {
locationResult.gotLocation(null);
}
}
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}
Splashscreen class
package com.driverapp.inis.zuber;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import Connectivity_manager.Internet_CheckingActivity;
public class Splashscreen extends Activity {
private static final String TAG = "SplashScreenActivity";
private Location newLocation = null;
private AlertDialogManager alert;
private Internet_CheckingActivity chckInternt;
private GeoLocationFinder geoLocationFinder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
alert = new AlertDialogManager();
chckInternt = new Internet_CheckingActivity(this);
}
#Override
protected void onResume() {
super.onResume();
// setupLocation();
if (chckInternt.isNetworkAvailable() == true) {
setupLocation();
}
else
{
alert.showAlertDialog(Splashscreen.this, "Error", "Please Check Your Internet Connection", false);
}
}
/** Method for checking the current lat log values. */
private void setupLocation() {
GeoLocationFinder.LocationResult locationResult = new GeoLocationFinder.LocationResult() {
#Override
public void gotLocation(Location location) {
if (location != null) {
newLocation = new Location(location);
newLocation.set(location);
Log.d(TAG,
"Got coordinates, congratulations. Longitude = "
+ newLocation.getLongitude() + " Latitude = "
+ newLocation.getLatitude());
Intent i = new Intent(Splashscreen.this, LoginActivity.class);
startActivity(i);
finish();
} else{
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
alert.showAlertDialog(Splashscreen.this, "Check Your GPS", "Restart your Application", false);
}
});
}
}
};
geoLocationFinder = new GeoLocationFinder();
geoLocationFinder.getLocation(this,locationResult);
}
}
AlertDialogManager class
package com.driverapp.inis.zuber;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.ContextThemeWrapper;
public class AlertDialogManager {
/**
* Function to display simple Alert Dialog
* #param context - application context
* #param title - alert dialog title
* #param message - alert message
* #param status - success/failure (used to set icon)
* - pass null if you don't want icon
* */
public int setOk = 0;
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
// AlertDialog alertDialog = new AlertDialog.Builder(context).create();
AlertDialog.Builder alertDialog= new AlertDialog.Builder(new ContextThemeWrapper(context,R.style.AlertDialogCustom));
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.setCancelable(Boolean.FALSE);
alertDialog.show();
}
/*Aler used for the delete in sheet details*/
public void showAlertDialogDelete(final Context context, String title, String message,
Boolean status) {
// AlertDialog alertDialog = new AlertDialog.Builder(context).create();
AlertDialog.Builder alertDialog= new AlertDialog.Builder(new ContextThemeWrapper(context,R.style.AlertDialogCustom));
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent(context, Splashscreen.class);
context.startActivity(in);
}
});
// Showing Alert Message
alertDialog.setCancelable(Boolean.FALSE);
alertDialog.show();
}
}
Add the following code in OnClick() method of the Positive buton:
Intent intent = new Intent(context, Splashscreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
It will clear the activity stack of your application and launch Splashscreen activity.
Related
I am new to Android Studio and firebase. Making an android app for my final year project. I want to save the location of the user under the username under the BusinessOwner field. I want to save the location of the user when signing in. Your help will be really appreciated
I have my firebase database like this now
I want it to be like this
BusinessOwnerRegister.java
package com.example.android.onroadsupport;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class BusinessOwnerRegister extends AppCompatActivity {
//Variables
TextInputLayout regName, regUsername, regEmail, regPhoneNo, regPassword,regFullAddress,regLandmark,regPinCode,regVoterID,regServiceType;
Button regBtn;
FirebaseDatabase rootNode;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_owner_register);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Hooks to all xml elements in activity_user_register.xml
regName = findViewById(R.id.reg_name);
regUsername = findViewById(R.id.reg_username);
regEmail = findViewById(R.id.reg_email);
regPhoneNo = findViewById(R.id.reg_phoneNumber);
regPassword = findViewById(R.id.reg_password);
regBtn = findViewById(R.id.reg_btn);
regFullAddress = findViewById(R.id.reg_address);
regLandmark = findViewById(R.id.reg_landmark);
regPinCode = findViewById(R.id.reg_pinCode);
regVoterID = findViewById(R.id.reg_voterID);
regServiceType = findViewById(R.id.reg_serviceType);
}
private Boolean validateName() {
String val = regName.getEditText().getText().toString();
if (val.isEmpty()) {
regName.setError("Field cannot be empty");
return false;
} else {
regName.setError(null);
regName.setErrorEnabled(false);
return true;
}
}
private Boolean validateUsername() {
String val = regUsername.getEditText().getText().toString();
String noWhiteSpace = "\\A\\w{4,20}\\z";
if (val.isEmpty()) {
regUsername.setError("Field cannot be empty");
return false;
} else if (val.length() >= 15) {
regUsername.setError("Username too long");
return false;
} else if (!val.matches(noWhiteSpace)) {
regUsername.setError("White Spaces are not allowed");
return false;
} else {
regUsername.setError(null);
regUsername.setErrorEnabled(false);
return true;
}
}
private Boolean validateEmail() {
String val = regEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
regEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
regEmail.setError("Invalid email address");
return false;
} else {
regEmail.setError(null);
regEmail.setErrorEnabled(false);
return true;
}
}
private Boolean validatePhoneNo() {
String val = regPhoneNo.getEditText().getText().toString();
if (val.isEmpty()) {
regPhoneNo.setError("Field cannot be empty");
return false;
} else {
regPhoneNo.setError(null);
regPhoneNo.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = regPassword.getEditText().getText().toString();
String passwordVal = "^" +
//"(?=.*[0-9])" + //at least 1 digit
//"(?=.*[a-z])" + //at least 1 lower case letter
//"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white spaces
".{4,}" + //at least 4 characters
"$";
if (val.isEmpty()) {
regPassword.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
regPassword.setError("Password is too weak");
return false;
} else {
regPassword.setError(null);
regPassword.setErrorEnabled(false);
return true;
}
}
private Boolean validateFullAddress() {
String val = regFullAddress.getEditText().getText().toString();
if (val.isEmpty()) {
regFullAddress.setError("Field cannot be empty");
return false;
} else {
regFullAddress.setError(null);
regFullAddress.setErrorEnabled(false);
return true;
}
}
private Boolean validateLandmark() {
String val = regLandmark.getEditText().getText().toString();
if (val.isEmpty()) {
regLandmark.setError("Field cannot be empty");
return false;
} else {
regLandmark.setError(null);
regLandmark.setErrorEnabled(false);
return true;
}
}
private Boolean validatePinCode() {
String val = regPinCode.getEditText().getText().toString();
if (val.isEmpty()) {
regPinCode.setError("Field cannot be empty");
return false;
} else {
regPinCode.setError(null);
regPinCode.setErrorEnabled(false);
return true;
}
}
private Boolean validateVoterID() {
String val = regVoterID.getEditText().getText().toString();
if (val.isEmpty()) {
regVoterID.setError("Field cannot be empty");
return false;
} else {
regVoterID.setError(null);
regVoterID.setErrorEnabled(false);
return true;
}
}
private Boolean validateServiceType() {
String val = regServiceType.getEditText().getText().toString();
if (val.isEmpty()) {
regServiceType.setError("Field cannot be empty");
return false;
} else {
regServiceType.setError(null);
regServiceType.setErrorEnabled(false);
return true;
}
}
//This function will execute when user click on Sign up Button
public void registerBusinessOwner(View view) {
//Save data in firebase on button click
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("BusinessOwners");
if (!validateName() | !validateUsername() | !validateEmail() | !validatePhoneNo() | !validatePassword() |
!validateFullAddress() | !validateLandmark() | !validatePinCode() | !validateVoterID() | !validateServiceType()) {
return;
}
//Get all the values in Strings
String name = regName.getEditText().getText().toString();
String username = regUsername.getEditText().getText().toString();
String email = regEmail.getEditText().getText().toString();
String phoneNo = regPhoneNo.getEditText().getText().toString();
String password = regPassword.getEditText().getText().toString();
String fullAddress = regFullAddress.getEditText().getText().toString();
String landmark = regLandmark.getEditText().getText().toString();
String pinCode = regPinCode.getEditText().getText().toString();
String voterID = regVoterID.getEditText().getText().toString();
String serviceType = regServiceType.getEditText().getText().toString();
//Storing data in Firebase
MechanicHelperClass mechanicHelperClass = new MechanicHelperClass(name, username, email, phoneNo, password, fullAddress, landmark, pinCode, voterID, serviceType);
//Adding multiple users
//Adding username as unique ID
reference.child(username).setValue(mechanicHelperClass);
Toast.makeText(this, "Your Account has been Created Successfully!", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Add Your Location", Toast.LENGTH_SHORT).show();
//Calling Login screen after Sign up completed
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(intent);
finish();
}
}
MapsActivity.java
package com.example.android.onroadsupport;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.media.audiofx.BassBoost;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.example.android.onroadsupport.databinding.ActivityMapsBinding;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.FirebaseDatabase;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
Button callLogin;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;
private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private long UPDATE_INTERVAL = 2000;
private long FASTEST_INTERVAL = 5000;
private LocationManager locationManager;
private LatLng latLng;
private boolean isPermission;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
//Call login from map
callLogin = findViewById(R.id.callLoginFromMap);
callLogin.setOnClickListener(v -> {
Intent intent = new Intent(MapsActivity.this, BusinessOwnerLogin.class);
startActivity(intent);
});
if (requestSinglePermission()) {
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationManager =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
checkLocation();
}
}
private boolean checkLocation() {
if (!isLocationEnabled()){
showAlert();
}
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your location setting is set to off \n Please enable location to" + "use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean requestSinglePermission() {
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
isPermission = true;
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
//Check for permanent denial of permission
if (response.isPermanentlyDenied()) {
isPermission = false;
}
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
}
}).check();
return isPermission;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (latLng!=null){
mMap.addMarker(new MarkerOptions().position(latLng).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,14f));
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation == null){
startLocationUpdates();
}
else{
Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
private void startLocationUpdates() {
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL).setFastestInterval(FASTEST_INTERVAL);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient
,mLocationRequest,this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(#NonNull Location location) {
String msg = "Updated Location : " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
LocationHelper locationHelper = new LocationHelper(
location.getLongitude(),
location.getLatitude()
);
FirebaseDatabase.getInstance().getReference("BusinessOwners").child("Current Location")
.setValue(locationHelper).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(MapsActivity.this, "Location Saved", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MapsActivity.this, "Location Not Saved", Toast.LENGTH_SHORT).show();
}
}
});
latLng = new LatLng(location.getLatitude(),location.getLongitude());
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null){
mGoogleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()){
mGoogleApiClient.disconnect();
}
}
}
I used async task for upload image in the background thread to show a progress dialog. But while getting a location from async task, it throws the following error:
java.lang.RuntimeException: Can't create handler inside thread that
has not called Looper.prepare()
Although it is work without an async task. I want that process of getting location done in a background thread so that main thread can work without disturbance.
I got error in GPSlocater.java at locationmanager.requestLocationUpdates() while calling from async task.
So what should I do?
This is onLocate function which calls from mainActivity.java
public void onLocate(View view) {
asyncG asyncG1 = new asyncG(this);
asyncG1.execute();
}
This is a sub class which created in mainActivity.java
class asyncG extends AsyncTask
{
Context context;
ProgressDialog progressDialog;
public asyncG(MainActivity mainActivity) {
this.context = mainActivity;
}
#Override
protected Object doInBackground(Object[] objects) {
GPSlocater gpSlocater = new GPSlocater(context);
gpSlocater.getLocation();
lat = gpSlocater.getLatitude();
longi = gpSlocater.getLongitude();
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Finding Location");
progressDialog.show();
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
progressDialog.dismiss();
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> arr;
arr = geocoder.getFromLocation(lat,longi,1);
String pincode = arr.get(0).getPostalCode();
String stat = arr.get(0).getAdminArea();
String city1 = arr.get(0).getLocality();
String city2 = arr.get(0).getSubAdminArea();
String area1 = arr.get(0).getSubLocality();
String area2 = arr.get(0).getLocality();
if(pincode!=null && stat!=null)
{
state.setText(stat);
pin.setText(pincode);
}
if(city1!=null)
{
city.setText(city1);
}
else if(city2!=null)
{
city.setText(city2);
}
if(area1!=null)
{
area.setText(area1);
}
else if(area2!=null)
{
area.setText(area2);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is GPSlocater class which called from doInBackground
package com.example.samarth.serviceprovider1;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSlocater extends Service implements LocationListener {
private final Context mContext;
// 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 = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSlocater(Context context) {
this.mContext = context;
}
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
showSettingsAlert();
} else {
this.canGetLocation = true;
// First get location from Network Provider
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);
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_BW_UPDATES,
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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSlocater.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) {
}
#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 arg0) {
return null;
}
}
you need to create a handler to access UI elements from a thread.
https://developer.android.com/training/multiple-threads/communicate-ui.html
This tutorial should get you going, good luck (:
I am trying to make an intent call from Bluetooth Low Energy Callback function onCharacteristicRead(). Please suggest me where i am wrong .
I am not sure if it is related to the context which we give to the intent class or some thing else.
It is showing me below error :
"Unable to start activity ComponentInfo::java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference"
Below is the code sample :
package com.example.pushkara.msable;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelUuid;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.ConsoleHandler;
#TargetApi(18)
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter;
private int REQUEST_ENABLE_BT = 1;
private Handler mHandler;
private static final long SCAN_PERIOD = 5000;
private BluetoothLeScanner mLEScanner;
private ScanSettings settings;
private List<ScanFilter> filters;
private BluetoothGatt mGatt;
private MsaScanCallback mScanCallback;
private Button mCheckInButton;
private Button mCheckOutButton;
private Button mNewButton;
private Boolean buttonvalue = false;
public static TextView mSecurityCode;
public static TextView rssiNdistance;
public final static UUID UUID_MSA_APP = UUID.fromString("13333333-3333-3333-3333-333333333337");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCheckInButton = (Button)findViewById(R.id.checkIn);
mCheckOutButton = (Button)findViewById(R.id.checkOut);
mSecurityCode= (TextView)findViewById(R.id.securityCode);
rssiNdistance= (TextView)findViewById(R.id.rssiNdistance);
mCheckOutButton.setOnClickListener(new MsaCheckInCheckout(false));
mCheckInButton.setOnClickListener(new MsaCheckInCheckout(true));
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This app needs location access");
builder.setMessage("Please grant location access so this app can detect msa server.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onDismiss(DialogInterface dialog) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
});
builder.show();
}
}
mHandler = new Handler();
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "BLE Not Supported",
Toast.LENGTH_SHORT).show();
finish();
}
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
catch(Exception ex){
Log.i("msable"," [##MA]::::Exception 1" +ex.toString());
mSecurityCode.setText("[##MA]Exc1" + ex.toString());
}
}
private final ConnectDevice connectToDeviceCallback = new ConnectDevice() {
#Override
public void OnConnectToDevice(BluetoothDevice device){
connectToDevice(device);
}
};
public class MsaCheckInCheckout implements View.OnClickListener {
private boolean mCheckIn;
public MsaCheckInCheckout(boolean isCheckIn){
mCheckIn =isCheckIn;
}
#Override
public void onClick (View v) {
try {
// your code here;
Log.i("CLICK", mCheckIn + "");
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
if (Build.VERSION.SDK_INT >= 21) {
if (mGatt != null) {
mGatt.close();
mGatt = null;
}
mScanCallback = new MsaScanCallback(connectToDeviceCallback);
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
ScanFilter filter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(UUID_MSA_APP)).build();
filters = new ArrayList<>();
filters.add(filter);
}
scanLeDevice(true);
}
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 2" +ex.toString());
mSecurityCode.setText("[##MA]Ex2" + ex.toString());
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
try {
switch (requestCode) {
case 1: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("1", "coarse location permission granted");
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Functionality limited");
builder.setMessage("Since location access has not been granted, this app will not be able to discover msa server");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
builder.show();
}
}
}
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 3" +ex.toString());
mSecurityCode.setText("[##MA]Ex3" + ex.toString());
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
scanLeDevice(false);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mGatt == null) {
return;
}
mGatt.close();
mGatt = null;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_CANCELED) {
//Bluetooth not enabled.
finish();
return;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 4" +ex.toString());
mSecurityCode.setText("[##MA]Ex4" + ex.toString());
}
}
private void scanLeDevice(final boolean enable) {
try {
Log.i("BLE", "**** scanLeDevice");
if(mBluetoothAdapter != null || mLEScanner !=null) {
Log.i("BLE", "**** Object not null proceed to stop scan");
if (enable) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
Log.i("BLE", "mBluetoothAdapter STOP SCAN");
} else {
Log.i("BLE", "mLEScanner STOP SCAN");
if(mLEScanner !=null) {
Log.i("BLE", "mLEScanner not null proceed for stop ");
}
else
{
Log.i("BLE", "mLEScanner is null !!!!!");
}
mLEScanner.stopScan(mScanCallback);
}
}
}, SCAN_PERIOD);
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.startLeScan(mLeScanCallback);
Log.i("BLE", "mBluetoothAdapter START SCAN");
} else {
Log.i("START SCAN", "START SCAN");
mLEScanner.startScan(filters, settings, mScanCallback);
}
} else {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}
else
{
Log.i("BLE","**** Object is null");
}
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 5" +ex.toString());
mSecurityCode.setText("[##MA]Ex5" + ex.toString());
}
}
double getDistance(int rssi) {
return Math.pow(10d, ((double) -52 - rssi) / (10 * 2));
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, final int rssi,
byte[] scanRecord) {
try {
Log.i("BLE","**** onLeScan LeScanCallback");
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("onLeScan", device.toString());
double distance = getDistance(rssi);
rssiNdistance.setText("rssi:"+rssi+" distance:"+distance);
if (distance <= 1) {
connectToDevice(device);
}
else{
mSecurityCode.setText("Out of Range!!!");
}
}
});
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 6" +ex.toString());
mSecurityCode.setText("[##MA]Ex6" + ex.toString());
}
}
};
public void connectToDevice(BluetoothDevice device) {
Log.i("BLE","**** connectToDevice");
if (mGatt == null) {
mGatt = device.connectGatt(this, false, gattCallback);
scanLeDevice(false);// will stop after first device detection
}else{
Log.i("gatt status","ATT");
}
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
try {
Log.i("BLE","**** gattCallback onConnectionStateChange Status: "+status);
Log.i("onConnectionStateChange", "Status: " + status);
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
Log.i("gattCallback", "STATE_CONNECTED");
gatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
Log.e("gattCallback", "STATE_DISCONNECTED");
break;
default:
Log.e("gattCallback", "STATE_OTHER");
}
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 7" +ex.toString());
mSecurityCode.setText("[##MA]Ex7" + ex.toString());
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
try {
Log.i("BLE","**** onServicesDiscovered Status: "+status);
List<BluetoothGattService> services = gatt.getServices();
for (BluetoothGattService bg : services) {
Log.i(bg.toString(), bg.getUuid().toString());
if (UUID_MSA_APP.equals(bg.getUuid())) {
Log.i("MSA APP", "found");
BluetoothGattCharacteristic msacode = bg.getCharacteristics().get(0);
//gatt.setCharacteristicNotification(msacode, true);
gatt.readCharacteristic(msacode);
Log.i("BLE", "**** BluetoothGattCharacteristic msacode: " + msacode.toString());
}
else{
Log.i("MSA APP", "UUID_MSA_APP not Matching found");
}
}
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 8" +ex.toString());
mSecurityCode.setText("[##MA]Ex8" + ex.toString());
}
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic
characteristic, int status) {
try {
Log.i("BLE","**** onCharacteristicRead Status: "+status);
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for (byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
Log.i("onCharacteristicRead", new String(data));
runOnUiThread(new Runnable() {
#Override
public void run() {
mSecurityCode.setText(new String(data));
Intent intent = new Intent(MainActivity.this, newActivity.class);
intent.putExtra("UniqueCode", new String(data));
startActivity(intent);
}
});
}
gatt.disconnect();
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 9" +ex.toString());
mSecurityCode.setText("[##MA]Ex9" + ex.toString());
}
}
};
}
In callback need to give intent a static context and had to set intent FLAG_ACTIVITY_NEW_TASK flag.
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic
characteristic, int status) {
try {
//Reads the requested characteristic and get the characteristic value.
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for (byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
Intent intent = new Intent(callBackContext, InOutActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
callBackContext.startActivity(intent);
}
}
catch(Exception ex){
dbObj.PutLog("[##MA]EX7" + ex.toString());
}
finally{
if(gatt != null){
dbObj.PutLog("[MA] 5 CLOSE GATT");
gatt.disconnect();
gatt.close();
}
}
}
};
Here callBackContext.startActivity(intent); is a Static context given to intent. this solved my purpose
It seems that mSecurityCode is causing the exception. Please post the code where you initialize or write to that variable, and also where you setup the Bluetooth callback.
I have tried to figure this out for the past 48 hours, but I must be an idiot. I followed the Google documentation to try and make this weather app location aware. The problem is I don't how to make onLocationChanged() run or even know when it is supposed to run. If it doesn't run I send a request to grab data from latitude 0 and longitude 0. I have enabled all the correct permissions. Please help me...
package com.brennanglynn.brennanweather.ui;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.brennanglynn.brennanweather.R;
import com.brennanglynn.brennanweather.weather.Current;
import com.brennanglynn.brennanweather.weather.Day;
import com.brennanglynn.brennanweather.weather.Forecast;
import com.brennanglynn.brennanweather.weather.Hour;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
public static final String TAG = MainActivity.class.getSimpleName();
protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
protected final static String LOCATION_KEY = "location-key";
protected final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
public static final String BG_GRADIENT = "BG_GRADIENT";
private Forecast mForecast;
private ColorWheel mColorWheel;
private int[] mBackground;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected Location mCurrentLocation;
protected Boolean mRequestingLocationUpdates;
protected String mLastUpdateTime;
private double mLatitude;
private double mLongitude;// = -116.2296;
#BindView(R.id.layoutBackground)
RelativeLayout mLayoutBackground;
#BindView(R.id.timeLabel)
TextView mTimeLabel;
#BindView(R.id.temperatureLabel)
TextView mTemperatureLabel;
#BindView(R.id.humidityValue)
TextView mHumidityValue;
#BindView(R.id.precipValue)
TextView mPrecipValue;
#BindView(R.id.summaryLabel)
TextView mSummaryLabel;
#BindView(R.id.iconImageView)
ImageView mIconImageView;
#BindView(R.id.refreshImageView)
ImageView mRefreshImageView;
#BindView(R.id.progressBar)
ProgressBar mProgressBar;
#BindView(R.id.locationLabel)
TextView mLocationLabel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mRequestingLocationUpdates = false;
mLastUpdateTime = "";
updateValuesFromBundle(savedInstanceState);
buildGoogleApiClient();
mColorWheel = new ColorWheel();
mProgressBar.setVisibility(View.INVISIBLE);
}
private void updateValuesFromBundle(Bundle savedInstanceState) {
Log.i(TAG, "Updating values from bundle");
if (savedInstanceState != null) {
// Update the value of mRequestingLocationUpdates from the Bundle, and make sure that
// the Start Updates and Stop Updates buttons are correctly enabled or disabled.
if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
mRequestingLocationUpdates = savedInstanceState.getBoolean(
REQUESTING_LOCATION_UPDATES_KEY);
}
// Update the value of mCurrentLocation from the Bundle and update the UI to show the
// correct latitude and longitude.
if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
// Since LOCATION_KEY was found in the Bundle, we can be sure that mCurrentLocation
// is not null.
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
}
// Update the value of mLastUpdateTime from the Bundle and update the UI.
if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
}
updateDisplay();
}
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
private void setBackgroundGradient() {
mBackground = mColorWheel.getColors();
GradientDrawable gd = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
new int[]{mBackground[0], mBackground[1]});
gd.setCornerRadius(0f);
mLayoutBackground.setBackground(gd);
}
private void getForecast(double latitude, double longitude) {
String apiKey = "50e826df5889d0d215cdcbae50d182e3";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mForecast = parseForecastDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException | JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
} else {
alertUserAboutError();
}
Log.i(TAG, forecastUrl);
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private Forecast parseForecastDetails(String jsonData) throws JSONException {
Forecast forecast = new Forecast();
forecast.setCurrentForecast(getCurrentDetails(jsonData));
forecast.setHourlyForecast(getHourlyForecast(jsonData));
forecast.setDailyForecast(getDailyForecast(jsonData));
return forecast;
}
private Day[] getDailyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject daily = forecast.getJSONObject("daily");
JSONArray data = daily.getJSONArray("data");
Day[] days = new Day[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonHour = data.getJSONObject(i);
Day day = new Day();
day.setTime(jsonHour.getLong("time"));
day.setSummary(jsonHour.getString("summary"));
day.setTemperatureMax(jsonHour.getInt("temperatureMax"));
day.setTimezone(timezone);
day.setIcon(jsonHour.getString("icon"));
days[i] = day;
}
return days;
}
private Hour[] getHourlyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject hourly = forecast.getJSONObject("hourly");
JSONArray data = hourly.getJSONArray("data");
Hour[] hours = new Hour[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonHour = data.getJSONObject(i);
Hour hour = new Hour();
hour.setTime(jsonHour.getLong("time"));
hour.setSummary(jsonHour.getString("summary"));
hour.setTemperature(jsonHour.getInt("temperature"));
hour.setTimezone(timezone);
hour.setIcon(jsonHour.getString("icon"));
hours[i] = hour;
}
return hours;
}
private Current getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject currently = forecast.getJSONObject("currently");
Current current = new Current(
currently.getString("icon"),
currently.getLong("time"),
currently.getDouble("temperature"),
currently.getDouble("humidity"),
currently.getDouble("precipProbability"),
currently.getString("summary"),
forecast.getString("timezone")
);
Log.i(TAG, current.toString());
return current;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
#OnClick(R.id.refreshImageView)
public void refreshPage(View view) {
mRequestingLocationUpdates = true;
getForecast(mLatitude, mLongitude);
setBackgroundGradient();
}
#OnClick(R.id.dailyButton)
public void startDailyActivity(View view) {
Intent intent = new Intent(this, DailyForecastActivity.class);
intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
if (mBackground != null) {
intent.putExtra(BG_GRADIENT, mBackground);
}
startActivity(intent);
}
#OnClick(R.id.hourButton)
public void startHourlyActivity(View view) {
Intent intent = new Intent(this, HourlyForecastActivity.class);
intent.putExtra(HOURLY_FORECAST, mForecast.getHourlyForecast());
if (mBackground != null) {
intent.putExtra(BG_GRADIENT, mBackground);
}
startActivity(intent);
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void startUpdatesButtonHandler(View view) {
if (!mRequestingLocationUpdates) {
mRequestingLocationUpdates = true;
startLocationUpdates();
}
}
public void stopUpdatesButtonHandler(View view) {
if (mRequestingLocationUpdates) {
mRequestingLocationUpdates = false;
stopLocationUpdates();
}
}
protected void startLocationUpdates() {
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);
}
protected void stopLocationUpdates() {
// It is a good practice to remove location requests when the activity is in a paused or
// stopped state. Doing so helps battery performance and is especially
// recommended in applications that request frequent location updates.
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
private void updateDisplay() {
Current current = mForecast.getCurrentForecast();
mTemperatureLabel.setText(current.getTemperature() + "");
mTimeLabel.setText("The time is " + current.getFormattedTime());
mHumidityValue.setText(current.getHumidity() + "");
mPrecipValue.setText(current.getPrecipChance() + "%");
mSummaryLabel.setText(current.getSummary());
Drawable drawable = ResourcesCompat.getDrawable(getResources(), current.getIconId(), null);
mIconImageView.setImageDrawable(drawable);
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onResume() {
super.onResume();
// Within {#code onPause()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
protected void onPause() {
super.onPause();
// Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
// If the initial location was never previously requested, we use
// FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store
// its value in the Bundle and check for it in onCreate(). We
// do not request it again unless the user specifically requests location updates by pressing
// the Start Updates button.
//
// Because we cache the value of the initial location in the Bundle, it means that if the
// user launches the activity,
// moves to a new location, and then changes the device orientation, the original location
// is displayed as the activity is re-created.
if (mCurrentLocation == null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "location changed");
mCurrentLocation = location;
mLatitude = mCurrentLocation.getLatitude();
mLongitude = mCurrentLocation.getLongitude();
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
getForecast(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
updateDisplay();
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates);
savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation);
savedInstanceState.putString(LAST_UPDATED_TIME_STRING_KEY, mLastUpdateTime);
super.onSaveInstanceState(savedInstanceState);
}
}
hi your api is working fine, i have checked. You have issue with your current latitude and longitude. So, i have one solution for you.
Please check how i'm using in my app and its working perfect.I'm using fused api for update location please follow few steps.
Step 1. Make this class
GoogleLocationService.java
public class GoogleLocationService {
private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks();
LocationUpdateListener locationUpdateListener;
Context activity;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000;
public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) {
this.locationUpdateListener = locationUpdateListener;
this.activity = activity;
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
//Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(activity)
.addConnectionCallbacks(callbacks)
.addOnConnectionFailedListener(callbacks)
.addApi(LocationServices.API)
.build();
createLocationRequest();
mGoogleApiClient.connect();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private class GoogleServicesCallbacks implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) {
Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show();
}
locationUpdateListener.cannotReceiveLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location.hasAccuracy()) {
if (location.getAccuracy() < 30) {
locationUpdateListener.updateLocation(location);
}
}
}
}
private static boolean locationEnabled(Context context) {
boolean gps_enabled = false;
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
return gps_enabled;
}
private boolean servicesConnected(Context context) {
return isPackageInstalled(GooglePlayServicesUtil.GOOGLE_PLAY_STORE_PACKAGE, context);
}
private boolean isPackageInstalled(String packagename, Context context) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
public void startUpdates() {
/*
* Connect the client. Don't re-start any requests here; instead, wait
* for onResume()
*/
if (servicesConnected(activity)) {
if (locationEnabled(activity)) {
locationUpdateListener.canReceiveLocationUpdates();
startLocationUpdates();
} else {
locationUpdateListener.cannotReceiveLocationUpdates();
Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show();
}
} else {
locationUpdateListener.cannotReceiveLocationUpdates();
Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show();
}
}
//stop location updates
public void stopUpdates() {
stopLocationUpdates();
}
//start location updates
private void startLocationUpdates() {
if (checkSelfPermission(activity, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(activity, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, callbacks);
}
}
public void stopLocationUpdates() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, callbacks);
}
}
public void startGoogleApi() {
mGoogleApiClient.connect();
}
public void closeGoogleApi() {
mGoogleApiClient.disconnect();
}
}
Step2. Make this interface
LocationUpdateListener.java
public interface LocationUpdateListener {
/**
* Called immediately the service starts if the service can obtain location
*/
void canReceiveLocationUpdates();
/**
* Called immediately the service tries to start if it cannot obtain location - eg the user has disabled wireless and
*/
void cannotReceiveLocationUpdates();
/**
* Called whenever the location has changed (at least non-trivially)
* #param location
*/
void updateLocation(Location location);
/**
* Called when GoogleLocationServices detects that the device has moved to a new location.
* #param localityName The name of the locality (somewhere below street but above area).
*/
void updateLocationName(String localityName, Location location);
}
Step 3. Call this in your class oncreate or where you want to get location
private GoogleLocationService googleLocationService;
googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() {
#Override
public void canReceiveLocationUpdates() {
}
#Override
public void cannotReceiveLocationUpdates() {
}
//update location to our servers for tracking purpose
#Override
public void updateLocation(Location location) {
if (location != null ) {
Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude());
}
}
#Override
public void updateLocationName(String localityName, Location location) {
googleLocationService.stopLocationUpdates();
}
});
googleLocationService.startUpdates();
and call this onDestroy
if (googleLocationService != null) {
googleLocationService.stopLocationUpdates();
}
Hope this will help you to solve your problem.
I'm trying to acquire GPS coordinates on my android application.
Criteria criteria = new Criteria();
criteria.setAltitudeRequired(false);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
LocationManager locationManager =
(LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Intent i = new Intent(context, IntentListener.class);
i.setAction(Actions.ACTION_UPDATE_LOCATION);
PendingIntent pi = PendingIntent.getBroadcast(
context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
String provider = locationManager.getBestProvider(criteria, true);
if (provider == null) return;
locationManager.requestLocationUpdates(provider, 90 * 1000, 30, pi);
and here's receiving code.
Intent service = new Intent(context, WorkerService.class);
service.setAction(Actions.ACTION_UPDATE_LOCATION);
Location location = (Location) intent.getExtras().get(
LocationManager.KEY_LOCATION_CHANGED);
if (location == null) { // <-- Always true
return;
}
service.putExtra("lat", location.getLatitude());
service.putExtra("lon", location.getLongitude());
context.startService(service);
As you can see, I'm unable to obtain Location instance by calling intent.getExtras()... etc. Returned value is always null. I'm testing on my emulator running android 4.1.2 and telnet client, using geo fix longitude latitude. Anyone knows what's wrong? Thanks.
P.S. Manifest contains all required permissions and GPS is enabled in the emulator.
P.P.S. This application is a corporate app, that runs as a service, without UI and should collect GPS coordinates.
You casually mentioned that you're testing on an emulator. The emulator doesn't receive mock locations by itself; you have to specifically send them through the DDMS interface.
Additionally, due to a bug in the emulator, the time offset in incoming locations is set to midnight, so your location criteria will likely not match it.
I strongly suggest you test with a physical device to confirm that the problem is still occurring.
Use the new Location API.
You'd have to include Google Play services into your project.
Add this in onCreate:
mIntentService = new Intent(this,LocationService.class);
mPendingIntent = PendingIntent.getService(this, 1, mIntentService, 0);
int resp =GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resp == ConnectionResult.SUCCESS){
locationclient = new LocationClient(this,this,this);
locationclient.connect();
}
And you'd have to override these methods:
#Override
protected void onDestroy() {
super.onDestroy();
if(locationclient!=null)
locationclient.disconnect();
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "onConnected");
//to get last location
Location loc =locationclient.getLastLocation();
//to get updates via service
locationrequest = LocationRequest.create();
locationrequest.setInterval(100);
locationclient.requestLocationUpdates(locationrequest, mPendingIntent);
}
#Override
public void onDisconnected() {
Log.i(TAG, "onDisconnected");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "onConnectionFailed");
}
#Override
public void onLocationChanged(Location location) {
if(location!=null){
Log.i(TAG, "Location Request :" + location.getLatitude() + "," + location.getLongitude());
}
}
Here's the service where I'm creating a notification for every new location, you can remove that and update location there.
public class LocationService extends IntentService {
private String TAG = this.getClass().getSimpleName();
public LocationService() {
super("Fused Location");
}
public LocationService(String name) {
super("Fused Location");
}
#Override
protected void onHandleIntent(Intent intent) {
Location location = intent.getParcelableExtra(LocationClient.KEY_LOCATION_CHANGED);
if(location !=null){
Log.i(TAG, "onHandleIntent " + location.getLatitude() + "," + location.getLongitude());
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Builder noti = new NotificationCompat.Builder(this);
noti.setContentTitle("Fused Location");
noti.setContentText(location.getLatitude() + "," + location.getLongitude());
noti.setSmallIcon(R.drawable.ic_launcher);
notificationManager.notify(1234, noti.build());
}
}
}
Follow the tutorial to get the location in Android app
You should take your location by implementing LocationListener
#Override
public void onLocationChanged(Location loc) {
}
Take a look at this implementation, works really nice and i have tested it on several devices.
package ro.gebs.captoom.activities;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.bugsense.trace.BugSenseHandler;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import ro.gebs.captoom.R;
import ro.gebs.captoom.database.ReceiptDataSource;
import ro.gebs.captoom.utils.Constants;
import ro.gebs.captoom.utils.Utils;
public class LocationActivity extends FragmentActivity {
private GoogleMap map;
private long rec_id;
private String address;
private Marker selectedLoc;
private boolean isSessionClosed;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
BugSenseHandler.initAndStartSession(this, Constants.BugSenseKEY);
setContentView(R.layout.preview_location);
RelativeLayout cancel_btn = (RelativeLayout) findViewById(R.id.cancel_btn);
LinearLayout save_location_btn = (LinearLayout) findViewById(R.id.delete_btn);
save_location_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (address != null) {
ReceiptDataSource r = new ReceiptDataSource();
r.updateReceiptLocation(rec_id, address);
Intent returnIntent = new Intent(getBaseContext(), EditReceiptActivity.class);
returnIntent.putExtra("result", address);
setResult(RESULT_OK, returnIntent);
finish();
} else {
Utils.showToast(getApplicationContext(), getString(R.string.c_unknownLocation), Toast.LENGTH_SHORT);
}
}
});
cancel_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (isGoogleMapsInstalled()) {
if (map != null) {
retrieveLocation();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Install Google Maps");
builder.setCancelable(false);
builder.setPositiveButton("Install", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.apps.maps"));
startActivity(intent);
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
if (isSessionClosed) {
BugSenseHandler.startSession(this);
isSessionClosed = false;
}
}
#Override
protected void onPause() {
super.onPause();
BugSenseHandler.closeSession(this);
isSessionClosed = true;
}
#Override
public void onBackPressed() {
map.clear();
super.onBackPressed();
}
private void retrieveLocation() {
Intent intent = getIntent();
address = intent.getStringExtra("location");
assert address != null;
if (address.equalsIgnoreCase("")) {
address = Utils.getCurrentLocation(LocationActivity.this);
}
rec_id = intent.getLongExtra("receipt_to_update_location", 0);
final Geocoder geocoder = new Geocoder(this, Locale.US);
double latitude = 0, longitude = 0;
try {
List<Address> loc = geocoder.getFromLocationName(address, 5);
if (loc.size() > 0) {
latitude = loc.get(0).getLatitude();
longitude = loc.get(0).getLongitude();
} else {
Utils.showToast(LocationActivity.this, getString(R.string.UnableToFindLocation), Toast.LENGTH_SHORT);
}
selectedLoc = map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(address).draggable(true));
map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
try {
List<Address> addresses = geocoder.getFromLocation(selectedLoc.getPosition().latitude, selectedLoc.getPosition().longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
if (address.getAddressLine(0) != null)
sb.append(address.getAddressLine(0)).append(", ");
if (address.getLocality() != null)
sb.append(address.getLocality()).append(", ");
if (address.getCountryName() != null)
sb.append(address.getCountryName());
}
address = sb.toString();
} catch (IOException e) {
}
}
});
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 12));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
} catch (IOException e) {
Log.e("IOException", e.getMessage());
Utils.showToast(LocationActivity.this, getString(R.string.c_unknownLocation), Toast.LENGTH_LONG);
}
}
public boolean isGoogleMapsInstalled() {
try {
getPackageManager().getApplicationInfo("com.google.android.apps.maps", 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
}
I see you implement the intent.putExtra after you get the extra! You should do the put in the activity that receives the location data and when you want to receive the data from the intent.extra you should do this:
Bundle extras = getIntent().getExtras();
if (extras != null) {
latitude= (double)extras.getDouble("lat");
longitude=(double)extras.getDouble("lon");
}