0

我正在尝试在 android 终端上使用 SAF 写入 SD 卡。在我的代码中,在 SD 卡上创建文件后,我检查了文件的状态,但当时一些用户发生了“NullPointerException”。尽管刚刚创建文件,但我在不知道为什么它为空的情况下苦苦挣扎。

  1. 这是这样,但现在遵循一个代码块
  2. “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);
    
                }
    
4

2 回答 2

0

你确定从许可。我认为这可能是许可

于 2018-01-21T05:44:57.420 回答
0

Null pointer usually occurs when you forget to initialize a variable

or when you initialize it via a method that is returning null

in your case

newFile = pickedDir.createFile("text", target_filename); //returning null

It's returning null.

于 2018-01-21T06:00:33.213 回答