Android mGoogleApiClient-地理位置应用程序上的空值
我正在构建一个地理定位应用程序,但我无法让它运行。mGoogleApiClient已生成并具有正常值,但在调用创建对象的方法后,它将变为null,因此无法连接。我已经通过调试模式看到了这一点。知道发生了什么吗?这是代码。manifest和build.gradle文件中的所有内容都是正确的;基本上我遵循了这个教程 该应用程序还集成了Parse。我正在虚拟设备上开发Android Studio 以下是调试模式的屏幕截图,即mGoogleApiClient对象:Android mGoogleApiClient-地理位置应用程序上的空值,android,api,Android,Api,我正在构建一个地理定位应用程序,但我无法让它运行。mGoogleApiClient已生成并具有正常值,但在调用创建对象的方法后,它将变为null,因此无法连接。我已经通过调试模式看到了这一点。知道发生了什么吗?这是代码。manifest和build.gradle文件中的所有内容都是正确的;基本上我遵循了这个教程 该应用程序还集成了Parse。我正在虚拟设备上开发Android Studio 以下是调试模式的屏幕截图,即mGoogleApiClient对象: 您使用了错误的变量范围。您的问题是您
您使用了错误的变量范围。您的问题是您正在使用局部变量存储GoogleAppClient:
public void buildGoogleApiClient() {
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
}//end of function buildGoogleApiClient
相反,请使用您的字段:
public void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
}//end of function buildGoogleApiClient
我想你忘了初始化mGoogleApiClient
private void initGoogleApiClient(Context context) {
if (!isGooglePlayServicesAvailable(context)) {
Toast.makeText(context, "Cannot Auto Locate", Toast.LENGTH_SHORT).show();
isGoogleServicesAvailable = false;
return;
} else {
isGoogleServicesAvailable = true;
mGoogleApiClient = (new GoogleApiClient.Builder(context)).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
return;
}
}
你在哪里初始化mGoogleApiClient?啊,真是个愚蠢的错误!非常感谢你!!但是现在,当我尝试在虚拟设备上启动应用程序时,出现了这个错误。。。致命异常:主进程:com.parse.starter,PID:1280 java.lang.ClassCastException:com.parse.starter.main无法将活动强制转换为com.google.android.gms.location.LocationListener此方法中存在问题。。。受保护的void startLocationUpdates(){LocationServices.FusedLocationApi.requestLocationUpdates(mgoogleapClient,mlLocationRequest,(com.google.android.gms.location.LocationListener)this);}但是如果我这样离开,我会收到错误消息,不清楚第三个参数上应该是什么:受保护的void startLocationUpdates(){LocationServices.FusedLocationApi.requestLocationUpdates(mgoogleapClient,mLocationRequest,this);}已解决;“this”是一个LocationListener对象,我没有导入GoogleAPI LocationListener类。一切都解决了,非常感谢大家:)
private void initGoogleApiClient(Context context) {
if (!isGooglePlayServicesAvailable(context)) {
Toast.makeText(context, "Cannot Auto Locate", Toast.LENGTH_SHORT).show();
isGoogleServicesAvailable = false;
return;
} else {
isGoogleServicesAvailable = true;
mGoogleApiClient = (new GoogleApiClient.Builder(context)).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
return;
}
}