Location Class returning empty location - java

I'm newcomer in Android development and I wish someone could help me.
My problem is as follow:
gradle
dependencies {
compile 'com.google.android.gms:play-services-maps:15.0.1'
compile 'com.google.android.gms:play-services-location:15.0.1'
}
MainActivity
[...]
local = (CheckBox) findViewById(R.id.local_checkbox);
local.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("DEBUG_INFO","CLICKED");
GPSTracker g = new GPSTracker(MainActivity.this);
if (((CheckBox) v).isChecked()) {
Log.v("DEBUG_INFO","CHECKED");
CheckGpsStatus();
if (GpsStatus == true) {
isLocated = true;
Location l = g.getLocation();
if ((l != null) && (isLocated == true)) {
lat = g.getLocation().getLatitude();
lon = g.getLocation().getLongitude();
Log.v("DEBUG_INFO","DEBUG_INFO:
Latitude: "+ String.valueOf(lat)+ " Longitude: "+
String.valueOf(lon));
}
else if ((l != null) && (isLocated == false)) {
lat = 0.0;
lon = 0.0;
} else {
lat = 0.0;
lon = 0.0;
}
} else {
new AlertDialog.Builder(NovaDenunciaActivity.this, R.style.AlertDialogCustom)
.setTitle("GPS TEXT!")
.setCancelable(false)
.setMessage("PLEASE SET GPS TEXT.")
.setPositiveButton("CLOSE",new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}).show();
local.toggle();
}
} else {
isLocated = false;
}
}
});
}//onCreate
public void CheckGpsStatus(){
locationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
GpsStatus =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v("CHECKBOX","MARCADO");
}
} //Code end's
GPSTracker.java
[...]
public class GPSTracker extends Activity implements LocationListener {
Context context;
/*variables*/
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public GPSTracker(Context c) {
context = c;
}
/*variables*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
} //Oncreate end's?
public Location getLocation() {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "No Permission Text!\nPlease allow
permissions text.", Toast.LENGTH_LONG).show();
return null;
}
//Get the location manager
locationManager = (LocationManager)
context.getSystemService(context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
Log.v("DEBUG_INFO:", "Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
//latituteField.setText("Location not available");
//longitudeField.setText("Location not available");
Log.v("DEBUG_INFO:", "Latitude: not available");
Log.v("DEBUG_INFO:", "Longitude: not available");
}
return location;
}
#Override
protected void onResume() {
super.onResume();
Log.v("DEBUG_INFO:", "REQUESTING LOCATION UPDATES");
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
Log.v("DEBUG_INFO:","STOP LOCATION UPDATES");
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
//latituteField.setText(String.valueOf(lat));
// longitudeField.setText(String.valueOf(lng));
Log.v("DEBUG_INFO:","Latitude: "+String.valueOf(lat));
Log.v("DEBUG_INFO:","Longitude: "+String.valueOf(lng));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(context, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(context, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
But when I click on checkbox the logcat (verbose) shows me the following:
V/DEBUG_INFO:: Latitude: not available
V/DEBUG_INFO:: Longitude: not available
The program should get latitude and longitude, if it does not exist it should call the locationManager.requestLocationUpdates(provider, 0, 0, this);
But I do not know what I'm doing wrong. Can someone help me?

Related

I don' know please help... Unable to start activity ComponentInfo{...}: java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am a Korean university student.
I use a translator.
Please excuse me for not being soft.
Failed to resolve issue while writing code, asking questions
Please help me.
The code below is quite simple and the only goal is to navigate from MainActivity.java to Mian2Activity.java However, I've been looking for a solution to this on a lot of tutorial and I really don't get what I'm doing wrong...
this is Main2Activity Code
public class Main2Activity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleApiClient mGoogleApiClient = null;
private GoogleMap mGoogleMap = null;
private Marker currentMarker = null;
private static final String TAG = "googlemap_example";
private static final int GPS_ENABLE_REQUEST_CODE = 2001;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2002;
private static final int UPDATE_INTERVAL_MS = 1000; // 1초
private static final int FASTEST_UPDATE_INTERVAL_MS = 500; // 0.5초
private AppCompatActivity mActivity;
boolean askPermissionOnceAgain = false;
boolean mRequestingLocationUpdates = false;
Location mCurrentLocatiion;
boolean mMoveMapByUser = true;
boolean mMoveMapByAPI = true;
LatLng currentPosition;
LocationRequest locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL_MS)
.setFastestInterval(FASTEST_UPDATE_INTERVAL_MS);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate");
mActivity = this;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
Log.d(TAG, "onResume : call startLocationUpdates");
if (!mRequestingLocationUpdates) startLocationUpdates();
}
//앱 정보에서 퍼미션을 허가했는지를 다시 검사해봐야 한다.
if (askPermissionOnceAgain) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
askPermissionOnceAgain = false;
checkPermissions();
}
}
}
private void startLocationUpdates() {
if (!checkLocationServicesStatus()) {
Log.d(TAG, "startLocationUpdates : call showDialogForLocationServiceSetting");
showDialogForLocationServiceSetting();
}else {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "startLocationUpdates : 퍼미션 안가지고 있음");
return;
}
Log.d(TAG, "startLocationUpdates : call FusedLocationApi.requestLocationUpdates");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
mRequestingLocationUpdates = true;
mGoogleMap.setMyLocationEnabled(true);
}
}
private void stopLocationUpdates() {
Log.d(TAG,"stopLocationUpdates : LocationServices.FusedLocationApi.removeLocationUpdates");
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mRequestingLocationUpdates = false;
}
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "onMapReady :");
mGoogleMap = googleMap;
//런타임 퍼미션 요청 대화상자나 GPS 활성 요청 대화상자 보이기전에
//지도의 초기위치를 서울로 이동
setDefaultLocation();
//mGoogleMap.getUiSettings().setZoomControlsEnabled(false);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mGoogleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener(){
#Override
public boolean onMyLocationButtonClick() {
Log.d( TAG, "onMyLocationButtonClick : 위치에 따른 카메라 이동 활성화");
mMoveMapByAPI = true;
return true;
}
});
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
Log.d( TAG, "onMapClick :");
}
});
mGoogleMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
#Override
public void onCameraMoveStarted(int i) {
if (mMoveMapByUser == true && mRequestingLocationUpdates){
Log.d(TAG, "onCameraMove : 위치에 따른 카메라 이동 비활성화");
mMoveMapByAPI = false;
}
mMoveMapByUser = true;
}
});
mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
}
});
}
#Override
public void onLocationChanged(Location location) {
currentPosition
= new LatLng( location.getLatitude(), location.getLongitude());
Log.d(TAG, "onLocationChanged : ");
String markerTitle = getCurrentAddress(currentPosition);
String markerSnippet = "위도:" + String.valueOf(location.getLatitude())
+ " 경도:" + String.valueOf(location.getLongitude());
//현재 위치에 마커 생성하고 이동
setCurrentLocation(location, markerTitle, markerSnippet);
mCurrentLocatiion = location;
}
#Override
protected void onStart() {
if(mGoogleApiClient != null && mGoogleApiClient.isConnected() == false){
Log.d(TAG, "onStart: mGoogleApiClient connect");
mGoogleApiClient.connect();
}
super.onStart();
}
#Override
protected void onStop() {
if (mRequestingLocationUpdates) {
Log.d(TAG, "onStop : call stopLocationUpdates");
stopLocationUpdates();
}
if ( mGoogleApiClient.isConnected()) {
Log.d(TAG, "onStop : mGoogleApiClient disconnect");
mGoogleApiClient.disconnect();
}
super.onStop();
}
#Override
public void onConnected(Bundle connectionHint) {
if ( mRequestingLocationUpdates == false ) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasFineLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (hasFineLocationPermission == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(mActivity,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
} else {
Log.d(TAG, "onConnected : 퍼미션 가지고 있음");
Log.d(TAG, "onConnected : call startLocationUpdates");
startLocationUpdates();
mGoogleMap.setMyLocationEnabled(true);
}
}else{
Log.d(TAG, "onConnected : call startLocationUpdates");
startLocationUpdates();
mGoogleMap.setMyLocationEnabled(true);
}
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed");
setDefaultLocation();
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended");
if (cause == CAUSE_NETWORK_LOST)
Log.e(TAG, "onConnectionSuspended(): Google Play services " +
"connection lost. Cause: network lost.");
else if (cause == CAUSE_SERVICE_DISCONNECTED)
Log.e(TAG, "onConnectionSuspended(): Google Play services " +
"connection lost. Cause: service disconnected");
}
public String getCurrentAddress(LatLng latlng) {
//지오코더... GPS를 주소로 변환
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(
latlng.latitude,
latlng.longitude,
1);
} catch (IOException ioException) {
//네트워크 문제
Toast.makeText(this, "지오코더 서비스 사용불가", Toast.LENGTH_LONG).show();
return "지오코더 서비스 사용불가";
} catch (IllegalArgumentException illegalArgumentException) {
Toast.makeText(this, "잘못된 GPS 좌표", Toast.LENGTH_LONG).show();
return "잘못된 GPS 좌표";
}
if (addresses == null || addresses.size() == 0) {
Toast.makeText(this, "주소 미발견", Toast.LENGTH_LONG).show();
return "주소 미발견";
} else {
Address address = addresses.get(0);
return address.getAddressLine(0).toString();
}
}
public boolean checkLocationServicesStatus() {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void setCurrentLocation(Location location, String markerTitle, String markerSnippet) {
mMoveMapByUser = false;
if (currentMarker != null) currentMarker.remove();
LatLng currentLatLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLatLng);
markerOptions.title(markerTitle);
markerOptions.snippet(markerSnippet);
markerOptions.draggable(true);
//구글맵의 디폴트 현재 위치는 파란색 동그라미로 표시
//마커를 원하는 이미지로 변경하여 현재 위치 표시하도록 수정 fix - 2017. 11.27
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher));
currentMarker = mGoogleMap.addMarker(markerOptions);
if ( mMoveMapByAPI ) {
Log.d( TAG, "setCurrentLocation : mGoogleMap moveCamera "
+ location.getLatitude() + " " + location.getLongitude() ) ;
// CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(currentLatLng, 15);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(currentLatLng);
mGoogleMap.moveCamera(cameraUpdate);
}
}
public void setDefaultLocation() {
mMoveMapByUser = false;
//디폴트 위치, Seoul
LatLng DEFAULT_LOCATION = new LatLng(37.56, 126.97);
String markerTitle = "위치정보 가져올 수 없음";
String markerSnippet = "위치 퍼미션과 GPS 활성 요부 확인하세요";
if (currentMarker != null) currentMarker.remove();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(DEFAULT_LOCATION);
markerOptions.title(markerTitle);
markerOptions.snippet(markerSnippet);
markerOptions.draggable(true);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
currentMarker = mGoogleMap.addMarker(markerOptions);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(DEFAULT_LOCATION, 15);
mGoogleMap.moveCamera(cameraUpdate);
}
//여기부터는 런타임 퍼미션 처리을 위한 메소드들
#TargetApi(Build.VERSION_CODES.M)
private void checkPermissions() {
boolean fineLocationRationale = ActivityCompat
.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION);
int hasFineLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (hasFineLocationPermission == PackageManager
.PERMISSION_DENIED && fineLocationRationale)
showDialogForPermission("앱을 실행하려면 퍼미션을 허가하셔야합니다.");
else if (hasFineLocationPermission
== PackageManager.PERMISSION_DENIED && !fineLocationRationale) {
showDialogForPermissionSetting("퍼미션 거부 + Don't ask again(다시 묻지 않음) " +
"체크 박스를 설정한 경우로 설정에서 퍼미션 허가해야합니다.");
} else if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "checkPermissions : 퍼미션 가지고 있음");
if ( mGoogleApiClient.isConnected() == false) {
Log.d(TAG, "checkPermissions : 퍼미션 가지고 있음");
mGoogleApiClient.connect();
}
}
}
#Override
public void onRequestPermissionsResult(int permsRequestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
if (permsRequestCode
== PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION && grantResults.length > 0) {
boolean permissionAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (permissionAccepted) {
if ( mGoogleApiClient.isConnected() == false) {
Log.d(TAG, "onRequestPermissionsResult : mGoogleApiClient connect");
mGoogleApiClient.connect();
}
} else {
checkPermissions();
}
}
}
#TargetApi(Build.VERSION_CODES.M)
private void showDialogForPermission(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
builder.setTitle("알림");
builder.setMessage(msg);
builder.setCancelable(false);
builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ActivityCompat.requestPermissions(mActivity,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
});
builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.create().show();
}
private void showDialogForPermissionSetting(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
builder.setTitle("알림");
builder.setMessage(msg);
builder.setCancelable(true);
builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
askPermissionOnceAgain = true;
Intent myAppSettings = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + mActivity.getPackageName()));
myAppSettings.addCategory(Intent.CATEGORY_DEFAULT);
myAppSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mActivity.startActivity(myAppSettings);
}
});
builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.create().show();
}
//여기부터는 GPS 활성화를 위한 메소드들
private void showDialogForLocationServiceSetting() {
AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
builder.setTitle("위치 서비스 비활성화");
builder.setMessage("앱을 사용하기 위해서는 위치 서비스가 필요합니다.\n"
+ "위치 설정을 수정하실래요?");
builder.setCancelable(true);
builder.setPositiveButton("설정", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent
= new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(callGPSSettingIntent, GPS_ENABLE_REQUEST_CODE);
}
});
builder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case GPS_ENABLE_REQUEST_CODE:
//사용자가 GPS 활성 시켰는지 검사
if (checkLocationServicesStatus()) {
if (checkLocationServicesStatus()) {
Log.d(TAG, "onActivityResult : 퍼미션 가지고 있음");
if ( mGoogleApiClient.isConnected() == false ) {
Log.d( TAG, "onActivityResult : mGoogleApiClient connect ");
mGoogleApiClient.connect();
}
return;
}
}
break;
}
}
}
and this MainActivity Code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bttest1 = (Button)findViewById(R.id.bttest1);
bttest1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),Main2Activity.class);
startActivity(intent);
}
});
}
}
Unable to start activity ComponentInfo{...}: java.lang.NullPointerException
An error occurs here.(Main2Activity)
mapFragment.getMapAsync(this);
What is the reason for the error?
Help me, please.
In your Main2Activity onCreate, you use setContentView(R.layout.activity_main);
It seems to be layout from MainActivity, not Main2Activity. You should make something like R.layout.activity_main2 for your second activity.
Then, your code
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
probably won't find view with ID R.id.map, because that view isn't part of first MainActivity layout.

Android GPS works at first but later returns null values

This is a simple GPS logger. The latitude and longitude values get logged into an SQLite database every 10 seconds.
This works when my app is run for the first time, but when the app is run again the location values are null and my table never gets updated with the values.
public class GPSService extends Service {
public static final String TAG = GPSService.class.getSimpleName();
private static final int ONGOING_NOTIFICATION_ID = 1000;
public static final String GPS_WAKE_LOCK = "GPSWakeLock";
public static final int GPS_TIME_THRESHOLD = 10000; // 10 sec
public static final int GPS_DISTANCE_THRESHOLD = 10; // 10 meters
public static EventBus bus = EventBus.getDefault();
private LocationManager lm;
private LocationManager locationManager2;
private LocationListener locationListener;
private Location location = null;
private Timer timer;
private DumpTask dumpTask = null;
private DatabaseHelper myDb = null;
private static boolean active = false;
private PowerManager.WakeLock wakeLock = null;
public static Double Latitude;
public static Double Longitude;
public static int TotalNoOfStations;
public float[] result = new float[2];
public int k;
public static Boolean SwitchOffAlarmService=false;
#Override
public void onCreate() {
super.onCreate();
bus.register(this);
timer = new Timer();
myDb = DatabaseHelper.getInstance(this);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager2 = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
Log.d(TAG, "onCreate ");
k=0;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
Log.d(TAG, "destroyed");
bus.unregister(this);
timer.cancel();
stopService(new Intent(this,GPSService.class));
super.onDestroy();
}
#SuppressWarnings("unused")
public void onEvent(GPSLoggerCommand e) {
if (e.command == GPSLoggerCommand.START && !active) {
Log.d(TAG, "start gps logger");
getRouteDetails();
MainActivity.LocationServiceStarted=true;
getLatLonFromDB();
try {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_TIME_THRESHOLD, GPS_DISTANCE_THRESHOLD, locationListener);
}catch (SecurityException ex){
Log.e(TAG, "onEvent " + ex.toString());
}
dumpTask = new DumpTask();
timer.schedule(dumpTask, GPS_TIME_THRESHOLD, GPS_TIME_THRESHOLD);
active = true;
} else if (e.command == GPSLoggerCommand.STOP && active) {
Log.d(TAG, "stop gps logger");
dumpTask.cancel();
try {
lm.removeUpdates(locationListener);
}catch(SecurityException ex){
Log.e(TAG, "onEvent " + ex);
}
bus.post(new StatusReply("total rows " + myDb.getRowsCount()));
stopForeground(true);
active = false;
locationManager2.sendExtraCommand(LocationManager.GPS_PROVIDER,"delete_aiding_data",null);
Bundle bundle = new Bundle();
locationManager2.sendExtraCommand("gps","force_xtra_injection",bundle);
locationManager2.sendExtraCommand("gps","fource_time_injection",bundle);
stopService(new Intent(this,GPSService.class));
} else if (e.command == GPSLoggerCommand.STATUS) {
Log.d(TAG, "onEvent send message " + active);
bus.post(new GPSLoggerStatus(active));
}
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
if (loc != null) {
Log.d(TAG, "onLocationChanged " + loc.getLatitude() + ":" + loc.getLongitude());
location = loc;
}
}
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled");
Toast.makeText(GPSService.this, "Service Canceled due to GPS being Disabled!!", Toast.LENGTH_SHORT).show();
GPSLoggerCommand c;
c = new GPSLoggerCommand(GPSLoggerCommand.STOP);
bus.post(c);
MainActivity.GPServiceStarted=false;
MainActivity.LocationServiceStarted=false;
}
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
String showStatus = null;
if (status == LocationProvider.AVAILABLE)
showStatus = "Available";
if (status == LocationProvider.TEMPORARILY_UNAVAILABLE)
showStatus = "Temporarily Unavailable";
if (status == LocationProvider.OUT_OF_SERVICE)
showStatus = "Out of Service";
Log.d(TAG, "onStatusChanged " + showStatus);
}
}
public class DumpTask extends TimerTask {
#Override
public void run() {
Log.d(TAG, "dump to base");
if (location != null) {
// write to database
}
}
}
public static void StopServiceFunction()
{
GPSLoggerCommand c;
c = new GPSLoggerCommand(GPSLoggerCommand.STOP);
bus.post(c);
MainActivity.GPServiceStarted=false;
MainActivity.LocationServiceStarted=false;
active = false;
}
}
implement GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
in your activity and past below code in override methods
#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) {
// 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;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
} else {
mCurrentLatitude = location.getLatitude();
mCurrentLongitude = location.getLongitude();
Toast.makeText(this, mCurrentLongitude + " * ********"+mCurrentLatitude, Toast.LENGTH_LONG).show();
}
}

Android Wear App java.lang.OutOfMemoryError: Failed to allocate

I had a problem. I want to make an Android App for my Android Wear device. I want to get the latitude and longitude of my current location. But when I run the applicatie I got this error:
03-22 11:14:00.096 29013-29013/? E/AndroidRuntime: Error reporting crash
java.lang.OutOfMemoryError: Failed to allocate a 52435096 byte allocation with 2097152 free bytes and 32MB until OOM
at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:125)
at java.lang.StringBuffer.append(StringBuffer.java:278)
at java.io.StringWriter.write(StringWriter.java:123)
at com.android.internal.util.FastPrintWriter.flushLocked(FastPrintWriter.java:358)
at com.android.internal.util.FastPrintWriter.appendLocked(FastPrintWriter.java:303)
at com.android.internal.util.FastPrintWriter.write(FastPrintWriter.java:625)
at com.android.internal.util.FastPrintWriter.append(FastPrintWriter.java:658)
at java.io.PrintWriter.append(PrintWriter.java:691)
at java.io.PrintWriter.append(PrintWriter.java:687)
at java.io.Writer.append(Writer.java:198)
at java.lang.Throwable.printStackTrace(Throwable.java:324)
at java.lang.Throwable.printStackTrace(Throwable.java:300)
at android.util.Log.getStackTraceString(Log.java:343)
at com.android.internal.os.RuntimeInit.Clog_e(RuntimeInit.java:61)
at com.android.internal.os.RuntimeInit.-wrap0(RuntimeInit.java)
at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:86)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
This is my code:
MainActivity.java
public class MainActivity extends Activity {
private TextView tvHuidigeLocatie;
private Button btSetHuidigeLocatie;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
onClickInfoButtonListener();
}
});
}
private void onClickInfoButtonListener() {
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
tvHuidigeLocatie = (TextView) stub.findViewById(R.id.tvHuidigeLocatie);
btSetHuidigeLocatie = (Button) stub.findViewById(R.id.btnSetHuidigeLocatie);
btSetHuidigeLocatie.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
tvHuidigeLocatie.setText("" + latitude + ", " + longitude);
}else{
gps.showSettingsAlert();
}
}
}
);
}
}
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
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 locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return location;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
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;
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation();
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS in settings");
alertDialog.setMessage("GPS staat niet aan, Wilt u naar uw instellingen gaan?");
alertDialog.setPositiveButton("Instellingen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Annuleer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#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 IBinder onBind(Intent intent) {
return null;
}
}
I hope anyone see the problem and can help me with this problem.
android:largeHeap="true"
In your android manifest, hope this will solve your problem.
http://developer.android.com/guide/topics/manifest/application-element.html#largeHeap

Android requestLocationUpdates doesn't call never to onLocationChanged in some terminals

I'm working on an app that uses the network location, but i've recived some users feedback that says that they never pass this block of code, i'm assuming that the problem is that location changed is never called, but it only happens in a few diveces, and i cant force the failure in mine.
Is there any chance to solve it or control it? showing a toast saying that is unable to find location, will work for me...
I know that if the user reboot his phone, the location will work, but that it's not a solution for the users
I left the code right here...
final LocationManager lm = (LocationManager) thisOfActivity
.getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// SOME STUFF
Location net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
final LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
lm.removeUpdates(this);
// SOME STUFF
myTask task = new myTask();
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
public void onProviderDisabled(String provider) {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(
thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
switch( status ) {
case LocationProvider.AVAILABLE:
Log.e("LocProv", "AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.e("LocProv", "OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.e("LocProv", "TEMPORARILY_UNAVAILABLE");
break;
}
}
};
if (network_enabled) {
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
} else {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_LONG).show();
}
I've tried with the next idea, i think it could work, at least to get a location and not keep the user waiting.
final LocationManager lm = (LocationManager) thisOfActivity
.getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// SOME STUFF
LocationListener locationListenerNetwork = null;
// Constructor
class MyThread implements Runnable {
LocationListener locationListenerNetwork;
public MyThread(LocationListener lln) {
locationListenerNetwork = lln;
}
public void run() {
}
}
final Handler myHandler = new Handler();
//Here's a runnable/handler combo
final Runnable MyRunnable = new MyThread(locationListenerNetwork)
{
#Override
public void run() {
if (locationListenerNetwork != null)
lm.removeUpdates(locationListenerNetwork);
Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null)
{
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
ListView tweetList = (ListView) thisOfActivity
.findViewById(R.id.tweets);
jsonUpdateAsyncTask task = new jsonUpdateAsyncTask(
thisOfActivity, Double.toString(lat),
Double.toString(lon), tweetList);
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
else
{
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_LONG).show();
}
}
};
locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
lm.removeUpdates(this);
myHandler.removeCallbacks(MyRunnable);
ListView tweetList = (ListView) thisOfActivity
.findViewById(R.id.tweets);
jsonUpdateAsyncTask task = new jsonUpdateAsyncTask(
thisOfActivity, Double.toString(lat),
Double.toString(lon), tweetList);
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
public void onProviderDisabled(String provider) {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(
thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
switch( status ) {
case LocationProvider.AVAILABLE:
Log.e("LocProv", "AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.e("LocProv", "OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.e("LocProv", "TEMPORARILY_UNAVAILABLE");
break;
}
}
};
if (network_enabled) {
myHandler.postDelayed(MyRunnable, 10 * 1000);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0,locationListenerNetwork);
} else {
// MORE STUFF
opinions?

User location cannot be found

I post a question not long ago. Basically what I am trying to do is have my location manager return my longitude and latitude. My getBestProvider() method returns network, however my locationManager.getLastKnownLocation(provider) returns null. As you can see I've implemented the listener. I must have done something wrong.
Here is the code.
public class Activity1 extends Activity implements LocationListener {
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
readFile();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println(provider);
System.out.println(locationManager.getProviders(criteria, false));
System.out.println(locationManager.getProvider("network"));
System.out.println(locationManager.getAllProviders());
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
} else {
System.out.println("Provider not available");
System.out.println("Provider not available");
}
}#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disenabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.NETWORK_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
}
private void updateWithNewLocation(Location location){
String latLongString;TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else { latLongString = "No location found"; }
}

Categories

Resources