2017-10-15 1 views
-1

의 프래그먼트 내에서 권한을 요청한 후 앱이 다운 된 경우 휴대 전화의 GPS를 사용하여 조각에서 경도와 위도를 가져온 다음 해당 정보를 anopther 프래그먼트로 전달할 수있는 버튼을 사용하려고합니다.이 앱에서

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) 
+0

마에서 권한을 확인하는 방법에 대한 매우 명확한 다운 무식하게 예를 준

@ThetNaingMizo

에 의해 만들어진 대답에 내 충돌 문제를 해결 당신 AnroidManifest.xml 파일 안에''이 있습니까? 매니페스트 – Thracian

+0

제가 가지고 은 <안드로이드 권한 사용 이름 = "android.permission.INTERNET은이"/> 는 <사용 불허 로이드 : 이름 = "android.permission.ACCESS_COARSE_LOCATION는"/> 는 <사용 불허 로이드 : name = "android.permission.ACCESS_FINE_LOCATION"/> <사용 권한 android : name = "android.permission.ACCESS_NETWORK_STATE"/> @FatihOzcan –

+1

[NullPointerException은 무엇이며 어떻게 수정합니까?] (https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) –

답변

관련 문제