在片段中使用RecyclerView时询问权限时,应用崩溃

时间:2019-06-22 06:04:56

标签: android-fragments android-recyclerview crash user-permissions

我正在recyclerView中显示所有歌曲,为此,我需要用户许可。现在,我已经在主Activity中实现了用于用户权限的代码,并且recyclerView是一个片段。因此,当应用程序要求用户权限时,只有用户权限对话框可见,但应用程序无法打开。

enter image description here

MainActivity.java

public class MainActivity extends AppCompatActivity {

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

        if(this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            requestStoragePermission();
        }else if(this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)==PackageManager.PERMISSION_GRANTED){
            //getSongArray();
            Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
        }

        ViewPager viewPager = findViewById(R.id.viewPagerId);
        viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
        viewPager.setPageTransformer(true,new ZoomOutPageTransform());

    }

    private static final int MY_PERMISSIONS_REQUEST = 100;
    private void requestStoragePermission(){
        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // file-related task you need to do.
                }
                else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }
        }
    }


}

RecyclerViewFragment

public class RecyclerViewFragment extends Fragment {

    public RecyclerView songListRecycleView;
    recyclerViewAdapter mAdapter;
    ArrayList<songInfo> songs;

    public void RecyclerViewFragment(){

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.recycler_view_fragment_layout,container,false);

        /**setting recycler view**/
        songListRecycleView = view.findViewById(R.id.songListViewId);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        songListRecycleView.setLayoutManager(mLayoutManager);

        // setting ArrayList
        songs = new ArrayList<>();

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

        Toast.makeText(view.getContext(), "hello", Toast.LENGTH_SHORT).show();
        Log.v("okay_till_now","yes");

        mAdapter = new recyclerViewAdapter(getActivity(),getSongArray());
        songListRecycleView.setAdapter(mAdapter);

    }


    public ArrayList<songInfo> getSongArray(){
        ArrayList<songInfo> songsList = new ArrayList<>();
        songInfo sInfo;

        Cursor c = getSongCursor();
        int songPathIndex = c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
        int songTitleIndex = c.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
        //Toast.makeText(, "", Toast.LENGTH_SHORT).show();

        sInfo = new songInfo("Hello Mayank","no path to this");
        songsList.add(sInfo);
        songsList.add(sInfo);
        Log.v("Cursor_length",""+c.getCount());
        for(int i=0;i<c.getCount();i++){
            //sInfo = new songInfo(c.getString(songTitleIndex),c.getString(songPathIndex));
            //songsList.add(sInfo);
        }
        return songsList;
    }

    public Cursor getSongCursor(){
        try{
            Uri externalUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            String[] projection = new String[]{
                    MediaStore.Audio.Media._ID,
                    MediaStore.Audio.Media.TITLE,
                    MediaStore.Audio.Media.ALBUM,
                    MediaStore.Audio.Media.DATA,
                    //MediaStore.Audio.Media._ID,
            };
            String selection = null;
            String[] selectionArgs = null;
            String sortOrder = MediaStore.Audio.Media.TITLE+" ASC";
            Cursor songCursor = getContext().getContentResolver().query(externalUri,projection,selection,selectionArgs,sortOrder);
            return songCursor;
        }catch (Exception e){
            return null;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}

错误

2019-06-22 11:44:05.909 14962-14962/com.example.mymusicplayer E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.mymusicplayer, PID: 14962
    java.lang.NullPointerException: Attempt to invoke interface method 'int android.database.Cursor.getColumnIndexOrThrow(java.lang.String)' on a null object reference
        at com.example.mymusicplayer.RecyclerViewFragment.getSongArray(RecyclerViewFragment.java:78)
        at com.example.mymusicplayer.RecyclerViewFragment.onViewCreated(RecyclerViewFragment.java:60)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1471)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
        at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2243)
        at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:654)
        at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:146)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1244)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1092)
        at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1622)
        at android.view.View.measure(View.java:22105)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6606)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
        at android.view.View.measure(View.java:22105)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6606)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:22105)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6606)
        at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:401)
        at android.view.View.measure(View.java:22105)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6606)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:22105)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6606)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
        at android.view.View.measure(View.java:22105)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6606)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at com.android.internal.policy.DecorView.onMeasure(DecorView.java:727)
        at android.view.View.measure(View.java:22105)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2467)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1549)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1806)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1437)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6886)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1029)
        at android.view.Choreographer.doCallbacks(Choreographer.java:841)
        at android.view.Choreographer.doFrame(Choreographer.java:772)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1015)
        at android.os.Handler.handleCallback(Handler.java:794)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:176)
2019-06-22 11:44:05.909 14962-14962/com.example.mymusicplayer E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:6651)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)

0 个答案:

没有答案