androidreact-nativemediastore

React native search for documents(.pdf, .doc, .xlsx) in device


I am working on an app to get all documents like .pdf .doc .docx .ppt .pptx .xls .txt .xlsx. ihave tried rn-fetch-blob and react-native-fs but there are giving only directory status.

useEffect(() => {
  const fetchdocuments = async () => {
    RNFetchBlob.fs.lstat(RNFetchBlob.fs.dirs.SDCardDir).then((data) => {
      data.forEach(element => {
          console.log(element)
      });
    }).catch((error) => {
      console.log(error)
    })
  }
  fetchdocuments()
},[])

I also tried this library react-native-get-music-files but it returns only the mediastore file API for android but don't know how to implement this in react-native. any help will be really appreciated.


Solution

  • here I have created a native module for this. code is given below

    package com.dconverter;
    import android.app.Activity;
    import android.content.ContentResolver;
    import android.content.Context;
    import android.content.Intent;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.provider.Settings;
    import android.util.Log;
    
    import androidx.annotation.Nullable;
    import androidx.annotation.RequiresApi;
    
    import com.facebook.react.ReactActivity;
    import com.facebook.react.bridge.ActivityEventListener;
    import com.facebook.react.bridge.Callback;
    
    import com.facebook.react.bridge.Promise;
    import com.facebook.react.bridge.ReactApplicationContext;
    import com.facebook.react.bridge.ReactContextBaseJavaModule;
    import com.facebook.react.bridge.ReactMethod;
    import com.facebook.react.bridge.WritableArray;
    import com.facebook.react.bridge.WritableMap;
    import com.facebook.react.bridge.WritableNativeArray;
    import com.facebook.react.bridge.WritableNativeMap;
    
    import java.util.Objects;
    
    public class CustomerMediaStore extends ReactContextBaseJavaModule implements ActivityEventListener {
        private final ReactApplicationContext reactContext;
        private int version = Build.VERSION.SDK_INT;
        @Override
        public String getName() {
            return "CustomerMediaStore";
        }
    
        public CustomerMediaStore(ReactApplicationContext reactContext) {
            super(reactContext);
            this.reactContext = reactContext;
            reactContext.addActivityEventListener(this);
        }
    
        @ReactMethod
        public void GetFiles(final Callback successCallback, final Callback errorCallback){
            if(version <= 19){
                getSongs( successCallback, errorCallback);
            }else{
                Thread bgThread = new Thread(null, new Runnable() {
                    @Override
                    public void run() {
                        getSongs(successCallback, errorCallback);
                    }
                }, "asyncTask", 1024);
                bgThread.start();
            }
    
        }
    
        private void getSongs (final Callback successCallback, final Callback errorCallback) {
            ContentResolver musicResolver = reactContext.getApplicationContext().getContentResolver();
            Uri uri = MediaStore.Files.getContentUri("external");
            try {
                WritableArray jsonArray = new WritableNativeArray();
                String[] projection = {
                        MediaStore.Files.FileColumns._ID,
                        MediaStore.Files.FileColumns.MIME_TYPE,
                        MediaStore.Files.FileColumns.DATE_ADDED,
                        MediaStore.Files.FileColumns.DATE_MODIFIED,
                        MediaStore.Files.FileColumns.DISPLAY_NAME,
                        MediaStore.Files.FileColumns.DATA,
                        MediaStore.Files.FileColumns.TITLE,
                        MediaStore.Files.FileColumns.SIZE,
                };
                String mimeType = "application/pdf";
                String selection = MediaStore.Files.FileColumns.MIME_TYPE + " IN ('" + mimeType + "')"
                        + " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'application/vnd%'"  // .docx , .xlsx , .pptx  .xls
                        + " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE '%application/msword'"  // .doc
                        + " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'application/mspowerpoint'"  // .ppt
                        + " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'text/plain'"  // .txt
                      //  + " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE '%/%'"   // all type of douments audio/vidoe/ evey thing
                        + " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'application/rtf'"  // wordpad
                        + " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'font/otf'"  // .otf
                        + " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'application/vnd.oasis.opendocument.spreadsheet'"  // .ods
                        + " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'application/vnd.oasis.opendocument.text'"   // .otd
                        ;
                String orderBy = MediaStore.Files.FileColumns.DATE_ADDED;
                Cursor cursor = musicResolver.query(uri, projection, selection,null,orderBy);
                if (cursor != null && cursor.getCount() > 0) {
                    Log.e("Musica", String.valueOf(cursor.getCount()));
                    cursor.moveToFirst();
                    do {
                        WritableMap item = new WritableNativeMap();
                        item.putString("id", String.valueOf(cursor.getString(0)));
                        item.putString("minetype", String.valueOf(cursor.getString(1)));
                        item.putString("dateadded", String.valueOf(cursor.getString(2)));
                        item.putString("datemodified", String.valueOf(cursor.getString(3)));
                        item.putString("displayname", String.valueOf(cursor.getString(4)));
                        item.putString("uri",String.valueOf(cursor.getString(5)));
                        item.putString("title", String.valueOf(cursor.getString(6)));
                        item.putString("size", String.valueOf(cursor.getString(7)));
                        jsonArray.pushMap(item);
                    } while (cursor.moveToNext());
                } else {
                    String msg = "cursor is either null or empty ";
    
                    Log.e("Musica", String.valueOf(cursor.getCount()));
                }
    
                cursor.close();
                successCallback.invoke(jsonArray);
            }catch (Exception e) {
                errorCallback.invoke(e.getMessage());
                Log.e("Musica", e.getMessage());
            }
        }
        @RequiresApi(api = Build.VERSION_CODES.R)
        @ReactMethod private void  checkStorgePermision(Promise promise){
    
        }
    
        @RequiresApi(api = Build.VERSION_CODES.R)
        @ReactMethod private void checkStorgaePermission(Promise promise){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                promise.resolve(Environment.isExternalStorageManager());
            }
        }
    
        @ReactMethod
        private  void  askforscopestoragepermission(){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if(!Environment.isExternalStorageManager())
                {
                    askAndroid11StoragePermission(reactContext);
                }
    
            }
        }
        @RequiresApi(Build.VERSION_CODES.R)
        private void askAndroid11StoragePermission(Context context )
        {
            try {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.addCategory("android.intent.category.DEFAULT");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("data",Uri.parse(String.format("package:%s",context.getApplicationContext().getPackageName())));
                getReactApplicationContext().startActivityForResult(intent,2296,  null);
            }
            catch (Exception e){
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getReactApplicationContext().startActivityForResult(intent,2296,  null);
            }
        }
    //    @Override
    //    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    //        super.onActivityResult(requestCode, resultCode, data);
    //        if (requestCode == 2296) {
    //            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
    //                if (Environment.isExternalStorageManager()) {
    //                    // perform action when allow permission success
    //                } else {
    //
    //                }
    //            }
    //        }
    //    }
        @Override
        public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
            Log.e("Musics", String.valueOf(requestCode +  requestCode));
        }
    
        @Override
        public void onNewIntent(Intent intent) {
    
        }
    }
    

    Here is the usage example

    import React, { useEffect, useState } from 'react';
    import {
      SafeAreaView,
      PermissionsAndroid,
      StatusBar,
      StyleSheet,
      Text,
      View,
      FlatList,
      NativeModules,Platform, addons
    } from 'react-native';
    
    
    const {CustomerMediaStore} = NativeModules;
    
    const calculateSize = (bytes, decimals = 2) => {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const dm = decimals < 0 ? 0 : decimals;
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
    }
    const Item = ({ title, dateadded, datemodified, size }) => { 
     let dateModified = (new Date(datemodified*1000));
     let dateAdded = new Date(dateadded*1000)
      return (
      <View style={styles.item}>
        <Text style={styles.title}>Name: {title}</Text>
        <Text>Date Modified: {('0' + dateModified.getUTCDate()).slice(-2) + '-' + ('0' + dateModified.getUTCMonth()).slice(-2) + '-' + dateModified.getUTCFullYear()  }</Text>
        <Text>Date Added: {('0' + dateAdded.getUTCDate()).slice(-2) + '-' + ('0' + dateAdded.getUTCMonth()).slice(-2) + '-' + dateAdded.getUTCFullYear() }</Text>
        <Text>Size: {calculateSize(size*1)}</Text>
      </View>
    )}
    
    
    const App = () => {
      
      const [data, setData] = useState([])
    
      useEffect(() => {
        requestCameraPermission()
         
      },[])
    
      const requestCameraPermission = async () => {
       
        if(Platform.OS === "android"){
          if(Platform.Version >= "29"){
              CustomerMediaStore.checkStorgaePermission().then( async(data) => {
                if(!data){
                  CustomerMediaStore.askforscopestoragepermission();
                }else{
                  try {
                    const granted = await PermissionsAndroid.request(
                      PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
                      {
                        title: "Document Reader App Storage Permission",
                        message:
                          "Cool Photo App needs access to your Storage" +
                          "so you can take awesome pictures.",
                        buttonNeutral: "Ask Me Later",
                        buttonNegative: "Cancel",
                        buttonPositive: "OK"
                      }
                    );
                    console.log(granted)
                    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                      try {
                        myGetFiles().then((data) => {
                          console.log(data.length,"length")
                          setData(data)
                        }).catch((err) => {
                          console.log(err,"error")
                        })
                      }
                      catch (err) {
                        console.log(err)
                      }
                    } else {
                      console.log("Storage Permission is required permission denied");
                    }
                  } catch (err) {
                    console.warn(err);
                  }
                }
              })
            
          }else {
            try {
              const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
                {
                  title: "Document Reader App Storage Permission",
                  message:
                    "Cool Photo App needs access to your Storage" +
                    "so you can take awesome pictures.",
                  buttonNeutral: "Ask Me Later",
                  buttonNegative: "Cancel",
                  buttonPositive: "OK"
                }
              );
              if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                try {
                  myGetFiles().then((data) => {
                    console.log(data.length)
                    setData(data)
                  }).catch((err) => {
                    console.log(err,"error")
                  })
                }
                catch (err) {
                  console.log(err)
                }
              } else {
                console.log("Storage Permission is required permission denied");
              }
            } catch (err) {
              console.warn(err);
            }
          }
        
        }else {
          console.log("ios Setting here");  
        }
      };
    
      const myGetFiles = () => {
        return new Promise((resolve, reject) => {
          if (Platform.OS === "android") {
            CustomerMediaStore.GetFiles(
              tracks => {
                resolve(tracks);
              },
              error => {
                reject(error);
              }
            );
          } 
        });
      }
    
      const renderItem = ({ item }) => { 
       
        return (
          <Item title={item.displayname} dateadded={item.dateadded} datemodified={item.datemodified} size={item.size} />
        )
      }
    
      return (
        <SafeAreaView style={styles.container}>
          <FlatList
            data={[...data]}
            renderItem={renderItem}
            keyExtractor={item => `${item.id}${+ new Date(item.id*1)}`}
          />
      </SafeAreaView>
      );
    };
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        marginTop: StatusBar.currentHeight || 0,
      },
      item: {
        backgroundColor: '#f9c2ff',
        padding: 20,
        marginVertical: 8,
        marginHorizontal: 16,
      },
      title: {
        fontSize: 15,
      },
    });
    
    export default App;