Now I have a strange problem. I have FusedLocationApi code.check it.I'm mentioning only related codes :
现在我有一个奇怪的问题。我有FusedLocationApi代码。检查它。我只提到相关的代码:
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
@Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
}
@Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
}
Now the problem is,this code is working perfectly for this activity.But when I'm writing the same code for other activity of the same project,mLastLocation
is returning null and I am getting a java.lang.NullPointerException.
现在的问题是,这个代码非常适合这个活动。但是,当我为同一个项目的其他活动编写相同的代码时,mLastLocation返回null,我得到了一个java.lang.NullPointerException。
only difference for that class is that there I'm implementing OnMapReadyCallback
also.Does it make any difference?
唯一不同的是,我在这里也实现了OnMapReadyCallback。这有什么区别吗?
I've read all the Q&A on this topic but not getting any help. What's the mistake from my side?
我已经阅读了关于这个主题的所有问答,但没有得到任何帮助。我身边的错误是什么?
1 个解决方案
#1
0
onCreate method called first then followed by onStart. So in your case if mGoogleApiClient is not connected on create it will return null.move this code from onCreate to onStart
onCreate方法首先调用,然后是onStart。在你的例子中如果mGoogleApiClient没有连接在create上它将返回null。将此代码从onCreate移动到onStart。
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
i will do something like this onStart
我会在开始的时候做一些类似的事情。
if(mGoogleApiClient.isConnected()){
// check for last location
}else{
mGoogleApiClient.connect();
//check for last location
}
#1
0
onCreate method called first then followed by onStart. So in your case if mGoogleApiClient is not connected on create it will return null.move this code from onCreate to onStart
onCreate方法首先调用,然后是onStart。在你的例子中如果mGoogleApiClient没有连接在create上它将返回null。将此代码从onCreate移动到onStart。
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
i will do something like this onStart
我会在开始的时候做一些类似的事情。
if(mGoogleApiClient.isConnected()){
// check for last location
}else{
mGoogleApiClient.connect();
//check for last location
}