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

时间:2017-10-15 14:17:58

标签: java android android-fragments nullpointerexception

在这个应用程序中,我尝试使用片段中的按钮,使用手机的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();
                }
            }
        }
    }



}

我是碎片的新手,在我看来,他们可能在很多方面与我刚刚发现的活动如此不同。应用程序正常运行,直到我转到按钮并单击它,此时它崩溃。

下面的

是崩溃日志。

谢谢你的时间和帮助。

    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)

1 个答案:

答案 0 :(得分:0)

How to check permission in fragment

这个链接在@ThetNaingMizo

创建的答案中解决了我的崩溃问题

他给出了一个非常明确的愚蠢的例子,说明如何检查Activity Vs Fragment中的权限