I'm trying to get a file to be recognized, which is to test my other code. Here is my code for finding the file and making sure the file is found:

String filePath = "/sdcard/Download/"+ fileName;
        File file = new File(filePath);
        if(file.exists()) {
            // Now scan it
            final CountDownLatch latch = new CountDownLatch(1);
            MediaScannerConnection.scanFile(
                    myContext,
                    new String[]{filePath},
                    null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String path, Uri uri) {
                            if (uri == null) {
                                android.util.Log.d(TAG, "Scan failed or file was not added: " + path);
                            } else {
                                android.util.Log.d(TAG, "File scanned and found at: " + uri.toString());
                            }
                            latch.countDown();
                        }
                    }
            );
            android.util.Log.d(TAG, "Sanity Check- file exists at "+filePath);
            try {
                latch.await(); // This will make the current thread wait until latch count becomes 0
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            android.util.Log.d(TAG, "File does not exist: " + filePath);
        }

        if (myContext != null) {
            Cursor cursor = myContext.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
            android.util.Log.d(TAG, "Check cursor != null");
            if (cursor != null && cursor.moveToFirst()) {
                android.util.Log.d(TAG, "cursor is not null");

                do {
                    android.util.Log.d(TAG, "Inside cursor.moveToNext while loop");
                    int columnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME);
                    if (columnIndex != -1) {
                        String displayName = cursor.getString(columnIndex);
                        android.util.Log.d(TAG, displayName);
                    } else {
                        android.util.Log.d(TAG, "DISPLAY_NAME column not found");
                    }

                } while (cursor.moveToNext());
                cursor.close();
            }
            else
            {
                android.util.Log.d(TAG, "cursor is null");
            }

So, when it runs this code, it says the file exists at the top, so mediascanner runs, mediascanner finds the file (great), then it waits for mediascanner to finish so the results are apparent to the rest of the software, then when it gets to the bottom half of the code above, it doesn't find any files at all. What am I doing wrong here?

0

There are 0 best solutions below