我正在尝试运行地图应用,但显示出一些错误
logcat的:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tracker.systechdigital.realtimetrackingandmonitoring/com.tracker.systechdigital.realtimetrackingandmonitoring.NavigationDrawerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.api.GoogleApiClient.connect()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2521)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2595)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5631)
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:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
摇篮:
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.google.android.gms:play-services:9.6.1'
compile 'com.google.maps.android:android-maps-utils:0.3.4'
compile 'com.android.support:support-v4:23.1.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.google.android.gms:play-services-location:9.6.1'
compile 'com.google.android.gms:play-services-maps:9.6.1'
}
爪哇:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
context = NavigationDrawerActivity.this;
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View hView = navigationView.getHeaderView(0);
ownProfilePic = (ImageView) hView.findViewById(R.id.ownImageShowDrawerHeaderIvId_navigationDrawer);
ownNameShow = (TextView) hView.findViewById(R.id.showUserNameTvId_navigationDrawer);
/****************************** own profile name and image show ************************** */
ownNameShow.setText(UserInfo.getOwnProfileName());
// new ImageDownloaderTask(ownProfilePic).execute(UserInfo.ownProfilePicUrl);
Picasso.with(context).load(UserInfo.getOwnProfilePicUrl()).resize(100, 100).placeholder(R.drawable.profile_show).error(R.drawable.profile_show).transform(new CircleTransform()).into(ownProfilePic);
// 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);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
this.lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = lm.getBestProvider(criteria, false);
location = this.lm.getLastKnownLocation(provider);
this.locationListener = new NavigationDrawerActivity();
this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, locationListener);
if (location != null) {
setUpMapIfNeeded(location);
updateUserLatLong(location);
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
if (client == null)
client = new GoogleApiClient.Builder(this).addOnConnectionFailedListener(this).addConnectionCallbacks(this).addApi(AppIndex.API).build();
//route
}
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
setUpMapIfNeeded(location);
}
}
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
// if(client!=null)
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Maps Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.tracker.systechdigital.realtimetrackingandmonitoring/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
@Override
public void onMapReady(GoogleMap googleMap) {
this.mMap = googleMap;
mMap.setMyLocationEnabled(true);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
return;
}
Location location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
setUpMapIfNeeded(location);
UserInfo.setLat(location.getLatitude());
UserInfo.setLng(location.getLongitude());
UserInfo.setLocation(location);
}
//setUpMapIfNeeded(location);
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(context, Live_MapActivity.class);
intent.putExtra("Driver", "anyFriend");
UserInfo.setFriendsId(friendIds.optString(marker.getId()));
startActivity(intent);
Toast.makeText(context, "You tracking " + marker.getTitle(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onLocationChanged(Location location) {
if (location != null && SharedPreference.getDefaults("ownUserId", context) != "0") {
updateUserLatLong(location);
//setUpMapIfNeeded(location);
float speed = location.getSpeed();
UserInfo.setSpeed(speed);
UserInfo.setLat(location.getLatitude());
UserInfo.setLng(location.getLongitude());
UserInfo.setLocation(location);
}
userPosition = new LatLng(location.getLatitude(),
location.getLongitude());
if (mMap != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userPosition,
12));
mMap.setMapType(UserInfo.getMapType());
}
//updateUserLatLong(location);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
// Criteria criteria = new Criteria();
// criteria.setAccuracy(Criteria.ACCURACY_COARSE);
LatLng userPosition = new LatLng(location.getLatitude(),
location.getLongitude());
if (mMap != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userPosition,
UserInfo.getZoomLevel()));
mMap.setMapType(UserInfo.getMapType());
userFriendsPos();
}
// 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.
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
// mMap.setMyLocationEnabled(true);
}
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Maps Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.tracker.systechdigital.realtimetrackingandmonitoring/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
@Override
public void onConnected(Bundle bundle) {
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Maps Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.tracker.systechdigital.realtimetrackingandmonitoring/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
location = LocationServices.FusedLocationApi.getLastLocation(
client);
}
任何人都可以解决这个问题。我找不到那里所需的正确的东西。我编辑了这个问题并添加了oncreated方法
答案 0 :(得分:1)
使用以下代码替换onCreate方法:
private static final int MY_PERMISSION_REQUEST_CODE = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
context = NavigationDrawerActivity.this;
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View hView = navigationView.getHeaderView(0);
ownProfilePic = (ImageView) hView.findViewById(R.id.ownImageShowDrawerHeaderIvId_navigationDrawer);
ownNameShow = (TextView) hView.findViewById(R.id.showUserNameTvId_navigationDrawer);
/****************************** own profile name and image show ************************** */
ownNameShow.setText(UserInfo.getOwnProfileName());
// new ImageDownloaderTask(ownProfilePic).execute(UserInfo.ownProfilePicUrl);
Picasso.with(context).load(UserInfo.getOwnProfilePicUrl()).resize(100, 100).placeholder(R.drawable.profile_show).error(R.drawable.profile_show).transform(new CircleTransform()).into(ownProfilePic);
// 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);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_PERMISSION_REQUEST_CODE
);
return;
} else {
setupLocation();
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
if (client == null)
client = new GoogleApiClient.Builder(this)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(AppIndex.API)
.build();
//route
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_REQUEST_CODE:
if (grantResults[0] == PackageManager.PERMISSION_DENIED || grantResults[1] == PackageManager.PERMISSION_DENIED) {
// TODO
finish();
return;
}
setupLocation();
break;
}
}
private void setupLocation() {
this.lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = lm.getBestProvider(criteria, false);
location = this.lm.getLastKnownLocation(provider);
this.locationListener = new NavigationDrawerActivity();
this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, locationListener);
if (location != null) {
setUpMapIfNeeded(location);
updateUserLatLong(location);
}
}