Google Maps API Key Error when launching Activity - java

I am trying to build an application that uses a Google maps activity using Android Studio.
I am facing issue: every time I try to launch the activity the app crashes. When I am using an emulator with SDK 24, the activity launches, it requires my permission and then it gives me an authentication error, even though I placed the correct API key.
On an emulator with SDK 26 the activity doesn't even launch and it crashes instantly.
Can you please help with this?
MapsActivity
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
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.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.util.ArrayList;
#SuppressWarnings("unchecked")
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onMapReady: map is ready");
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
private static final String TAG = "MapsActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
//vars
private Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getLocationPermission();
}
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionsGranted){
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM);
}else{
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(MapsActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
private void moveCamera(LatLng latLng, float zoom){
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap(){
Log.d(TAG, "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = true;
initMap();
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0){
for(int i = 0; i < grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
}
Error from the logcat for an emulator with SDK 24:
06-21 16:52:53.625 13392-13392/com.example.raluca.geoloc.feature E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:52:55.011 1314-1321/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
06-21 16:52:55.452 13392-13560/com.example.raluca.geoloc.feature E/Google Maps Android API: Authorization failure. Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
06-21 16:52:55.454 13392-13560/com.example.raluca.geoloc.feature E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
Ensure that the "Google Maps Android API v2" is enabled.
Ensure that the following Android Key exists:
API Key: XXX_Key
Android Application (<cert_fingerprint>;<package_name>): D3:DF:7B:C7:09:CA:00:9F:32:DD:93:98:D6:E2:09:A1:18:B1:F6:6B;com.example.raluca.geoloc.feature
06-21 16:53:01.866 13392-13392/com.example.raluca.geoloc.feature E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.raluca.geoloc.feature, PID: 13392
java.lang.RuntimeException: Failure delivering result ResultInfo{who=#android:requestPermissions:, request=1234, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4053)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at com.example.raluca.geoloc.feature.MapsActivity.initMap(MapsActivity.java:110)
at com.example.raluca.geoloc.feature.MapsActivity.onRequestPermissionsResult(MapsActivity.java:154)
at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:7067)
at android.app.Activity.dispatchActivityResult(Activity.java:6919)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096) 
at android.app.ActivityThread.-wrap20(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
06-21 16:53:02.076 1314-1322/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
06-21 16:53:05.957 8187-8220/? E/InputDispatcher: channel '65bcf76 com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.LoginActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
06-21 16:53:05.957 8187-8220/? E/InputDispatcher: channel '23dfb3a com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.MapsActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
06-21 16:53:26.978 8543-12462/? E/NetworkScheduler: Unrecognised action provided: android.intent.action.PACKAGE_REMOVED
06-21 16:53:27.653 8543-11730/? E/NetworkScheduler: Unrecognised action provided: android.intent.action.PACKAGE_REPLACED
06-21 16:53:28.495 8906-13710/? E/FontsPackageChangeOp: Error adding manifest dependency for newly downloaded font {Press Start 2P, wdth 100.0, wght 400, ital 0.0, bestEffort false}
06-21 16:53:28.507 8906-13053/? E/FontDisk: Error inserting metadata for Press Start 2P
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/user/0/com.google.android.gms/databases/metadata.db
at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1442)
at vdo.run(Unknown Source)
at ovb.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):27)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at pbc.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431))
at java.lang.Thread.run(Thread.java:761)
06-21 16:53:29.228 13637-13764/? E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:53:29.611 13637-13764/? E/Finsky: [464] com.google.android.finsky.am.c.a(34): Unable to build selector: /storage/emulated/0/Download/marketenvs.csv (No such file or directory)
06-21 16:53:30.423 13637-13637/? E/Finsky: [1] com.google.android.finsky.wear.y.a(3): onConnectionFailed: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
06-21 16:53:35.484 13637-13828/? E/Finsky: [483] com.google.android.finsky.splitinstallservice.ad.a(3): Can't schedule deferred install. No modules found.
06-21 16:53:36.939 13637-13637/? E/Finsky: [1] com.google.android.finsky.wear.y.a(3): onConnectionFailed: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
06-21 16:53:37.759 13836-13836/? E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:53:38.320 8906-8965/? E/AsyncOpDispatcher: Unable to get current module info in ModuleManager created with non-module Context
06-21 16:53:39.373 8543-13891/? E/BluetoothAdapter: Bluetooth binder is null
06-21 16:53:39.503 8543-13891/? E/GCoreUlr: java.lang.IllegalStateException: Missing location or location status: 3016643, -1, 3781840, 7160153
at awot.a(:com.google.android.gms#12685026#12.6.85 (040700-197041431):387)
at awos.a(:com.google.android.gms#12685026#12.6.85 (040700-197041431):12)
at awos.handleMessage(:com.google.android.gms#12685026#12.6.85 (040700-197041431):7)
at oup.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):6)
at ovb.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):27)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at pbc.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431))
at java.lang.Thread.run(Thread.java:761)
06-21 16:53:40.868 12038-13901/? E/art: The String#value field is not present on Android versions >= 6.0
06-21 16:58:10.742 8543-13895/? E/BluetoothAdapter: Bluetooth binder is null
06-21 16:58:10.743 8543-13895/? E/GCoreUlr: java.lang.IllegalStateException: Missing location or location status: 3016643, -1, 3781840, 7431479
at awot.a(:com.google.android.gms#12685026#12.6.85 (040700-197041431):387)
at awos.a(:com.google.android.gms#12685026#12.6.85 (040700-197041431):12)
at awos.handleMessage(:com.google.android.gms#12685026#12.6.85 (040700-197041431):7)
at oup.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):6)
at ovb.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431):27)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at pbc.run(:com.google.android.gms#12685026#12.6.85 (040700-197041431))
at java.lang.Thread.run(Thread.java:761)
06-21 17:07:17.957 8543-9125/? E/WakeLock: release without a matched acquire!
06-21 17:07:18.371 14053-14083/? E/SQLiteLog: (1) no such table: mmsconfig
06-21 17:07:18.376 14053-14083/? E/Babel_SMS: canonicalizeMccMnc: invalid mccmnc nullnull
Error from the logcat for an emulator with SDK 26:
06-21 17:13:05.646 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:14.440 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.440 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.441 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.441 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.443 1929-2545/com.android.systemui E/ResourcesManager: failed to add asset path /data/app/com.example.raluca.geoloc.feature-sqq-lfGT9yN1ITtLhodWNA==/base.apk
06-21 17:13:14.899 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:15.787 5360-5360/com.example.raluca.geoloc.feature E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.raluca.geoloc.feature, PID: 5360
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.raluca.geoloc.feature/com.example.raluca.geoloc.feature.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at com.example.raluca.geoloc.feature.MapsActivity.initMap(MapsActivity.java:110)
at com.example.raluca.geoloc.feature.MapsActivity.getLocationPermission(MapsActivity.java:123)
at com.example.raluca.geoloc.feature.MapsActivity.onCreate(MapsActivity.java:67)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
06-21 17:13:16.975 1510-1510/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:16.976 1510-1510/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:16.978 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:16.990 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:16.990 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-21 17:13:16.998 2349-5365/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
06-21 17:13:17.682 2308-2853/com.google.android.gms.persistent E/ctxmgr: [ProducerStatusImpl]updateStateForNewContextData: inactive, contextName=7
06-21 17:13:17.794 2308-2308/com.google.android.gms.persistent E/BeaconBle: Missing BluetoothAdapter
06-21 17:13:17.895 2308-2308/com.google.android.gms.persistent E/BeaconBle: Scan couldn't start for Places
06-21 17:13:22.074 1510-1650/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:22.074 1510-1650/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:22.074 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:22.084 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:22.084 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-21 17:13:22.086 2349-5365/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
06-21 17:13:27.115 1510-1648/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:27.116 1510-1648/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:27.116 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:27.123 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:27.124 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-21 17:13:27.714 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:27.737 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:31.070 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:31.084 1744-1775/system_process E/memtrack: Couldn't load memtrack module
06-21 17:13:32.154 1510-1650/? E/AudioFlinger: not enough memory for AudioTrack size=131296
06-21 17:13:32.155 1510-1650/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
06-21 17:13:32.155 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
06-21 17:13:32.157 2349-5365/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
06-21 17:13:32.157 2349-5365/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
Msps Activity Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<fragment 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=".MapsActivity"
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
/>
</RelativeLayout>
Gradle
android {
compileSdkVersion 26
defaultConfig {
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
debuggable true
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation project(':base')
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.github.orhanobut:logger:1.12'
compile 'com.google.android.gms:play-services-maps:11.6.0'
implementation "com.google.android.gms:play-services-location:11.6.0"
}

You have to initialize your map in onCreate() as done here and this will do your job.
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback
{
private GoogleMap mMap;
#Override
public void onMapReady(GoogleMap googleMap)
{
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d("Mapready", "onMapReady: map is ready");
mMap = googleMap;
if (mLocationPermissionsGranted)
{
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
private static final String TAG = "MapsActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
//vars
private Boolean mLocationPermissionsGranted = false;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
initMap();
getLocationPermission();
}
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionsGranted){
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM);
}else{
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(MapsActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
private void moveCamera(LatLng latLng, float zoom){
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap(){
Log.d(TAG, "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = true;
initMap();
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0){
for(int i = 0; i < grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
}
Also, do the following changes in the manifest file:-
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>

Create a New Project and check on the "Use androidx.* artifacts" and it will work fine.
Should use API 23 or newer.

Related

MediaRecorder stop() failed

I know there are a few of these on SO already but none of them really were able to help my issue, but when I am running the code and start recording audio and then press my stop button it always fails because it is in the wrong state. I am not sure how I would go about fixing my states for this.
Here is my MainActivity.java code:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.IOException;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class MainActivity extends AppCompatActivity {
Button buttonStartRecording, buttonStopRecording, buttonPlayLastRecordAudio,
buttonStopPlayingRecording;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder;
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer;
AudioManager audioManager;
boolean isAudioPlayInSameDevice = true;
// AudioRouter audioRouter;
RadioGroup mRadioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStartRecording = (Button) findViewById(R.id.start_recording);
buttonStopRecording = (Button) findViewById(R.id.stop_rec);
buttonPlayLastRecordAudio = (Button) findViewById(R.id.play_last_rec);
buttonStopPlayingRecording = (Button) findViewById(R.id.stop_playing_btn);
// mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
buttonStopRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
buttonStartRecording.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View view) {
// Check audio permission
if (checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "AudioRecording.3gp";
// Start Media recorder
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStartRecording.setEnabled(false);
buttonStopRecording.setEnabled(true);
Toast.makeText(MainActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStopRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
// Stop Media recorder
mediaRecorder.stop();
Toast.makeText(MainActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
int selectedId = 1;
if (selectedId == 1) {
isAudioPlayInSameDevice = true;
} else {
isAudioPlayInSameDevice = false;
}
// if you want to play audio on your Mobile speaker then set isAudioPlayInSameDevice true
// and if you want to play audio to connected device then set isAudioPlayInSameDevice false.
if (isAudioPlayInSameDevice) {
audioManager.setMode(audioManager.STREAM_MUSIC);
audioManager.setSpeakerphoneOn(true);
} else {
audioManager.setSpeakerphoneOn(false);
audioManager.setMode(audioManager.MODE_NORMAL);
}
audioManager.setBluetoothScoOn(false);
audioManager.stopBluetoothSco();
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer = new MediaPlayer();
try {
// Start media player
System.out.println("Recorded Audio Path-" + AudioSavePathInDevice);
mediaPlayer.setDataSource(AudioSavePathInDevice);
if (isAudioPlayInSameDevice) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if (mediaPlayer != null) {
// Stop Media Player
mediaPlayer.stop();
mediaPlayer.release();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
MediaRecorderReady();
}
}
}
});
}
private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
System.out.println("ANDROID Audio SCO state: " + state);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
/*
* Now the connection has been established to the bluetooth device.
* Record audio or whatever (on another thread).With AudioRecord you can record with an object created like this:
* new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
* AudioFormat.ENCODING_PCM_16BIT, audioBufferSize);
*
* After finishing, don't forget to unregister this receiver and
* to stop the bluetooth connection with am.stopBluetoothSco();
*/
}
}
};
#RequiresApi(api = Build.VERSION_CODES.O)
public void MediaRecorderReady() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_2_TS);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
registerReceiver(mBluetoothScoReceiver, intentFilter);
audioManager = (AudioManager) getApplicationContext().getSystemService(getApplicationContext().AUDIO_SERVICE);
// Start Bluetooth SCO.
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(true);
audioManager.startBluetoothSco();
// Stop Speaker.
audioManager.setSpeakerphoneOn(false);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBluetoothScoReceiver);
// Stop Bluetooth SCO.
audioManager.stopBluetoothSco();
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(false);
// Start Speaker.
audioManager.setSpeakerphoneOn(true);
}
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
// if (StoragePermission && RecordPermission) {
// Toast.makeText(BluetoothAudioRecorder.this, "Permission Granted",
// Toast.LENGTH_LONG).show();
// } else {
// Toast.makeText(BluetoothAudioRecorder.this,"Permission Denied",Toast.LENGTH_LONG).show();
// }
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
}
And then my logcat of when the error occurs:
2019-11-24 11:26:54.440 29627-29683/com.example.esense_application E/libc: Access denied finding property "vendor.gralloc.disable_ahardware_buffer"
2019-11-24 11:26:54.435 29627-29627/com.example.esense_application W/RenderThread: type=1400 audit(0.0:17779): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=24699 scontext=u:r:untrusted_app:s0:c7,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
2019-11-24 11:26:54.487 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:26:54.487 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 2
2019-11-24 11:26:54.868 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:26:57.769 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: java.io.FileNotFoundException: /storage/emulated/0/AudioRecording.3gp: open failed: EACCES (Permission denied)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at libcore.io.IoBridge.open(IoBridge.java:496)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:289)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:152)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.media.MediaRecorder.prepare(MediaRecorder.java:1046)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at com.example.esense_application.MainActivity$1.onClick(MainActivity.java:67)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.performClick(View.java:7140)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.performClickInternal(View.java:7117)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.access$3500(View.java:801)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View$PerformClick.run(View.java:27351)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.os.Handler.handleCallback(Handler.java:883)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.os.Handler.dispatchMessage(Handler.java:100)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.os.Looper.loop(Looper.java:214)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7356)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.Linux.open(Native Method)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:252)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7255)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.IoBridge.open(IoBridge.java:482)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: ... 15 more
2019-11-24 11:27:03.528 29627-29627/com.example.esense_application E/MediaRecorder: stop called in an invalid state: 4
2019-11-24 11:27:03.528 29627-29627/com.example.esense_application D/AndroidRuntime: Shutting down VM
2019-11-24 11:27:03.529 29627-29627/com.example.esense_application E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.esense_application, PID: 29627
java.lang.IllegalStateException
at android.media.MediaRecorder.stop(Native Method)
at com.example.esense_application.MainActivity$2.onClick(MainActivity.java:98)
at android.view.View.performClick(View.java:7140)
at android.view.View.performClickInternal(View.java:7117)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27351)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2019-11-24 11:27:03.540 29627-29627/com.example.esense_application I/Process: Sending signal. PID: 29627 SIG: 9
Your MediaRecorder is throwing when you try to stop() it because it has never entered the "recording" state. In fact, it never even entered the "prepared" state, because your call to prepare() did not complete successfully.
SOLUTION
Do not allow a call to start() until the prepare() call has returned (without throwing).
Do not allow a call to stop() until the start() call has returned (without throwing).
Make sure you have chosen a valid location for your output file. Try using getExternalFilesDir( null ) instead of Environment.getExternalStorageDirectory(). The bad file path is the reason your prepare() call is currently failing with an EACCESS.
As you can see, swallowing exceptions without addressing their root cause (i.e., just doing a e.printStackTrace() and carrying on), can rapidly lead to problems -- even in rough code used for learning/experimentation. If you are going to add an exception handler, it is better to provide real error handling -- and always make sure you understand why an exception is being thrown.

Bluetooth Android app keeps crashing on startup [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I tried to build an app that lets you send data over bluetooth to an
arduino. But I got stuck while creating the socket. The app keeps
crashing on startup, but I don't know why.
package de.lutherschule.bled.bluetoothled;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.icu.util.Output;
import android.support.annotation.WorkerThread;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
BluetoothAdapter bAdapter;
BluetoothDevice device;
Boolean found;
BluetoothSocket btSocket;
OutputStream outputStream;
InputStream inputStream;
public static final String DEVICE_ADRESS = "";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final String TAG = "MainActvity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bAdapter = BluetoothAdapter.getDefaultAdapter();
found = false;
btSocket = null;
Log.v(TAG, "Funst");
if (bAdapter == null) {
Toast.makeText(getApplicationContext(),"Funst net",Toast.LENGTH_SHORT).show();
}
if(!bAdapter.isEnabled()) {
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
}
Set<BluetoothDevice> bondedDevices = bAdapter.getBondedDevices();
if(bondedDevices.isEmpty()) {
Toast.makeText(getApplicationContext(),"Muss gepaired werden",Toast.LENGTH_SHORT).show();
} else {
for (BluetoothDevice iter : bondedDevices) {
if(iter.getAddress().equals(DEVICE_ADRESS)) { // oder iter.getName() wenn Name bekannt muessen dann aendern
device=iter;
found=true;
break;
}
}
}
When I delete the section under this quote. The app starts just fine.
try{
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
}catch(IOException ioe){
Log.v(TAG, "socket nit erstellt");
}
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
device = bAdapter.getRemoteDevice(DEVICE_ADRESS);
try {
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket nit erstellt", Toast.LENGTH_LONG).show();
}
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
}
}
}
#Override
public void onPause() {
super.onPause();
try {
btSocket.close();
} catch (IOException e2) {
}
}
}
I'd appreciate any help. By the way sorry for my formatting... I'm a newbie in creating posts.
Android Monitor:
08-27 17:56:51.857 3071-3071/? E/libprocessgroup: failed to make and chown /acct/uid_10058: Read-only file system
08-27 17:56:51.857 3071-3071/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
08-27 17:56:51.857 3071-3071/? I/art: Not late-enabling -Xcheck:jni (already on)
08-27 17:56:52.086 3071-3071/de.lutherschule.bled.bluetoothled I/InstantRun: Starting Instant Run Server for de.lutherschule.bled.bluetoothled
08-27 17:56:52.288 3071-3071/de.lutherschule.bled.bluetoothled W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
[ 08-27 17:56:52.386 1162: 2146 D/ ]
HostConnection::get() New Host Connection established 0xb68aea60, tid 2146
08-27 17:56:52.429 3071-3079/de.lutherschule.bled.bluetoothled W/art: Suspending all threads took: 17.085ms
08-27 17:56:52.442 3071-3071/de.lutherschule.bled.bluetoothled E/BluetoothAdapter: Bluetooth binder is null
08-27 17:56:52.442 3071-3071/de.lutherschule.bled.bluetoothled V/MainActvity: Funst
08-27 17:56:52.452 3071-3071/de.lutherschule.bled.bluetoothled D/AndroidRuntime: Shutting down VM
--------- beginning of crash
08-27 17:56:52.453 3071-3071/de.lutherschule.bled.bluetoothled E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.lutherschule.bled.bluetoothled, PID: 3071
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.lutherschule.bled.bluetoothled/de.lutherschule.bled.bluetoothled.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at de.lutherschule.bled.bluetoothled.MainActivity.onCreate(MainActivity.java:59)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
Try to use
BluetoothDevice device = mAdapter.getRemoteDevice(address);
btsocket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
Here is my code.
try {
socket = connect_device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
h.sendEmptyMessage(0);
} catch (IOException e) {
// TODO Auto-generated catch block
h.sendEmptyMessage(1);
e.printStackTrace();
try {
socket.close();
} catch (IOException e2) {
}
}

How to fix HandleSignInResult return false?

I'm making a notes app using firebase auth and realtime database.
I'm stuck at the setup of google authentication.
this is my Code:
`package zohar.com.blablabla;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
public class LoginActivity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {
SignInButton signInButton;
GoogleApiClient mGoogleApiClient;
public static final int RC_SIGN_IN = 9001;
public static final String TAG = "SignInActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
signInButton = (SignInButton) findViewById(R.id.signInButtonGoogle);
signInButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
signIn();
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
//connected successfully
Toast.makeText(this, "You are successfully connected!", Toast.LENGTH_SHORT).show();
Intent toMainActivityIntent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(toMainActivityIntent);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "We are currently facing with google/'s api issues,
please try again later", Toast.LENGTH_LONG).show();
}
}`
The problam is that every time when I click on the sign in button its not even showing the account picker (I dont know if its importent but I have more than 1 google accounts on my emulator). When I click it the screen turns little dark and than turns regular.
Everytime HandleSignInResult returns False.
*I did register my project and insert the sha-1.
**Sorry if I made some spelling/grammar mistakes. I'm still learning english and it's not my primary language.
Thanks.
EDIT: This are the warns:
08-14 10:52:34.116 2355-2355/? W/art: Unexpected CPU variant for X86 using
defaults: x86
08-14 10:52:34.404 2355-2355/zohar.com.notescloud W/System: ClassLoader
referenced unknown path: /data/app/zohar.com.notescloud-2/lib/x86
08-14 10:52:34.564 2355-2378/zohar.com.notescloud W/DynamiteModule: Local
module descriptor class for com.google.firebase.auth not found.
08-14 10:52:34.579 2355-2378/zohar.com.notescloud W/DynamiteModule: Local
module descriptor class for com.google.firebase.auth not found.
08-14 10:52:35.009 2355-2355/zohar.com.notescloud W/art: Before Android 4.1,
method android.graphics.PorterDuffColorFilter
android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
08-14 10:52:35.209 2355-2355/zohar.com.notescloud W/System: ClassLoader referenced unknown path:
08-14 10:52:35.405 2355-2355/zohar.com.notescloud W/System: ClassLoader referenced unknown path: /data/user_de/0/com.google.android.gms/app_chimera/m/00000006/n/x86
08-14 10:52:35.856 2355-2430/zohar.com.notescloud W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
08-14 10:52:36.030 2355-2355/zohar.com.notescloud W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
c
Debug:
08-14 11:02:08.029 2355-11693/zohar.com.notescloud D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=46612, firebase_screen_class(_sc)=LoginActivity, firebase_screen_id(_si)=3256989730768445770}]
08-14 11:02:08.072 2355-11693/zohar.com.notescloud D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=LoginActivity, firebase_previous_id(_pi)=3256989730768445770, firebase_screen_class(_sc)=SignInHubActivity, firebase_screen_id(_si)=3256989730768445773}]
08-14 11:02:08.178 2355-11693/zohar.com.notescloud D/FA: Connected to remote service
08-14 11:02:08.183 2355-2430/zohar.com.notescloud D/EGL_emulation: eglMakeCurrent: 0x9aa2b320: ver 2 0 (tinfo 0x9c741ef0)
08-14 11:02:08.205 2355-2430/zohar.com.notescloud D/EGL_emulation: eglMakeCurrent: 0x9aa2b320: ver 2 0 (tinfo 0x9c741ef0)
08-14 11:02:08.947 2355-2355/zohar.com.notescloud D/SignInActivity: handleSignInResult:false
08-14 11:02:08.953 2355-11693/zohar.com.notescloud D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=SignInHubActivity, firebase_previous_id(_pi)=3256989730768445773, firebase_screen_class(_sc)=LoginActivity, firebase_screen_id(_si)=3256989730768445770}]
EDIT2: FIXED!
I was so dumb and gave the auto-completion make GOOGLE_SIGN_IN to GOOGLE_GAMES_SIGN_IN.
Sry guys.

LoginActivty with Firebase & Facebook authentication not responding after 3th relaunch

Everytime at the 3th relaunch, my app gets stuck on a dark screen. I have no clue why, I have checked out the Facebook and Firebase docs, followed examples (github). Has anyone experienced this too?
Additional information:
Facebook lib: com.facebook.android:facebook-android-sdk:4.12.0
Firebase lib: com.google.firebase:firebase-auth:9.0.0
MainActivity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Intent navigationIntent;
private Intent serviceIntent;
// FIREBASE
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
// FACEBOOK
private CallbackManager FBcallbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navigationIntent = new Intent(this, NavigationActivity.class);
serviceIntent = new Intent(this, BackgroundService.class);
// Initialize Firebase
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
// if so start next activty and close this one
Log.d(TAG, "User logged in");
startHomeActivity();
startActivity(navigationIntent);
finish();
} else {
Log.d(TAG, "User not logged in");
}
}
};
// Initialize Facebook Login button
FBcallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.facebookButton);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(FBcallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
Log.d("Facebook Error", error.toString());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
FBcallbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onResume() {
super.onResume();
firebaseAuth.addAuthStateListener(firebaseAuthListener);
}
#Override
protected void onPause() {
super.onPause();
if (firebaseAuthListener != null) {
firebaseAuth.removeAuthStateListener(firebaseAuthListener);
}
}
private void handleFacebookAccessToken(AccessToken accessToken) {
final AuthCredential authCredential = FacebookAuthProvider.getCredential(accessToken.getToken());
firebaseAuth.signInWithCredential(authCredential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Authentication successful");
startHomeActivity();
} else {
Log.d(TAG, "Authentication not successful");
Log.d(TAG, task.getException().getMessage());
}
}
});
}
private boolean isServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
private void startHomeActivity() {
if (navigationIntent != null && serviceIntent != null) {
if (!isServiceRunning(BackgroundService.class)) {
startService(serviceIntent);
Log.d(TAG, "Service is no running. Starting service..");
} else {
Log.d(TAG, "Service is running. Not starting service..");
}
startActivity(navigationIntent);
finish();
}
}
}
Application:
public class ???????? extends Application {
#Override
public void onCreate() {
super.onCreate();
FacebookSdk.sdkInitialize(getApplicationContext());
}
}
Logcat (app specific) before last restart (there is no log on 3th restart/freeze)
05-24 16:53:19.547 16587-16618/my.package.app W/System.err: remove failed: ENOENT (No such file or directory) : /data/user/0/my.package.app/files/AppEventsLogger.persistedevents
05-24 16:53:19.557 16587-16609/my.package.app V/FA: Inactivity, disconnecting from AppMeasurementService
05-24 16:53:19.627 16587-16618/my.package.app I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
05-24 16:53:19.627 16587-16618/my.package.app I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
05-24 16:53:30.167 16587-16587/my.package.app D/ViewRootImpl: ViewPostImeInputStage processKey 0
05-24 16:53:30.247 16587-16587/my.package.app D/ViewRootImpl: ViewPostImeInputStage processKey 1
05-24 16:53:30.287 16587-16609/my.package.app V/FA: Activity paused, time: 455339818
05-24 16:53:30.807 16587-16587/my.package.app D/FirebaseApp: Notifying background state change listeners.a
Logcat (firebase background crash)
05-24 16:53:14.247 16940-16940/my.package.app:background_crash E/DynamiteModule: Failed to load module descriptor class: Didn't find class "com.google.android.gms.dynamite.descriptors.com.google.android.gms.crash.ModuleDescriptor" on path: DexPathList[[zip file "/data/app/my.package.app-1/base.apk"],nativeLibraryDirectories=[/data/app/my.package.app-1/lib/arm64, /vendor/lib64, /system/lib64]]
05-24 16:53:14.247 16940-16968/my.package.app:background_crash W/System.err: remove failed: ENOENT (No such file or directory) : /data/user/0/my.package.app/files/AppEventsLogger.persistedevents
05-24 16:53:14.247 16940-16956/my.package.app:background_crash I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
05-24 16:53:14.247 16940-16956/my.package.app:background_crash I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
05-24 16:53:14.257 16940-16940/my.package.app:background_crash V/GoogleSignatureVerifier: com.google.android.gms signature not valid. Found:
// I have changed the key below for security reasons MIIEQzCCAyugAwIBAgIJAMLgh0ZkSjCNMA0GCSqGSIb3DQEBBAUAMHQxCzAJBgNVBAYTAlVTMRMw
MIIEQzCCAyugAwIBAgIJAMLgh0ZkSjCNMA0GCSqGSIb3DQEBBAUAMHQxCzAJBgNVBAYTAlVTMRMw
MIIEQzCCAyugAwIBAgIJAMLgh0ZkSjCNMA0GCSqGSIb3DQEBBAUAMHQxCzAJBgNVBAYTAlVTMRMw
MIIEQzCCAyugAwIBAgIJAMLgh0ZkSjCNMA0GCSqGSIb3DQEBBAUAMHQxCzAJBgNVBAYTAlVTMRMw
MIIEQzCCAyugAwIBAgIJAMLgh0ZkSjCNMA0GCSqGSIb3DQEBBAUAMHQxCzAJBgNVBAYTAlVTMRMw
MIIEQzCCAyugAwIBAgIJAMLgh0ZkSjCNMA0GCSqGSIb3DQEBBAUAMHQxCzAJBgNVBAYTAlVTMRMw
MIIEQzCCAyugAwIBAgIJAMLgh0ZkSjCNMA0GCSqGSIb3DQEBBAUAMHQxCzAJBgNVBAYTAlVTMRMw
05-24 16:53:14.267 16940-16940/my.package.app:background_crash W/ResourcesManager: getTopLevelResources: /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk / 1.0 running in my.package.app rsrc of package com.google.android.gms
05-24 16:53:14.267 16940-16940/my.package.app:background_crash D/ResourcesManager: For user 0 new overlays fetched Null
05-24 16:53:14.267 16940-16940/my.package.app:background_crash I/InjectionManager: Inside getClassLibPath caller
05-24 16:53:14.287 16940-16940/my.package.app:background_crash W/System: ClassLoader referenced unknown path: /system/priv-app/PrebuiltGmsCore/lib/arm64
05-24 16:53:14.297 16940-16940/my.package.app:background_crash W/ResourcesManager: getTopLevelResources: /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk / 1.0 running in my.package.app rsrc of package com.google.android.gms
05-24 16:53:14.297 16940-16940/my.package.app:background_crash D/ChimeraCfgMgr: Reading stored module config
05-24 16:53:14.317 16940-16940/my.package.app:background_crash I/DynamiteModule: Considering local module com.google.android.gms.crash:0 and remote module com.google.android.gms.crash:2
05-24 16:53:14.317 16940-16940/my.package.app:background_crash I/DynamiteModule: Selected remote version of com.google.android.gms.crash, version >= 2
05-24 16:53:14.317 16940-16940/my.package.app:background_crash W/ResourcesManager: getTopLevelResources: /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk / 1.0 running in my.package.app rsrc of package com.google.android.gms
05-24 16:53:14.327 16940-16940/my.package.app:background_crash I/InjectionManager: Inside getClassLibPath caller
05-24 16:53:14.327 16940-16940/my.package.app:background_crash W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/m/00000005/n/arm64-v8a
05-24 16:53:14.327 16940-16940/my.package.app:background_crash D/ChimeraFileApk: Primary ABI of requesting process is arm64-v8a
05-24 16:53:14.327 16940-16940/my.package.app:background_crash D/ChimeraFileApk: Classloading successful. Optimized code found.
05-24 16:53:14.337 16940-16940/my.package.app:background_crash I/FirebaseCrashReceiverServiceImpl: FirebaseCrashReceiverServiceImpl created by ClassLoader com.google.android.chimera.container.internal.DelegateLastPathClassLoader[DexPathList[[zip file "/data/user/0/com.google.android.gms/app_chimera/m/00000005/DynamiteModulesC_GmsCore_prodmnc_alldpi_release.apk"],nativeLibraryDirectories=[/data/user/0/com.google.android.gms/app_chimera/m/00000005/n/arm64-v8a, /vendor/lib64, /system/lib64]]]
05-24 16:53:14.337 16940-16940/my.package.app:background_crash D/FirebaseCrashReceiverServiceImpl: onCreate
05-24 16:53:14.347 16940-16940/my.package.app:background_crash I/DynamiteModule: Considering local module com.google.android.gms.flags:0 and remote module com.google.android.gms.flags:1
05-24 16:53:14.347 16940-16940/my.package.app:background_crash I/DynamiteModule: Selected remote version of com.google.android.gms.flags, version >= 1
05-24 16:53:14.417 16940-16940/my.package.app:background_crash I/FirebaseCrashSenderServiceImpl: FirebaseCrashSenderServiceImpl created by ClassLoader com.google.android.chimera.container.internal.DelegateLastPathClassLoader[DexPathList[[zip file "/data/user/0/com.google.android.gms/app_chimera/m/00000005/DynamiteModulesC_GmsCore_prodmnc_alldpi_release.apk"],nativeLibraryDirectories=[/data/user/0/com.google.android.gms/app_chimera/m/00000005/n/arm64-v8a, /vendor/lib64, /system/lib64]]]
05-24 16:53:14.417 16940-16940/my.package.app:background_crash D/FirebaseCrashSenderServiceImpl: onCreate
Possibly this is an issue with the background Firebase Crash process calling the Facebook SDK in a way that the SDK didn't expect. You can guard that with a check for whether Firebase has initialised properly:
#Override
public void onCreate() {
super.onCreate();
if (!FirebaseApp.getApps(this).isEmpty()) {
FacebookSdk.sdkInitialize(getApplicationContext());
}
}
Try that, and see if it stop the freeze occurring.
I have the same problem from firebase analytics version 9.0.2, I think it's a bug.
And I found this issue is on the analytics version 9.0.2, and I try to revert version to 9.0.0, it will be fine and no black screen.
But you are the auth lib 9.0.0, so I think it's different...
My solution like this:
compile 'com.google.firebase:firebase-analytics:9.0.0'

Can not retrieve location, app crashes

I have two classes.
MainActivity:
package ytu.ytu1;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button gpsBtn;
private TextView gpsTxt;
private LocationManager locMngr;
private LocationListener locLstnr;
GPSTracker gps;
double lot,lat;
String txt;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lat=gps.getLocation().getLongitude();
lot=gps.getLocation().getLatitude();
txt="longti "+lat + "latit " +lot;
gpsTxt = (TextView) findViewById(R.id.gpsTxt);
gpsTxt.setText("Coordinates: ");
gpsTxt.append(txt);
Toast.makeText(MainActivity.this,txt,
Toast.LENGTH_LONG).show();
}}
GPSTracker.java from here
http://pastie.org/9300205
only permissions were changed, because i am using this on android kitkat tablet.
package ytu.ytu1;
/**
* Created by mia on 11/28/2015.
*/
import android.Manifest;
import android.annotation.TargetApi;
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.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
private TextView txt;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 5000; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void StoprequestUpdates() {
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// 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 Activity#requestPermissions for more details.
if (isGPSEnabled) {
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();
}
}
}
if (isNetworkEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
return;
} else {
}
}
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 GPS Enabled get lat/long using GPS Services
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
if (isGPSEnabled) {
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();
}
}
}
if (isNetworkEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
locationManager.removeUpdates(GPSTracker.this);return;}
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
*
*
*
*
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
this.location = location;
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
I can not even debug, as soon as it starts, it crashes without showing any view.
logcat:
11-28 16:51:19.541 9413-9413/? D/dalvikvm: Late-enabling CheckJNI
11-28 16:51:19.591 9413-9413/? D/ActivityThread: handleBindApplication:ytu.ytu1
11-28 16:51:19.621 9413-9413/ytu.ytu1 W/ApplicationPackageManager: getCSCPackageItemText()
11-28 16:51:19.631 9413-9413/ytu.ytu1 D/DisplayManager: DisplayManager()
11-28 16:51:19.641 9413-9413/ytu.ytu1 W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
11-28 16:51:19.641 9413-9413/ytu.ytu1 I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onSearchRequested
11-28 16:51:19.641 9413-9413/ytu.ytu1 W/dalvikvm: VFY: unable to resolve interface method 17904: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
11-28 16:51:19.641 9413-9413/ytu.ytu1 D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-28 16:51:19.641 9413-9413/ytu.ytu1 I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onWindowStartingActionMode
11-28 16:51:19.641 9413-9413/ytu.ytu1 W/dalvikvm: VFY: unable to resolve interface method 17908: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
11-28 16:51:19.641 9413-9413/ytu.ytu1 D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-28 16:51:19.661 9413-9413/ytu.ytu1 D/AndroidRuntime: Shutting down VM
11-28 16:51:19.661 9413-9413/ytu.ytu1 W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x416adbc0)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: FATAL EXCEPTION: main
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: Process: ytu.ytu1, PID: 9413
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{ytu.ytu1/ytu.ytu1.MainActivity}: java.lang.NullPointerException
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:166)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.os.Looper.loop(Looper.java:136)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5584)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: Caused by: java.lang.NullPointerException
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at ytu.ytu1.MainActivity.onCreate(MainActivity.java:44)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:5447)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:166) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.os.Looper.loop(Looper.java:136) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5584) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method) 
I am using on android studio and i did not change the original code so much. I dont understand why it wont start.
Try something like this:
GPSTracker gps = new GPSTracker(this);
also check this tutorial: http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

Categories

Resources