This question already has answers here:
Android permission doesn't work even if I have declared it
(11 answers)
Closed 2 years ago.
Upon accessing the Maps Activity, it crashes. I've tried switching out the Activity with a generic Maps Activity which does work, and I've rolled back to a previous version that I know worked all to no avail.
This is the Android Java:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Camera;
import android.location.Location;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.google.android.gms.location.LocationListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApi;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.internal.GoogleApiAvailabilityCache;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class DriverMapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location driverLastLocation;
LocationRequest driverLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driver_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Button buttonLogout = findViewById(R.id.buttonLogout);
buttonLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(DriverMapsActivity.this, MainActivity.class);
startActivity(intent);
finish();
return;
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
protected synchronized void buildGoogleApiClient(){
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
driverLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("driversClear");
GeoFire geoFire = new GeoFire(ref);
geoFire.setLocation(userID, new GeoLocation(location.getLatitude(), location.getLongitude()));
}
#Override
public void onConnected(#Nullable Bundle bundle) {
driverLocationRequest = new LocationRequest();
driverLocationRequest.setInterval(1000);
driverLocationRequest.setFastestInterval(2000);
driverLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, driverLocationRequest, (com.google.android.gms.location.LocationListener) this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onStop(){
super.onStop();
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("driversClear");
GeoFire geoFire = new GeoFire(ref);
geoFire.removeLocation(userID);
}
}
I'm new to Android Dev so I'm not sure if it is particularly vital to debugging this kind of issue but here is the layout XML thing
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DriverMapsActivity" >
<Button
android:id="#+id/buttonLogout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout" />
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
and I'm not sure if I should share the AndroidManifest but I feel like it is important
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".CustomerMapsActivity" >
</activity>
<activity android:name=".TestClass" />
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".DriverMapsActivity"
android:label="#string/title_activity_driver_maps" />
<activity android:name=".DriverLogin" />
<activity android:name=".DriverRegistration" />
<activity android:name=".CustomerLogin" />
<activity android:name=".CustomerRegistration" />
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Also if anyone can tell me why the built in debugger isn't notifying me of this error that would be appreciated (as in do I need to toggle a setting or install something extra?)
Thanks
Can you check the 'Run' tab for error, instead of Logcat. If the app crashes as soon as it starts, logs may be present in 'Run' tab.
Related
I am trying to develop a motion sensing application.
For this, I have created two Activities.
The first Activity takes the latitude and longitude from the user and there is a Button which saves the data and passes it onto the next Activity.
The second Activity is a GoogleMaps Activity, where I am using the user's data and all the respective managers (SensorManager, accelerometer, etc).
The first page is working fine, but when I enter the data and press the button,the application stops.
In the log, it shows that a ClassCastException is thrown in the MapsActivity class.
Please help.
Error:
12-21 17:14:44.564 5417-5417/com.example.anurag.anurag_latest_morgenall E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.anurag.anurag_latest_morgenall, PID: 5417
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anurag.anurag_latest_morgenall/com.example.anurag.anurag_latest_morgenall.MapsActivity}: java.lang.ClassCastException: com.example.anurag.anurag_latest_morgenall.MapsActivity cannot be cast to android.hardware.SensorEventListener
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.ClassCastException: com.example.anurag.anurag_latest_morgenall.MapsActivity cannot be cast to android.hardware.SensorEventListener
at com.example.anurag.anurag_latest_morgenall.MapsActivity.onCreate(MapsActivity.java:49)
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)
MainActivity.java file:
package com.example.anurag.anurag_latest_morgenall;
import android.app.usage.UsageEvents;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
float x, y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText latitude = (EditText) findViewById(R.id.latitude1);
final EditText longitude = (EditText) findViewById(R.id.longitude1);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
x= Float.parseFloat(latitude.getText().toString());
y= Float.parseFloat(longitude.getText().toString());
Intent intent=new Intent(getApplicationContext(),MapsActivity.class);
Bundle extras= new Bundle();
extras.putFloat("LATITUDE",x);
extras.putFloat("LONGITUDE",y);
intent.putExtras(extras);
startActivity(intent);
}
});
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
}
MapsActivity.java file:
package com.example.anurag.anurag_latest_morgenall;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.icu.text.SimpleDateFormat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.Date;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private SensorManager sensorManager;
private Sensor accelerometer;
long lastUpdate=0;
private float last_x,last_y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
last_x = extras.getFloat("LATITUDE");
last_y = extras.getFloat("LONGITUDE");
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// set up acclerometer
sensorManager= (SensorManager)this.getSystemService(Context.SENSOR_SERVICE);
accelerometer= sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
**the below line is where the error is getting pointed to**
sensorManager.registerListener((SensorEventListener) this,accelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
public void onSensorChanged(SensorEvent event){
Sensor mySensor= event.sensor;
if (mySensor.getType()==Sensor.TYPE_ACCELEROMETER)
{
float x= event.values[0];
float y= event.values[1];
long curTime= System.currentTimeMillis();
if(Math.abs(curTime - lastUpdate)>2000){
java.text.SimpleDateFormat date= new java.text.SimpleDateFormat("dd-MM-yyyy");
String currentDateTime= date.format(new Date());
lastUpdate=curTime;
if(Math.abs(last_x - x)>10)
{
mMap.addMarker(new MarkerOptions().position(new LatLng(last_x,last_y))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
.title("Hey you moved the x-axis on "+currentDateTime));
}
if(Math.abs(last_y - y)>10)
{
mMap.addMarker(new MarkerOptions().position(new LatLng(last_x,last_y))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.title("Hey you moved the y-axis on "+currentDateTime));
}
last_x=x;
last_y=y;
}
}
}
public void onAccuracyChanged(Sensor sensor,int accuracy)
{
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(last_x,last_y);
mMap.addMarker(new MarkerOptions().position(sydney).title("Virginia Tech"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,14.9f));
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.anurag.anurag_latest_morgenall.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/TextView1"
android:text="#string/Text_Name"
android:gravity="center_horizontal"
android:textSize="20sp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:layout_below="#+id/latitude1"
android:layout_alignEnd="#+id/latitude1"
android:layout_marginTop="33dp"
android:id="#+id/longitude1"
android:hint="Enter the longitude"
android:gravity="center_vertical|center" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginTop="34dp"
android:id="#+id/latitude1"
android:hint="Enter the Latitude"
android:layout_below="#+id/TextView1"
android:layout_centerHorizontal="true"
android:gravity="center_vertical|center" />
<Button
android:text="Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button1"
android:layout_below="#+id/longitude1"
android:layout_centerHorizontal="true"
android:layout_marginTop="71dp"
android:onClick="sendData"/>
</RelativeLayout>
activity_maps.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.anurag.anurag_latest_morgenall.MapsActivity" />
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.anurag.anurag_latest_morgenall">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps"></activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
I have already entered all the necessary API key in the required places.
Hint: These methods do nothing
public void onSensorChanged(SensorEvent event)
public void onAccuracyChanged(Sensor sensor,int accuracy)
Tip: Add #Override onto them to let the compiler warn you that you didn't implement the interface.
class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
I need some help...
My application can't show the map. I've enabled the API Key and try to create it many times, with new keystore.
Screenshot for result
The error code says:
12-14 03:47:45.527 31641-31956/tkj5a.dhiaulhaq.pnj.project_paksyamsi E/b: Authentication failed on the server.
12-14 03:47:45.527 31641-31956/tkj5a.dhiaulhaq.pnj.project_paksyamsi E/Google Maps Android API: Authorization failure. Please see
12-14 03:47:45.533 31641-31956/tkj5a.dhiaulhaq.pnj.project_paksyamsi 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: AIzaSyCLdUfhN9SoszJQiGzDF1rcOuV5P2RfcJs
Android Application (<cert_fingerprint>;<package_name>): 39:AD:91:AB:60:3D:34:22:1C:F3:36:4B:B6:98:6F:BB:61:5A:B5:60;tkj5a.dhiaulhaq.pnj.project_paksyamsi
And my layout:
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="tkj5a.dhiaulhaq.pnj.project_paksyamsi">
<permission android:name="tkj5a.dhiaulhaq.pnj.project_paksyamsi.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="tkj5a.dhiaulhaq.pnj.project_paksyamsi.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="tkj5a.dhiaulhaq.pnj.project_paksyamsi.permission.READ_GSERVICES"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MapsActivity"
android:theme="#style/AppTheme.NoActionBar"></activity>
<activity android:name=".CheckInActivity"
android:theme="#style/AppTheme.NoActionBar"></activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyCLdUfhN9SoszJQiGzDF1rcOuV5P2RfcJs"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
</application>
</manifest>
And here's the MapsActivity.java:
package tkj5a.dhiaulhaq.pnj.project_paksyamsi;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
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.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
public class MapsActivity extends FragmentActivity {
private GoogleMap map;
private DBLokasi lokasi;
private ArrayList<DBLokasi> values;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFrag=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
map=mapFrag.getMap();
map.setMyLocationEnabled(true);
Bundle b=this.getIntent().getExtras();
if (b.containsKey("longitude")){
final LatLng latLng=new LatLng(b.getDouble("latitude"),b.getDouble("longitude"));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
map.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(MapsActivity.this,"Lokasi Saat Ini " + latLng.latitude+ "," +latLng.longitude,Toast.LENGTH_LONG).show();
return false;
}
});
}else if (this.getIntent().getSerializableExtra("lokasi")!=null){
lokasi=(DBLokasi)this.getIntent().getSerializableExtra("lokasi");
if (lokasi!=null){
LatLng latLng=new LatLng(lokasi.getLatD(),lokasi.getLngD());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
map.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)).title(lokasi.getNama()));
}
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
final Dialog dialog=new Dialog(MapsActivity.this);
dialog.setTitle("Checkin Data : ");
dialog.setContentView(R.layout.fragment_dialog_datashow);
TextView tvNama=(TextView)dialog.findViewById(R.id.tv_nama);
TextView tvKoordinat=(TextView)dialog.findViewById(R.id.tv_koordinat);
Button btOK=(Button)dialog.findViewById(R.id.bt_checkin_ok);
tvNama.setText(String.format(getResources().getString(R.string.checkin_label_name),marker.getTitle()));
tvKoordinat.setText(marker.getPosition().latitude+ ","+ marker.getPosition().longitude);
btOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
dialog.show();
return false;
}
});
}
else {
LatLng init;
DBLokasi lokInit;
LatLng latLng;
values=((ArrayList<DBLokasi>)this.getIntent().getSerializableExtra("arraylokasi"));
lokInit=values.get(0);
init=new LatLng(lokInit.getLatD(),lokInit.getLngD());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(init,16));
for (DBLokasi lok:values){
latLng=new LatLng(lok.getLatD(),lok.getLngD());
map.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
}
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
final Dialog dialog=new Dialog(MapsActivity.this);
dialog.setTitle("Checkin Data : ");
dialog.setContentView(R.layout.fragment_dialog_datashow);
TextView tvNama=(TextView)dialog.findViewById(R.id.tv_nama);
TextView tvKoordinat=(TextView)dialog.findViewById(R.id.tv_koordinat);
Button btOK=(Button)dialog.findViewById(R.id.bt_checkin_ok);
tvNama.setText(String.format(getResources().getString(R.string.checkin_label_name)));
tvKoordinat.setText(marker.getPosition().latitude+","+marker.getPosition().longitude);
btOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
dialog.show();
return false;
}
});
}
}
}
Thanks for any helps guys :)
Confirm the SHA-1 key you are getting in the message and the key you have on server are same. Also, make sure adding the API key in manifest as well as in a XML file (release -> res -> values -> google_maps_api.xml) which automatically gets generated.
**Manifest:**
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/google_maps_key" />
and
**google_maps_api.xml**
<string name="google_maps_key" translatable="false" templateMergeStrategy="preserve">
YOUR_KEY_HERE
</string>
You can get SHA-1 key and package name from the error message you have posted. Both are separated by ';'
Make sure your API key is the correct one... and maybe check if you have the 'Google Play Services' SDK installed.
It says "In the Google Developer Console" so i would start there lol
Check:
-SHA 1 key
-API Key
Don't forget to hit 'Save' once you're done, i know a few people who have made that mistake before!
I'm completely new to Android development, but I have worked with Java (and other programming languages) before.
I'm using Android Studio to develop my application and I've become stuck when following the developer tutorial on accessing Location information (http://developer.android.com/training/location/index.html). I understand that the Location services require the android.permission.ACCESS_COARSE_LOCATION and/or android.permission.ACCESS_FINE_LOCATION permissions but upon adding them to my ApplicationManifest my application still crashes with a SecurityException
java.lang.SecurityException: Client must have ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to perform any location operations.
I've come across several other instances of people having trouble, but these have generally been the result of mis-placing (java.lang.SecurityException: Requires ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permission), mis-spelling (ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted) or incorrect capitalization of the permission string.
Here is my ApplicationManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="scd.tt" >
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="23" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher_tt_v2"
android:label="#string/app_name"
android:theme="#style/TT_Theme">
<activity
android:name=".MainActivity"
android:theme="#style/TT_Theme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoginActivity" android:theme="#style/TT_Theme.NoActionBar" />
<activity android:name=".IndexActivity" />
</application>
</manifest>
I've even tried to remove ACCESS_NETWORK_STATE and INTERNET to see if this would cause other SecurityExceptions as the application is required to communicate with an HTTP server (which it performs successfully) before it gets attempts to get Location information.
It seems as though modifications I make to the permissions on the AndroidManifest aren't being updated when I run the program. I've also tried to Clean and Rebuild the application using the Build menu.
UPDATE:
Here is the core of the Activity; I've removed some of the unrelated methods (such as onCreateOptionsMenu() and onBackPressed() as they have nothing to do with the Location)
package scd.tt;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.util.Map;
/**
* Created by Liam on 08/09/2015
*/
public class IndexActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mLastLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index);
if(debug) Log.d(TAG, "onCreate() called: savedInstanceState is " + (savedInstanceState == null ? "null" : "not null"));
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
buildGoogleApiClient();
if (findViewById(R.id.index_fragment_container) != null) {
if (savedInstanceState != null) return;
Fragment index = new IndexFragment();
index.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(R.id.index_fragment_container, index).commit();
}
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
#Override
public void onConnected(Bundle bundle) {
if(debug) Log.d(TAG, "onConnected");
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
if(debug) Log.d(TAG, "Connection Suspended");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if(debug) Log.d(TAG, "Connection Failed");
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
if(debug) Log.d(TAG, "buildGoogleAPIClient()");
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
Check these 3 links. They might help -
Android - Unable to get the gps location on the emulator
ACCESS_FINE_LOCATION permission error emulator only
http://www.gitshah.com/2011/02/android-fixing-no-internet-connection.html
As quoted by you in comments -
Permissions with a protection level of dangerous must be granted at runtime by prompting the user as of SDK 23 and can not be defined solely in the Manifest any more.
I am new to android and I am trying to make this application where I need location co-ordinates of my current position and show my position on the map. all the other parts of the app run quite well until just when ever I try to get the latitude and longitude from the fusedLocationApi. I have followed this tutorial Get the Last Known Location and have tried to implement it on Google Map Activity.
here is my java file:
package com.example.deep.app_project;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.plus.Plus;
public class Map extends FragmentActivity implements GoogleMap.OnMyLocationChangeListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
LocationManager lm;
TextView lt, ln;
String provider;
Location l;
double lon= 0, lat =0;
GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
setUpMapIfNeeded();
client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
mMap.setMyLocationEnabled(true);
}
public void button_Map_Back(View v){
Intent MainActivityIntent = new Intent(Map.this, MainActivity.class);
startActivity(MainActivityIntent);
finish();
}
#Override
public void onConnected(Bundle bundle) {
l = LocationServices.FusedLocationApi.getLastLocation(client);
if (l != null) {
lt.setText(String.valueOf(l.getLatitude()));
ln.setText(String.valueOf(l.getLongitude()));
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onMyLocationChange(Location location) {
lt.setText(String.valueOf(location.getLatitude()));
ln.setText(String.valueOf(location.getLongitude()));
}
here is my .xml file :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.deep.app_project" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Distance_timer"
android:label="#string/title_activity_distance_timer" >
</activity>
<activity
android:name=".Journey_type"
android:label="#string/title_activity_journey_type" >
</activity>
<activity
android:name=".prev_stat_fragment"
android:label="#string/title_activity_prev_stat_fragment" >
</activity>
<activity
android:name=".Result"
android:label="#string/title_activity_result" >
</activity>
<activity
android:name=".settings_fragment"
android:label="#string/title_activity_settings_fragment" >
</activity>
<activity
android:name=".SimpleFragmentActivity"
android:label="#string/title_activity_simple_fragment" >
</activity>
<activity
android:name=".Time_timer"
android:label="#string/title_activity_time_timer" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyD-LoJLRIyTF2mI5HdKULNk1QhBAQlhkRQ"/>
<activity
android:name=".Map"
android:label="#string/title_activity_map" >
</activity>
</application>
I have recently done this... and found it confusing to deal with varying different documentation.
I found it easier to use OnMyLocationChangeListener:
Activity implements GoogleMap.OnMyLocationChangeListener
then Override onLocationChanged:
#Override
public void onMyLocationChange(Location location) {
LatLng pos = new LatLng(location.getLatitude(),location.getLongitude());
CameraUpdate mLoc = CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(pos).zoom(ZOOM_LEVEL).build());
map.moveCamera(mLoc);
mLocMarker = map.addMarker(new MarkerOptions()
.title(TITLE)
.snippet(SNIPPET)
.position(pos)
.draggable(true));
mLocMarker.showInfoWindow();
map.setOnMyLocationChangeListener(null);
}
I'm working on a project which involves a "Points of Interest" locator. I have a generated Google Maps API v2 key and I've added all the proper permissions to the AndroidManifest (as you'll see below), and everything compiles...except for the map itself! There's a marker that shows your current location and as well as the GPS coordinates but not the map, which needless to say is essential. Also there are no runtime erros except that the LogCat says at points "There is too much output to process". Any help would be greatly appreciated.
Android Manifest
package="com.example.kavin_000.travelapplication" >
<!-- suppress AndroidDomInspection -->
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<permission
android:name="com.example.kavin_000.travelapplication.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.kavin_000.travelapplication.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/nyit_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".ow_main_page"
android:label="#string/app_name" >
</activity>
<activity
android:name=".manhattan_main_page"
android:label="#string/title_activity_manhattan_main_page" >
</activity>
<activity
android:name=".main_page"
android:label="Travel Application" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ow_campus_points_of_interest"
android:label="#string/title_activity_ow_campus_points_of_interest" >
</activity>
<activity
android:name=".manhattan_campus_points_of_interest"
android:label="#string/title_activity_manhattan_campus_points_of_interest" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="MY_KEY" />
</application>
</manifest>
Layout XML file
<RelativeLayout 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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".ow_main_page"
android:background="#ffffb502">
<fragment
android:id="#+id/googleMap"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_above="#+id/latlongLocation" />
<TextView
android:id="#+id/latlongLocation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:background="#ff058fff"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textColor="#ffffffff"
android:paddingLeft="5dp"
android:paddingRight="5dp" />
</RelativeLayout>
Java class in question
package com.example.kavin_000.travelapplication;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class ow_campus_points_of_interest extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GooglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_ow_campus_points_of_interest);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
}
It sounds like there may be an issue with your authorization on Google App Engine. Did you make sure to use the SHA1 fingerprint from your debug.keystore and not from your release keystore? Additionally, make sure that you are appending ;com.example.kavin_000.travelapplication to the end of the SHA1 fingerprint.
If you have not added your SHA1 fingerprint to the list of authorized applications, that is the issue. It can be done by finding your debug.keystore file (search on Google depending on your OS), and running the following command:
keytool -list -v -keystore debug.keystore