I am trying to write to the SD card using SAF on the android terminal. In my code, after creating a file on the SD card, I check the status of the file, but "NullPointerException" occurred at that time by some users. Despite being just after creating the file, I am struggling without knowing why it is null.
- So is this, but now follows a code block
Error occurs at "if(newFile.canWrite()){".:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { getContentResolver().takePersistableUriPermission(data.getData(), Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } try { countDownLatch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } countDownLatch.countDown(); } }).start(); countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } target_filename= String.valueOf(System.currentTimeMillis()); treeUri = data.getData(); DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri); // Create a new file and write into it newFile = pickedDir.createFile("text", target_filename); for(int i=0;i<10;i++){ newFile=pickedDir.findFile(target_filename); int wait_sd=0; countDownLatch = new CountDownLatch(1); do{ if(newFile.canWrite()){ wait_sd=10; }else{ try { countDownLatch.await(500, TimeUnit.MILLISECONDS); wait_sd++; } catch (InterruptedException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } } }while(wait_sd<10); }