私のアプリで場所を取得しようとしています。どうやら、私は場所オブジェクトを埋もうとしている間に立ち往生しています。ロケーションを取得できません。Android Marshmallow
Log.d(TAG, "Location changed. New location: " + String.valueOf(mLastlocation.getLatitude()));
ことを呼び出そうとすると
import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
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 com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.whattaspot.R;
import com.whattaspot.parameters.ParameterConst;
import com.whattaspot.utils.ConnectionDetector;
import com.whattaspot.utils.LocationProvider;
public class NewsfeedActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{
public static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 0x3;
private final int PERMISSION_REQUEST_LOCATION = 0;
private final String TAG = NewsfeedActivity.class.getSimpleName();
private double currentLatitude, currentLongitude;
private String mLastToken;
private LocationProvider mLocationProvider;
private GoogleApiClient mGoogleApiClient;
// views
private View rootView;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLayoutManager;
private LocationRequest mLocationRequest = new LocationRequest();
private Location mLastlocation;
@SuppressWarnings("ConstantConditions")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newsfeed);
// Toolbar inizialization
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getString(R.string.title_newsfeed).toUpperCase());
// Restore preferences
SharedPreferences settings = getSharedPreferences(
ParameterConst.WHATTASPOT_TOKEN_TYPE, Activity.MODE_APPEND);
mLastToken = settings.getString(ParameterConst.PARAM_TOKEN_NAME, null);
// Inizializzo il Location provider
//mLocationProvider = new LocationProvider(this, this);
// Initialize views
rootView = findViewById(R.id.container);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.newsfeed_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
/* overridePendingTransition(0, 0); */
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mLocationRequest = LocationRequest.create()
.setInterval(10000)
.setFastestInterval(100)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
@Override
public void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
Log.d(TAG, "GoogleApiClient disconnect");
// Disconnect the GoogleApiClient
//mLocationProvider.disconnect();
}
@Override
public void onStart(){
mGoogleApiClient.connect();
super.onStart();
Log.d(TAG, "GoogleApiClient connect");
}
@Override
public void onResume() {
super.onResume();
// Check the internet connection
if (!ConnectionDetector.isNetworkAvailable(this)) {
Log.d(TAG, "No Internet connection.");
Snackbar.make(rootView, "No Internet connection.", Snackbar.LENGTH_LONG).show();
}
mGoogleApiClient.connect();
Log.d(TAG, "GoogleApiClient connect AGAIN");
}
@Override
public void onConnected(Bundle bundle) {
// Check permission for Android M
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Checkpoint 1");
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
Log.d(TAG, "Checkpoint 2");
String permit = String.valueOf(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION));
Log.d(TAG, permit);
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_LOCATION);
String granted = String.valueOf(PackageManager.PERMISSION_GRANTED);
Log.d(TAG, permit);
Log.d(TAG, granted);
}
}
Log.d(TAG, "Checkpoint 3");
}
@Override
public void onLocationChanged(Location location) {
mLastlocation = location;
}
@Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "GoogleApiClient connection has been suspended");
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.d(TAG, "GoogleApiClient connection failed");
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.d(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
Log.d(TAG, "In ORPR.");
switch (requestCode) {
case PERMISSION_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Checkpoint ORPR, Yes.");
if (mLastlocation == null) {
try {
if(mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastlocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.d(TAG, "Location retrieved.");
}
} catch (SecurityException ex){
Log.d(TAG, "Location not retrieved.");
}
} else {
Log.d(TAG, "Location not retrieved");
}
Log.d(TAG, "Location changed. New location: " + String.valueOf(mLastlocation.getLatitude()));
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
Log.d(TAG, "Checkpoint ORPR, No.");
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
私はこのエラーを取得する:私は私の場所を取得することはできないんだけど、なぜjava.lang.RuntimeException: Failure delivering result ResultInfo{[email protected]:requestPermissions:, request=0, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.myapp/com.myapp.activities.NewsfeedActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
あなたが任意のアイデアを持っていますか?
ありがとうございます!