从片段内请求权限后应用程序崩溃

Posted

技术标签:

【中文标题】从片段内请求权限后应用程序崩溃【英文标题】:app crashing after requesting permission from within a fragment 【发布时间】:2018-03-27 03:09:26 【问题描述】:

在这个应用程序中,我尝试使用片段中的按钮来使用手机的 GPS 获取片段中的经度和纬度,然后可能将该信息传递到另一个片段中。

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;


/**
 * A simple @link Fragment subclass.
 */
public class GalleryFragment extends Fragment 
    FragmentActivity mContext = getActivity();
    double latitude = 0;//21.6001;
    double longitude = 0;//39.136;




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) 

        // Inflate the layout for this fragment
        final View v = inflater.inflate(R.layout.fragment_gallery, container, false);


        Button gpsBtn = (Button) v.findViewById(R.id.gpsBtn);
        gpsBtn.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                //VVVVVVVVV// HERE IS WHERE THE CRASH HAPPENS...
                if (ContextCompat.checkSelfPermission(mContext,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(mContext,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
                    ActivityCompat.requestPermissions(mContext,new String[]Manifest.permission.ACCESS_FINE_LOCATION, 1);

                 else 
                    Toast.makeText(mContext, "You need have granted permission", Toast.LENGTH_SHORT).show();
                    GPSTracker gps = new GPSTracker(mContext, GalleryFragment.this);

                    // Check if GPS enabled

                    if (gps.canGetLocation()) 

                        latitude = gps.getLatitude();
                        longitude = gps.getLongitude();

                        // \n is for new line

                        Toast.makeText(getActivity().getApplicationContext(),
                                "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                     else 

                        // Can't get location.

                        // GPS or network is not enabled.

                        // Ask user to enable GPS/network in settings.

                        gps.showSettingsAlert();
                    
                
                //setMyPrayerList(latitude,longitude,prayerNamez,prayerTimez);

            
        );
        return v;
    

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

        switch (requestCode) 
            case 1: 
                // If request is cancelled, the result arrays are empty.

                if (grantResults.length > 0

                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) 

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    GPSTracker gps = new GPSTracker(mContext, GalleryFragment.this);

                    // Check if GPS enabled

                    if (gps.canGetLocation()) 

                        double latitude = gps.getLatitude();
                        double longitude = gps.getLongitude();

                        // \n is for new line

                        Toast.makeText(getActivity().getApplicationContext(),
                                "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                     else 
                        // Can't get location.

                        // GPS or network is not enabled.

                        // Ask user to enable GPS/network in settings.

                        gps.showSettingsAlert();
                    

                 else 

                    // permission denied, boo! Disable the

                    // functionality that depends on this permission.
                    Toast.makeText(mContext, "You need to grant permission", Toast.LENGTH_SHORT).show();
                
            
        
    




我对 Fragment 不熟悉,在我看来,它们在许多方面与我刚刚发现的活动如此不同。该应用程序正常运行,直到我翻转到按钮并单击它时它崩溃。

下面附上崩溃日志。

感谢您的时间和帮助。

    10-15 05:52:27.500 26041-26041/com.example.majidalashari.sanad E/AndroidRuntime: FATAL EXCEPTION: main        
                                                                                     Process: com.example.majidalashari.sanad, PID: 26041        
                                                                                     java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String,         int, int)' on a null object reference
                                                                                         at android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:432)
                                                                                         at com.example.majidalashari.sanad.GalleryFragment$1.onClick(GalleryFragment.java:43)
                                                                                         at android.view.View.performClick(View.java:5669)
                                                                                         at android.view.View$PerformClick.run(View.java:22546)
                                                                                         at android.os.Handler.handleCallback(Handler.java:751)
                                                                                         at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                         at android.os.Looper.loop(Looper.java:154)
                                                                                         at android.app.ActivityThread.main(ActivityThread.java:6334)
                                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

【问题讨论】:

你的 AnroidManifest.xml 文件中有 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 吗? 在清单中我有: @FatihOzcan What is a NullPointerException, and how do I fix it?的可能重复 我不确定为什么它会指向 null mContext好像是null,换成FragmentActivity.this试试 【参考方案1】:

How to check permission in fragment

这个链接解决了我在@ThetNaingMizo 创建的答案中崩溃的问题

他给出了一个非常清晰的示例,说明如何在 Activity Vs Fragment 中检查权限

【讨论】:

以上是关于从片段内请求权限后应用程序崩溃的主要内容,如果未能解决你的问题,请参考以下文章

android studio中片段内的RecyclerView使我的应用程序崩溃

在Android Fragment中允许权限导致应用程序崩溃?

请求权限/Android Studio 时应用程序崩溃

从现有片段启动其他片段时应用程序崩溃

google-map 片段应用程序在模拟器中崩溃后打开 WebView 活动

由于缺少权限请求,应用程序崩溃 [重复]