java.lang.RuntimeException:传递结果失败ResultInfo {who = @android:requestPermissions :, request = 1,result = -1,data = Intent

时间:2017-11-23 12:09:11

标签: android android-intent google-maps-api-3

我的应用程序允许用户在按下按钮时找到他们当前的位置。每当应用程序第一次启动时,它会询问用户权限,但是在授予权限时崩溃会导致以下logcat错误:< / p>

FATAL EXCEPTION: mainProcess: com.shubhamsharma.idonate, PID: 17404
java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=1, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.shubhamsharma.idonate/com.shubhamsharma.idonate.iDonate}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
                                                                               at android.app.ActivityThread.deliverResults(ActivityThread.java:4123)
                                                                               at android.app.ActivityThread.handleSendResult(ActivityThread.java:4166)
                                                                               at android.app.ActivityThread.-wrap20(ActivityThread.java)
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1562)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                               at android.os.Looper.loop(Looper.java:163)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6237)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                            Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
                                                                               at com.shubhamsharma.idonate.iDonate.onRequestPermissionsResult(iDonate.java:165)
                                                                               at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:7263)
                                                                               at android.app.Activity.dispatchActivityResult(Activity.java:7115)
                                                                               at android.app.ActivityThread.deliverResults(ActivityThread.java:4119)
                                                                               at android.app.ActivityThread.handleSendResult(ActivityThread.java:4166) 
                                                                               at android.app.ActivityThread.-wrap20(ActivityThread.java) 
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1562) 
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                               at android.os.Looper.loop(Looper.java:163) 
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6237) 
                                                                               at java.lang.reflect.Method.invoke(Native Method) 
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877) 
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

流程是这样的 主要活动(获取登录ID和密码并从firebase检查)---&gt;然后是idonate Activity请求许可然后崩溃

我的主要活动代码

公共类MainActivity扩展了AppCompatActivity {

Button login, register;
EditText email,password;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener firebaseAuthListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    email = (EditText) findViewById(R.id.email);
    password = (EditText) findViewById(R.id.password);
    login = (Button) findViewById(R.id.button2);
    register=(Button)findViewById(R.id.button1);
    mAuth = FirebaseAuth.getInstance();



    firebaseAuthListener = new FirebaseAuth.AuthStateListener() {

        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if (user != null) {

                Intent intent = new Intent(MainActivity.this, iDonate.class);
                startActivity(intent);
                return;

            }
        }


    };

    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final String log= email.getText().toString();
            final String pas= password.getText().toString();
            if(log.length()!=0 && pas.length()!=0) {
                mAuth.createUserWithEmailAndPassword(log, pas).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        if (!task.isSuccessful()) {
                            Toast.makeText(getApplicationContext(), "Something Went Wrong", Toast.LENGTH_LONG).show();
                        } else {
                            String userid = mAuth.getCurrentUser().getUid();
                            DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Drivers").child(userid);
                            current_user_db.setValue(true);
                        }
                    }
                });
            }
            else{
                Toast.makeText(getApplicationContext(), "Login Id or Password cannot be Empty", Toast.LENGTH_SHORT).show();
                email.setText("");
                password.setText("");

            }
        }
    });

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final String log = email.getText().toString();
            final String pas = password.getText().toString();
            if(log.length()!=0 && pas.length()!=0) {
                mAuth.signInWithEmailAndPassword(log, pas).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {

                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (!task.isSuccessful())
                            Toast.makeText(getApplicationContext(), "Signup Error", Toast.LENGTH_SHORT).show();

                        else {
                            Intent intent = new Intent(MainActivity.this, iDonate.class);
                            startActivity(intent);
                            finish();
                            return;
                        }
                    }
                });

            }
            else{
                Toast.makeText(getApplicationContext(), "Login Id or Password cannot be Empty", Toast.LENGTH_SHORT).show();
                email.setText("");
                password.setText("");
            }
        }
    });


}



@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(firebaseAuthListener);
}

@Override
protected void onStop() {
    super.onStop();
    mAuth.removeAuthStateListener(firebaseAuthListener);

}

}

下面的idonate代码

public class iDonate extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

    private GoogleMap mMap;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    LocationRequest mLocationRequest;
    SupportMapFragment mapFragment;
    private Button mlogout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_i_donate);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        mlogout=(Button)findViewById(R.id.logout);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);

        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(iDonate.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
      //  return;
        } else {
            mapFragment.getMapAsync(this);

        }


        mlogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FirebaseAuth.getInstance().signOut();
                Intent intent=new Intent(getApplicationContext(),MainActivity.class);
                startActivity(intent);
                finish();
                return;

            }
        });


    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        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(iDonate.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
          //  return;
        }

        buildGoogleApiClient();
         mMap.setMyLocationEnabled(true);




    }


    protected synchronized void buildGoogleApiClient(){


        mGoogleApiClient= new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        mGoogleApiClient.connect();


    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        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(iDonate.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
        return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);


    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {

        mLastLocation=location;
        LatLng latLng=new LatLng(location.getLatitude(),location.getLongitude());

        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(14));

      String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
      DatabaseReference ref = FirebaseDatabase.getInstance().getReference("DriversAvailable");

        GeoFire geoFire  = new GeoFire(ref);
        geoFire.setLocation(userId,new GeoLocation(location.getLatitude(),location.getLongitude()));


    }

    final int LOCATION_REQUEST_CODE = 1;
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
       // Toast.makeText(getApplicationContext(), String.valueOf(grantResults[0]), Toast.LENGTH_LONG).show();
        switch (requestCode) {
            case LOCATION_REQUEST_CODE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    mapFragment.getMapAsync(this);
             //   break;
                }
                else {
                    Toast.makeText(getApplicationContext(), "Please allow your GPS Permission", Toast.LENGTH_LONG).show();
                }
              //  return;
                break;
            }
        }
    }
    public boolean hasAllPermissionsGranted(@NonNull int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onStop() {
        super.onStop();

        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        FirebaseUser userId = FirebaseAuth.getInstance().getCurrentUser();/////////////////////////////
        DatabaseReference ref = FirebaseDatabase.getInstance().getReference("DriversAvailable");
     //   Toast.makeText(getApplicationContext(),userId.getUid(),Toast.LENGTH_LONG).show();
        GeoFire geoFire = new GeoFire(ref);
        geoFire.removeLocation(userId.getUid());
       // return;
    }
}

1 个答案:

答案 0 :(得分:0)

mapFragment.getMapAsync(this)返回null,因此检查该类