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

时间:2017-01-08 20:16:02

标签: android nullpointerexception android-permissions

修改

现在该应用正在运行。但它只是在第一次启动后(安装后)请求许可。如果我离开应用程序(按下后退按钮),然后再启动它,它不会要求许可。为什么会这样?

不按后退按钮会通过调用onDestroy()来破坏活动,是否应该再次调用onCreate()方法?

原始问题

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

java.lang.RuntimeException: Failure delivering result 
ResultInfo{who=@android:requestPermissions:, request=10, result=-1,
data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has
extras) }} to activity
{com.example.hpi5.location/com.example.hpi5.location.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference

以下是我的活动代码:

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.content.pm.PackageManager;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button button ;
    LocationListener locationListener;
    LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        if (Build.VERSION.SDK_INT >=23 ){
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        10);
                return;
            }
        }

        button = (Button) findViewById(R.id.button);

        locationManager = (LocationManager)
                getSystemService(LOCATION_SERVICE);

        locationListener = new LocationListener()
        {

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onLocationChanged(Location location) {
                // TODO Auto-generated method stub
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                //double speed = location.getSpeed(); //spe2d in meter/minute
                //speed = (speed*3600)/1000;      // speed in km/minute
                Toast.makeText(getApplicationContext(), "lat" + latitude + "lon" + longitude,Toast.LENGTH_SHORT).show();
            }
        };




    }
    void requestUpdate(){
        button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[], @ NonNull int[] grantResults) {
        switch (requestCode) {
            case -1:{
                //hello
            }

            case 10: {
                if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    requestUpdate();
                }
            }

        }
    }



}

以下是logcat错误:

java.lang.RuntimeException: Failure delivering result
ResultInfo{who=@android:requestPermissions:, request=10, result=-1,
data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has
extras) }} to activity
{com.example.hpi5.location/com.example.hpi5.location.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
    android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
     on a null object reference
                                                                             at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
                                                                           at
    android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
                                                                            at android.app.ActivityThread.-wrap16(ActivityThread.java)
     android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:148)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                         Caused by: java.lang.NullPointerException: Attempt to invoke virtual
     method 'void
  android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
     on a null object reference
com.example.hpi5.location.MainActivity.requestUpdate(MainActivity.java:80)
     com.example.hpi5.location.MainActivity.onRequestPermissionsResult(MainActivity.java:95)
    android.app.Activity.dispatchRequestPermissionsResult(Activity.java:6553)
                                                                         at android.app.Activity.dispatchActivityResult(Activity.java:6432)
                                                                        at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
 android.app.ActivityThread.handleSendResult(ActivityThread.java:3742) 
                                                                        at android.app.ActivityThread.-wrap16(ActivityThread.java) 
 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393) 
                                                                        at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                         at android.os.Looper.loop(Looper.java:148) 
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                          at java.lang.reflect.Method.invoke(Native Method) 
     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

3 个答案:

答案 0 :(得分:4)

编辑Coarse Permission,按钮初始化。 onCreate()并将ponit添加为onRequestPermissionsResult()

由于NullPointException的空对象引起的错误是Button

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.content.pm.PackageManager;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

Button button ;
LocationListener locationListener;
LocationManager locationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            requestUpdate();
        }
    });

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission
                        (this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,},
                    10);
            return;
        }
    }

    locationManager = (LocationManager)
            getSystemService(LOCATION_SERVICE);

    locationListener = new LocationListener()
    {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            //double speed = location.getSpeed(); //spe2d in meter/minute
            //speed = (speed*3600)/1000;      // speed in km/minute
            Toast.makeText(getApplicationContext(), "lat" + latitude + "lon" + longitude,Toast.LENGTH_SHORT).show();
        }
    };
}

void requestUpdate(){    
  locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String permissions[], @ NonNull int[] grantResults) {

    switch (requestCode) {
        case -1:
            //hello
            break;


        case 10: 
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                requestUpdate();
            }else{
            //do something if permission not granted.
            }
            break;

    }
 }
}

答案 1 :(得分:2)

在初始化button之前请求权限,我假设回调在有机会完全初始化Button对象之前完成。尝试将权限检查移至onCreate的末尾,如果没有,请仔细检查按钮的ID是否正确。

答案 2 :(得分:0)

移动线

 button = (Button) findViewById(R.id.button);

之后的位置
setContentView(..);