Finding Location - android

i'm writing a program which i need to get the coordination of my place , latitude and longitude. my problem is i cant get the location and in my Log lat
and lng are 0 and 0 and i'm trying to run it on a nexus 6P device which is running android M 6.0.1.
here is my GPSTracker class
package es.euphrat.clover.compass;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
private Location mLocation;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager mLocationManager;
public GPSTracker(Context context) {
mContext = context;
getLocation();
}
private Location getLocation() {
try {
mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
}
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
latitude = mLocation.getLatitude();
longitude = mLocation.getLongitude();
}
}
}
if (isGPSEnabled) {
if (mLocation == null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
latitude = mLocation.getLatitude();
longitude = mLocation.getLongitude();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return mLocation;
}
public void stopUsingGPS() {
if (mLocationManager != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mLocationManager.removeUpdates(GPSTracker.this);
}
}
}
public double getLatitude(){
if (mLocation != null){
latitude = mLocation.getLatitude();
}
return latitude;
}
public double getLongitude(){
if (mLocation != null){
longitude = mLocation.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
#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) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
this is my main method which i'm Logging the result in main activity
package es.euphrat.clover.compass.activity;
import android.Manifest;
import android.content.Context;
import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import es.euphrat.clover.compass.GPSTracker;
import es.euphrat.clover.compass.R;
import es.euphrat.clover.compass.adapters.CityAdapter;
import es.euphrat.clover.compass.boxes.CityBox;
import es.euphrat.clover.compass.boxes.CompassAndCityBox;
import es.euphrat.clover.compass.boxes.DateBox;
import es.euphrat.clover.compass.boxes.DayAndNight;
import es.euphrat.clover.compass.database.City;
import es.euphrat.clover.compass.database.DataBaseHelper;
import info.alqiblah.taqwim.MA6;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
public final String TAG = this.getClass().getSimpleName();
protected DataBaseHelper mDataBaseHelper;
protected CompassAndCityBox mCompassAndCityBox;
protected DateBox mDateBox;
protected CityBox mCityBox;
protected DayAndNight mDayAndNight;
protected SensorManager mSensorManager;
protected LinearLayout myRoot;
protected DrawerLayout drawerLayout;
protected RelativeLayout gpsDrawer;
protected RelativeLayout cityListDrawer;
protected ArrayList<String> mCityNames;
protected ListView cityListView;
protected EditText searchCity;
protected City[] mCities;
private CityAdapter mCityListAdapter;
protected City currentCity;
protected GPSTracker mGPSTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath(getTypeface())
.setFontAttrId(R.attr.fontPath)
.build());
myRoot = (LinearLayout) findViewById(R.id.my_root);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
gpsDrawer = (RelativeLayout) findViewById(R.id.gps_drawer);
cityListDrawer = (RelativeLayout) findViewById(R.id.city_list_drawer);
cityListView = (ListView) findViewById(R.id.listView);
searchCity = (EditText) findViewById(R.id.search_city);
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
MA6.InitPlanetsTerms(this);
mGPSTracker = new GPSTracker(this);
mCityNames = new ArrayList<>();
mDataBaseHelper = new DataBaseHelper(this);
mCityBox = new CityBox(this);
mDateBox = new DateBox(this);
mCompassAndCityBox = new CompassAndCityBox(this);
mDayAndNight = new DayAndNight(this);
myRoot.addView(mCityBox);
myRoot.addView(mDateBox);
myRoot.addView(mCompassAndCityBox);
myRoot.addView(mDayAndNight);
searchCityTextView();
createTheDataBase();
double a = mGPSTracker.getLatitude();
if (mGPSTracker.canGetLocation()) {
Log.d(TAG, String.valueOf(mGPSTracker.canGetLocation()));
Log.d(TAG, a + "," + mGPSTracker.getLongitude());
}
}
private void createTheDataBase() {
try {
mDataBaseHelper.createDataBase();
} catch (IOException e) {
Log.e(TAG , "Cannot Create DataBase", e);
}
}
private void searchCityTextView() {
searchCity.clearComposingText();
searchCity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Cursor cursor = mDataBaseHelper.selectOrSearchAllCities(searchCity.getText().toString());
updateList(cursor);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private void updateList(Cursor cursor) {
mCityNames.clear();
final int cityName = cursor.getColumnIndex(DataBaseHelper.CITY_NAME);
int timeZone = cursor.getColumnIndex(DataBaseHelper.CITY_TIMEZONE);
int countryName = cursor.getColumnIndex(DataBaseHelper.COUNTRY_NAME);
int lat = cursor.getColumnIndex(DataBaseHelper.CITY_LATITUDE);
int lng = cursor.getColumnIndex(DataBaseHelper.CITY_LONGITUDE);
mCities = new City[cursor.getCount()];
int c = 0;
cursor.moveToFirst();
while (!cursor.isAfterLast()){
String city = cursor.getString(cityName);
String tZone = cursor.getString(timeZone);
String country = cursor.getString(countryName);
float latitude = cursor.getFloat(lat);
float longitude = cursor.getFloat(lng);
mCities[c] = new City(city,tZone,country,latitude,longitude);
c++;
cursor.moveToNext();
}
mCityListAdapter = new CityAdapter(this, mCities);
cityListView.setAdapter(mCityListAdapter);
cityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
currentCity = new City(mCities[position]);
drawerLayout.closeDrawer(cityListDrawer);
mCityBox.setCurrentCityName(currentCity);
hideKeyboard();
}
});
}
private void hideKeyboard() {
InputMethodManager inputManager =
(InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
public void antenaClick(View view) {
drawerLayout.openDrawer(gpsDrawer);
}
public void pinpointClick (View view){
drawerLayout.openDrawer(cityListDrawer);
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_GAME);
mDataBaseHelper.openDataBase();
Cursor cursor = mDataBaseHelper.selectOrSearchAllCities(searchCity.getText().toString());
updateList(cursor);
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
mDataBaseHelper.close();
}
#Override
public void onSensorChanged(SensorEvent event) {
float degree = Math.round(event.values[0]);
mCompassAndCityBox.setDegreeFromNorth(degree,currentCity);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
private String getTypeface(){
if( Locale.getDefault().getDisplayLanguage().toLowerCase().startsWith("en")) return "fonts/Roboto-Medium.ttf";
else return "fonts/IRAN Sans.ttf";
}
}
and this is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="es.euphrat.clover.compass">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
>
<activity android:name=".activity.MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
can any one please help me to find a solution for my problem.

Related

GoogleFusedLocation api returns me null for lat and 0.0 for lon and altitude ever

Sorry for the long title but couldn't resume it more, basicly i implemented the googlefusedlocation api as a service, i need the service to run on background and update the location, this service starts on my app running (atm i am not requesting the user if he want to share location because i have no idea how ti implement it with a service).
My service:
package com.example.afcosta.inesctec.pt.android.services;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class GoogleLocation extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG = "BOOMBOOMTESTGPS";
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 0;
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 0f;
private int updatePriority;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private final IBinder mBinder = new LocalBinder();
private Intent intent;
private String provider;
Context context;
Location mLastLocation;
public class LocalBinder extends Binder {
public GoogleLocation getServerInstance() {
return GoogleLocation.this;
}
}
public Location getLocation() {
Log.d("IMHERE", "HELLO");
return mLastLocation;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
context = getApplicationContext();
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
} else if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
this.updatePriority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
} else {
this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
}
this.buildGoogleApiClient();
this.createLocationRequest();
this.googleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(this.googleApiClient, this.locationRequest,this);
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
this.googleApiClient.unregisterConnectionCallbacks(this);
this.googleApiClient.unregisterConnectionFailedListener(this);
this.googleApiClient.disconnect();
this.mLastLocation = null;
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
private synchronized void buildGoogleApiClient() {
this.googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
private void createLocationRequest() {
this.locationRequest = new LocationRequest();
this.locationRequest.setInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
this.locationRequest.setPriority(updatePriority);
}
then on my camera i access the getLocation method that is inside my service, it gives me the last location, i just display the way i acces the service if you guys ask, but i just remember that i had a solution before(i used locationListener and not google one) and i could get the location, failled sometimes thats why i tried to change.
public void onServiceConnected(ComponentName name, IBinder service) {
mBounded = true;
GoogleLocation.LocalBinder mLocalBinder = (GoogleLocation.LocalBinder)service;
mlocation = mLocalBinder.getServerInstance();
location = mlocation.getLocation();
Log.d("localizacao",location.toString());
}
Now i get:
lat:null
lon:0.0
alt:0.0
Strange, why is that happening?
Thanks

Lat and Lng always return 0.0,0.0

hi im going through this tutorial and i faced a annoying problem that latitude and longitude always return 0.0 .im using api 16 on nexus 4.
GPSTracker.java
package ir.ketabe_zard.www.maps;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
/**
* Created by Pedram Hassas on 11/24/2016.
*/
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
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 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) {
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.
}
Criteria locationCritera = new Criteria();
String providerName = locationManager.getBestProvider(locationCritera,
true);
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(providerName);
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;
}
/**
* 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 if best network provider
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* */
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?");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.delete);
// 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();
}
public void stopUsingGPS() {
if (locationManager != 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;
}
locationManager.removeUpdates(GPSTracker.this);
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location loc) {
if(location!=null){
location=loc;
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}<br>
MapsActivity.java
package ir.ketabe_zard.www.maps;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
View.OnClickListener {
Location location;
TextView txtLatLng;
protected LocationManager locationManager;
Double Lat, Lng;
LocationListener locationListener = new LocationListener() {
#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) {
}
};
#Override
public void onMapLongClick(LatLng latLng) {
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
#Override
protected void onStart() {
txtLatLng = (TextView) findViewById(R.id.txtLatLng);
super.onStart();
}
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
}
public void btnLocation_clicked(View view) {
GPSTracker gps = new GPSTracker(this);
if(gps.canGetLocation()){
Lat=gps.getLatitude();
Lng=gps.getLongitude();
txtLatLng.setText(String.valueOf(Lat)+","+String.valueOf(Lng));
}else {
gps.showSettingsAlert();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
final TextView LatLng;
// Add a marker in Sydney and move the camera
LatLng Tehran = new LatLng(35.689197, 51.388974);
mMap.addMarker(new MarkerOptions().position(Tehran).title("Marker in Tehran").draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Tehran, 12));
}
#Override
public void onClick(View v) {
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#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) {
}
}<br>
i have a button when user taped it . show lat and lng in a textview in x.x,x.x format.

Error inflating class fragment with supportMapFragment and fragmentactivity

This question is asked here many times,I tried all the answers but none of them worked.
I'm getting this error: Error inflating class fragment.
Mapsactivity:
package com.example.gio.autostop;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Geocoder;
import android.location.Location;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
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.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.NetworkInterface;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class MapsActivity extends FragmentActivity implements LocationListener,
GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener,
GoogleApiClient.ConnectionCallbacks {
public int permissionRequestCounter;
public GoogleApiClient mGoogleApiClient;
public Boolean startedLocationUpdate;
public LocationRequest locationRequest;
public Location mCurrentLocation;
public LocationManager mLocationManager;
public final static int MILISECONDS_PER_SECOND = 1000;
public final static int REQUEST_FINE_LOCATION = 0;
public final static int MINUTE = 60 * MILISECONDS_PER_SECOND;
protected String mLastUpdateTime;
protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
protected final static String LOCATION_KEY = "location-key";
protected static final String ADDRESS_REQUESTED_KEY = "address-request-pending";
protected static final String LOCATION_ADDRESS_KEY = "location-address";
protected static final String TAG = "main-activity";
public address_fragment address_fragment;
private GoogleMap mMap;// Might be null if Google Play services APK is not available.
private Button checkInButton,checkOutButton;
private ArrayList<Marker> markerCollection = new ArrayList<>();
private Marker markerForDeletion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
checkInButton = (Button) findViewById(R.id.button2);
checkOutButton=(Button)findViewById(R.id.button3);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
address_fragment address_fragment=(address_fragment)getSupportFragmentManager().findFragmentById(R.id.address_fragment);
address_fragment.setMapsActivity(this);
startedLocationUpdate = false;
permissionRequestCounter = 0;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
locationRequest = new LocationRequest();
locationRequest.setInterval(MINUTE);
locationRequest.setFastestInterval(15 * MILISECONDS_PER_SECOND);
locationRequest.setPriority(com.google.android.gms.location.LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
checkGps();
}
deviceUniqueNumber();
updateValuesFromBundle(savedInstanceState);
checkInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkInCurrentPosition();
checkInButton.setClickable(false);
checkOutButton.setClickable(true);
}
});
checkOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePosition();
markerForDeletion.remove();
checkOutButton.setClickable(false);
checkInButton.setClickable(true);
}
});
checkOutButton.setClickable(false);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
if (mGoogleApiClient.isConnected() && !startedLocationUpdate)
startLocationUpdates();
}
#Override
public void onConnected(Bundle bundle) {
if (!startedLocationUpdate)
startLocationUpdates();
if (mCurrentLocation != null) {
if (!Geocoder.isPresent()) {
Toast.makeText(this, R.string.no_geocoder_available, Toast.LENGTH_SHORT).show();
return;
}
address_fragment gettingAddressFragment=(address_fragment)getSupportFragmentManager().findFragmentById(R.id.map);
if (gettingAddressFragment.mAddressRequested) {
gettingAddressFragment.startIntentService();
}
}
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
startedLocationUpdate = false;
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected() && startedLocationUpdate)
stopLocationUpdates();
}
private void startLocationUpdates() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, MapsActivity.this);
startedLocationUpdate = true;
} else {
if (permissionRequestCounter == 0) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
permissionRequestCounter++;
}
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMyLocationButtonClickListener(this);
enableMyLocation();
}
public void enableMyLocation() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
if (permissionRequestCounter == 0) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
permissionRequestCounter++;
}
} else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_FINE_LOCATION: {
if (grantResults.length == 1
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableMyLocation();
checkGps();
} else {
Toast.makeText(MapsActivity.this, "Permission was blocked", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public boolean onMyLocationButtonClick() {
checkGps();
return false;
}
public void checkGps() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
}
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
address_fragment.fetchAddressHandler();
}
private void setUpMap() {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonResponse = new JSONObject(s);
boolean success = jsonResponse.getBoolean("success");
if (success) {
JSONArray jsonArray = jsonResponse.getJSONArray("data");
JSONObject jsonObject;
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String mac = jsonObject.getString("mac");
String android_id = jsonObject.getString("android_id");
Double latitude = jsonObject.getDouble("latitude");
Double longitude = jsonObject.getDouble("longitude");
if (!isMarkerOnArray(markerCollection, latitude, longitude))
markerCollection.add(mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude))));
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MapsActivity.this);
builder.setMessage("Downloading position failed")
.setNegativeButton("retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DownloadPosition downloadPosition = new DownloadPosition(responseListener);
RequestQueue queue = Volley.newRequestQueue(MapsActivity.this);
queue.add(downloadPosition);
}
private boolean isMarkerOnArray(ArrayList<Marker> array, Double Latitude, Double Longitude) {
Marker current;
for (int c = 0; c < array.size(); c++) {
current = array.get(c);
if ((current.getPosition().latitude == Latitude) && (current.getPosition().longitude == Longitude))
return true;
}
return false;
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, startedLocationUpdate);
savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation);
savedInstanceState.putBoolean(ADDRESS_REQUESTED_KEY, address_fragment.mAddressRequested);
savedInstanceState.putString(LOCATION_ADDRESS_KEY, address_fragment.mAddressOutput);
super.onSaveInstanceState(savedInstanceState);
}
private void updateValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY))
startedLocationUpdate = savedInstanceState.getBoolean(REQUESTING_LOCATION_UPDATES_KEY);
if (savedInstanceState.keySet().contains(LOCATION_KEY))
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
if (savedInstanceState.keySet().contains(ADDRESS_REQUESTED_KEY)) {
address_fragment.mAddressRequested = savedInstanceState.getBoolean(ADDRESS_REQUESTED_KEY);
}
if (savedInstanceState.keySet().contains(LOCATION_ADDRESS_KEY)) {
address_fragment.mAddressOutput = savedInstanceState.getString(LOCATION_ADDRESS_KEY);
address_fragment.displayAddressOutput();
}
}
}
public void checkInCurrentPosition() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location locationGPS = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNet = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location location;
long GPSLocationTime = 0;
if (null != locationGPS) { GPSLocationTime = locationGPS.getTime(); }
long NetLocationTime = 0;
if (null != locationNet) {
NetLocationTime = locationNet.getTime();
}
if ( 0 < GPSLocationTime - NetLocationTime ) {
location=locationGPS;
}
else {
location=locationNet;
}
LatLng newLatLng = new LatLng(location.getLatitude(), location.getLongitude());
markerForDeletion=mMap.addMarker(new MarkerOptions().position(newLatLng).title(newLatLng.toString()));
String deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
Positions position=new Positions(newLatLng.latitude,newLatLng.longitude,getWifiMacAddress(),deviceId);
Response.Listener<String> responseListener= new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonResponse= new JSONObject(s);
boolean success=jsonResponse.getBoolean("success");
if(!success){
AlertDialog.Builder builder=new AlertDialog.Builder(MapsActivity.this);
builder.setMessage("uploading position failed")
.setNegativeButton("retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
UploadPosition upload=new UploadPosition(position,responseListener);
RequestQueue queue= Volley.newRequestQueue(MapsActivity.this);
queue.add(upload);
}
public void deletePosition(){
String deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
String mac=getWifiMacAddress();
Response.Listener<String> responseListener = new Response.Listener<String>(){
#Override
public void onResponse(String s) {
try {
JSONObject jsonResponse= new JSONObject(s);
boolean success=jsonResponse.getBoolean("success");
if(!success){
AlertDialog.Builder builder=new AlertDialog.Builder(MapsActivity.this);
builder.setMessage("uploading position failed")
.setNegativeButton("retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DeletePosition delete=new DeletePosition(mac,deviceId,responseListener);
RequestQueue queue=Volley.newRequestQueue(MapsActivity.this);
queue.add(delete);
}
public void deviceUniqueNumber(){
String deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
Toast.makeText(this,deviceId+" "+getWifiMacAddress(),Toast.LENGTH_SHORT).show();
}
public static String getWifiMacAddress() {
try {
String interfaceName = "wlan0";
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (!intf.getName().equalsIgnoreCase(interfaceName)){
continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac==null){
return "";
}
StringBuilder buf = new StringBuilder();
for (byte aMac : mac) {
buf.append(String.format("%02X:", aMac));
}
if (buf.length()>0) {
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}
} catch (Exception ex) {
Log.i("getWifiMacAddress","exception in getWifiMacAddress");
}
return "";
}
}
activity_maps.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<fragment class="com.example.gio.autostop.address_fragment"
android:id="#+id/address_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/map"
tools:context="com.example.gio.autostop.MapsActivity"
class="com.google.android.gms.maps.SupportMapFragment"
>
<include layout="#layout/map_interface"/>
</fragment>
</LinearLayout>
address_fragment.java:
package com.example.gio.autostop;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
public class address_fragment extends Fragment {
protected TextView mLocationAddressTextView;
protected String mAddressOutput;
private AddressResultReceiver mResultReceiver;
private ProgressBar mProgressBar;
protected boolean mAddressRequested;
private MapsActivity mapsActivity;
public address_fragment() {
// Required empty public constructor
}
class AddressResultReceiver extends ResultReceiver{
private int CREATOR;
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
mAddressRequested = false;
updateUIWidgets();
super.onReceiveResult(resultCode, resultData);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_address_fragment, container, false);
}
public void setMapsActivity(MapsActivity mapsActivity){
this.mapsActivity=mapsActivity;
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("mAddressOutput",mAddressOutput);
outState.putBoolean("mAddressRequested",mAddressRequested);
}
#Override
public void onStart() {
super.onStart();
View view = getView();
if(view!=null){
mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
mLocationAddressTextView=(TextView) view.findViewById(R.id.address);
displayAddressOutput();
}
}
public void displayAddressOutput(){
mLocationAddressTextView.setText(mAddressOutput);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mResultReceiver = new AddressResultReceiver(new Handler());
mAddressRequested = false;
mAddressOutput = " ";
updateUIWidgets();
}
public void startIntentService() {
Intent intent = new Intent(getContext(), FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA, mapsActivity.mCurrentLocation);
mapsActivity.startService(intent);
}
public void fetchAddressHandler() {
if (mapsActivity.mGoogleApiClient.isConnected() && mapsActivity.mCurrentLocation != null) {
startIntentService();
}
mAddressRequested = true;
updateUIWidgets();
}
private void updateUIWidgets() {
if (mAddressRequested) {
mProgressBar.setVisibility(ProgressBar.VISIBLE);
} else {
mProgressBar.setVisibility(ProgressBar.GONE);
}
}
}
fragment_address_fragment:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.gio.autostop.address_fragment"
android:background="#android:color/transparent">
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text=""
android:layout_centerHorizontal="true"
android:textSize="22sp"/>
</FrameLayout>
map_interface.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/check_in"
android:layout_marginTop="#dimen/layout_marginTop_button"
android:layout_gravity="end"
android:layout_alignParentBottom="true"
android:layout_weight="1"
/>
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/check_out"
android:layout_marginTop="#dimen/layout_marginTop_button"
android:layout_gravity="end"
android:layout_weight="1"
/>
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</LinearLayout>
what is causing error?
update:
full project: https://github.com/giusha/Autostop
Perhaps the "Error inflating fragment" message is misleading somewhat - but a closer examination of your error stacktrace shows that it is caused by NullPointerException (because you are calling mProgressBar.setVisibility) whereas mProgressBar is actually NULL - because you assigned it to view.findViewById(R.id.progress_bar); which returns null because the view R.id.progress_bar does not exist in the layout file (fragment_address_fragment). So my suggestion would be to move :
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
into the fragment_address_fragment layout file - and then run your code again and see if it works.

Location only updating TextView when app is out of focus

For some reason it only updates the textviews when the app hits onPause, like when I hit the home button, or multitasking button. Can someone help me figure out why that is?
MainActivity.java:
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private String lat, lon;
private TextView longTextView, latTextView;
LocationService locationService = new LocationService(this);
private Intent intentService;
private PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latTextView = (TextView) findViewById(R.id.latitude_textview);
longTextView = (TextView) findViewById(R.id.longitude_textview);
}
#Override
protected void onStart() {
super.onStart();
locationService.buildGoogleApiClient();
locationService.apiConnect();
if (latTextView != null && longTextView != null) {
latTextView.setText( locationService.getLat());
longTextView.setText( locationService.getLon());
Toast.makeText(getApplicationContext(), " Actually got location", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(), "The shit was null fam", Toast.LENGTH_LONG)
.show();
}
}
#Override
protected void onStop() {
super.onStop();
locationService.apiDisconnect();
}
}
LocationService.java:
import android.Manifest;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import static com.google.android.gms.wearable.DataMap.TAG;
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
// ============================================================= Variables
Context context;
Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private String lat, lon;
final static String[] LOCATION_PERMISSIONS = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long UPDATE_FASTEST_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
public static boolean isEnded = false;
public static Boolean requestingLocationUpdates;
protected String lastUpdateTime;
final int GOOGLEAPI_REQUEST_CODE = 24;
private FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
// ============================================================= Constructor
public LocationService(Context context) {
this.context = context;
}
// ============================================================= Getters / Setters
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
// ============================================================= Methods
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public void apiConnect() {
mGoogleApiClient.connect();
}
public void apiDisconnect() {
mGoogleApiClient.disconnect();
}
void updateUI() {
}
// ============================================================= Implemented Location Methods
#Override
public void onLocationChanged(Location location) {
setLat(String.valueOf(location.getLatitude()));
setLon(String.valueOf(location.getLongitude()));
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); // Sets Location to update every second
mLocationRequest.setFastestInterval(UPDATE_FASTEST_INTERVAL_IN_MILLISECONDS); // The fastest location can update is every half-second
startLocationUpdates();
// TODO come back to this to see whats up
/* mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);*/
if (mLastLocation != null) {
setLat(String.valueOf(mLastLocation.getLatitude()));
setLon(String.valueOf(mLastLocation.getLongitude()));
}
}
#Override
public void onConnectionSuspended(int i) {
}
protected void startLocationUpdates() {
/*if (!requestingLocationUpdates) {
requestingLocationUpdates = true;*/
if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) context, LOCATION_PERMISSIONS, GOOGLEAPI_REQUEST_CODE);
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
Log.i(TAG, " startLocationUpdates===");
isEnded = true;
//}
}
// ============================================================= Implemented Service Methods
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 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.
Log.d("LOC", "Service init...");
isEnded = false;
requestingLocationUpdates = false;
lastUpdateTime = "";
buildGoogleApiClient();
if (mGoogleApiClient.isConnected() && requestingLocationUpdates) {
startLocationUpdates();
}
return Service.START_REDELIVER_INTENT;
}
}
The reason why you are not getting the location updated in textview is because your code doesn't have a way for the service to communicate back to the activity.
If you want to obtain location only when the activity is in foreground don't use Service and please look into this google's example for obtaining location and updating on a TextView using fused location provider.
I am not sure why you are using a Service.Use Service only when you want to continuously fetch the location even when the app is running background.
For this use any one of the method mentioned here to inform the activity that a new location has been obtained.LocalBroadcast would be your best bet. Anyway explore the best possible solution that suits your usecase in the previous link.

LocationManager.requestLocationUpdates is never called

I have an application and I want to use the GPS's Location. After implementing what I was taught, I have two files, VirtualAssistantActivity which uses the LocationGPS file. The second file will send the result with an intent received from the first file.
The problem is the TextView that is supposed to be edited after receiving the intent filled with the location.toString() doesn't change. After using the debug feature of Android Studio, I've found that it's like the locationManager's requestLocationUpdate is never called, I can't even get into the new LocationListener's creation.
I am using a Sony XPERIA running Android 5.0, and decided to develop targeting Android 4.0 with API 15.
Here's the VirtualAssistantActivity code :
public class VirtualAssistantActivity extends AppCompatActivity {
private LocationGPS lgps = null;
private BroadcastReceiver mLocationReceiver;
private TextView tvTest = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_virtual_assistant);
tvTest = (TextView) findViewById(R.id.tV_testGeo);
lgps = LocationGPS.get(this.getApplicationContext());
mLocationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent){
Location l = (Location)intent.getParcelableExtra(LocationManager.KEY_LOCATION_CHANGED);
if (l!=null){
tvTest.setText(""+l);
} else {
tvTest.setText("Empty intent");
}
}
};
}#Override
protected void onResume(){
super.onResume();
this.registerReceiver(mLocationReceiver, new IntentFilter(LocationGPS.ACTION_LOCATION));
lgps.startLocationUpdates();
Toast.makeText(getApplicationContext(), "BR Init", Toast.LENGTH_SHORT).show();
}
#Override
public void onPause() {
super.onPause();
//unregisterReceiver(mLocationReceiver);
}
And the LocationGPS's :
public class LocationGPS {
static LocationGPS slocationGPS = null;
Context mAppContext = null;
LocationManager mLocationManager = null;
public static String ACTION_LOCATION = "LOCATION_MSG";
private LocationGPS(Context appContext) {
mAppContext = appContext;
mLocationManager = (LocationManager)appContext.getSystemService(Context.LOCATION_SERVICE);
}
public static LocationGPS get(Context c) {
if (slocationGPS == null) {
slocationGPS = new LocationGPS(c);
}
return slocationGPS;
}
private void broadcastLocation(Location location) {
Intent broadcast = new Intent(this.ACTION_LOCATION);
broadcast.putExtra(LocationManager.KEY_LOCATION_CHANGED, location);
this.mAppContext.sendBroadcast(broadcast);
}
public void startLocationUpdates(){
if (ContextCompat.checkSelfPermission(mAppContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mAppContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager.requestLocationUpdates
(LocationManager.GPS_PROVIDER, 1000, 5, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
//Log.d(this.getClass().getName(), location.toString());
Log.d("GPS", "Latitude " + location.getLatitude() + " et longitude " + location.getLongitude());
Toast.makeText(mAppContext, "Location", Toast.LENGTH_SHORT).show();
broadcastLocation(location);
}
Toast.makeText(mAppContext, "Location", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
I've searched for some solutions, and while it seems to work for everyone, or at least they have some error messages, I don't know what I can do except eventually use Google's APIs, but I would prefer to avoid that. I have checked my permission, they're granted and this is a list of my imports:
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
And the permissions :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Categories

Resources