【发布时间】:2015-03-26 10:35:22
【问题描述】:
我正在使用谷歌地图 v2。
我的代码在方法上被卡住了:
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
} // end onConnected
日志猫:
03-25 10:30:41.120 25816-25816/? E/dalvikvm﹕ Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zza
03-25 10:30:41.460 25816-25816/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.robot.myapplication.MainActivity.onConnected(MainActivity.java:66)
我怎么想,这一行的例外:
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(**mGoogleApiClient**);
但我已经创建了这个对象(mGoogleApiClient):
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
我怎么了?
完整代码:
public class MainActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
TextView mLatitudeText;
TextView mLongitudeText;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private static final int REQUEST_RESOLVE_ERROR = 1001;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView mLatitudeText = (TextView) findViewById(R.id.mLatitudeText);
TextView mLongitudeText = (TextView) findViewById(R.id.mLongitudeText);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
mGoogleApiClient.disconnect();
}
@Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
} // end onConnected
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult result) {
if (result.hasResolution()) {
try {
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
}
catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} //end if
} // end onConnectionFailed
}
【问题讨论】:
-
将此代码
mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build();移动到onCreate()方法上。 -
您的 android 清单文件中是否拥有所有正确的权限?
-
你使用哪个android api lvl?
标签: android nullpointerexception