0

RecyclerView adapter doesn't load data on first launch after Permission check. I have to re-tap the tab to get the data.

I have already visited/tried these links -

-- RecyclerView doesn't load data in first launch using FirebaseRecyclerAdapter

-- RecyclerView doesn't load items on first start of activity

Here's code -

onCreateView -

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

recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);

if (checkAndRequestPermissions()) {
    loadAudio();
}

return view;
}

onRequestPermissionResult -

loadAudio() //  call to method if permission granted

loadAudio() -

private void loadAudio() {
ContentResolver contentResolver = getActivity().getContentResolver();
... /** accessing contents */ ...

   if (cursor != null) {
        cursor.close();
      }
  initRecyclerView();
 }

initRecyclerView -

private void initRecyclerView() {

// To check if this method called at first time tab click
// which it doesn't.
System.out.println("==== mAudioList ==="+mAudioList+"::");
// ------

if (mAudioList != null && mAudioList.size() > 0) {
    AudioAdapter adapter = new AudioAdapter(mAudioList, getActivity());
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(linearLayoutManager);
    DIviderItemDecoration dividerItemDecoration = new DIviderItemDecoration(getContext(), linearLayoutManager.getOrientation());
    recyclerView.addItemDecoration(dividerItemDecoration);

    // thought this would help
    adapter.notifyDataSetChanged();

    recyclerView.setAdapter(adapter);
}
}

onRequestPermissionResult -

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

    String TAG = "LOG_PERMISSION";
    Log.d(TAG, "Permission callback called-------");
    switch (requestCode) {
        case REQUEST_ID_MULTIPLE_PERMISSIONS: {

            Map<String, Integer> perms = new HashMap<>();
            // Initialize the map with both permissions
            perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
            // Fill with actual results from user
            if (grantResults.length > 0) {
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // Check for both permissions

                if (perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        ) {
                    Log.d(TAG, "Phone state and storage permissions granted");
                    loadAudio();
                } else {
                    Log.d(TAG, "Some permissions are not granted ask again ");
                    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_PHONE_STATE)) {
                        showDialogOK("Phone state and storage permissions required for this app",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        switch (which) {
                                            case DialogInterface.BUTTON_POSITIVE:
                                                checkAndRequestPermissions();
                                                break;
                                            case DialogInterface.BUTTON_NEGATIVE:
                                                // proceed with logic by disabling the related features or quit the app.
                                                break;
                                        }
                                    }
                                });
                    }
                    else {
                        Toast.makeText(getContext(), "Go to settings and enable permissions", Toast.LENGTH_LONG)
                                .show();
                    }
                }
            }
        }
    }

}

I don't know how to fix this. Please, Any help would be Appreciated. Already asked this question here - question but that didn't worked.

Note : There's no code in my other fragment lifecycle methods.

Ansh
  • 365
  • 6
  • 19
  • have u tried to debug are u getting data in mAudioList? – Pavan Jun 07 '17 at 16:56
  • You need to handle the callback `public void onRequestPermissionsResult` in your Activity, if you request Permissions - I would assume that if you restarted the app after permissions granted that if `loadAudio()` is correct would work as expected. – Mark Jun 07 '17 at 17:04
  • @Pavan Yeah! But only after 2nd tab click! Not during 1st tab click. Tho after first time it works perfectly! – Ansh Jun 07 '17 at 17:05
  • What error log on first attempt where are u requesting permission as mark mentioned – Pavan Jun 07 '17 at 17:07
  • There's no error log! Even the sysout inside initRecyclerView not getting executed. – Ansh Jun 07 '17 at 17:10
  • @MarkKeen Yeah! It does or if I 2nd click on tab or migrate from other fragment to this one, then it loads the data. Any solution other than adding permission inside MainActivity because according to Android Docs, One should ask for permission when it's needed. – Ansh Jun 07 '17 at 17:12
  • post your `onRequestPermissionsResult` method – Veneet Reddy Jun 07 '17 at 17:16
  • @VeneetReddy check updated Question – Ansh Jun 07 '17 at 17:27

1 Answers1

0

Finally! I got the answer. The problem is not with the permission but with onRequestPermissionResult as it's not getting callback!

This answer helped me.

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    Fragment fragment = getSupportFragmentManager().findFragmentById(/**fragmentContainer*/);
    if (fragment != null) {
        fragment.onRequestPermissionsResult(requestCode&0xff, permissions, grantResults);
    }
}

Though they originally answered for Nested Fragment but it also work for top-level fragments. If anyone else having same problem then check it out.

Please visit the above link to know how it works.

Ansh
  • 365
  • 6
  • 19