【问题标题】:Firebase Storage no auth token for request in AndroidFirebase 存储在 Android 中没有用于请求的身份验证令牌
【发布时间】:2020-08-01 06:50:11
【问题描述】:

我不知道如何描述这个问题,所以我将列出我需要为应用执行的任务:

  1. 从 Firebase 云存储下载 .txt 文件
  2. 将其存储在我的应用特定存储目录中
  3. 从应用特定的存储中获取文件并逐行读取。

Logcat:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=Intent { dat=content://com.google.android.apps.photos.contentprovider/0/1/content://media/external/images/media/2328/ORIGINAL/NONE/image/png/1631689393 flg=0x1 clip={text/uri-list U:content://com.google.android.apps.photos.contentprovider/0/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F2328/ORIGINAL/NONE/image%2Fpng/1631689393} }} to activity {com.example.android.getroasted/com.example.android.getroasted.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.lifecycle.MutableLiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' on a null object reference

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.lifecycle.MutableLiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' on a null object reference

片段:

private void setRoast() throws FileNotFoundException {
        homeViewModel.getRandomRoast().observe(getViewLifecycleOwner(), new Observer<byte[]>() {
            @RequiresApi(api = Build.VERSION_CODES.Q)
            @Override
            public void onChanged(byte[] bytes) {
                try (FileOutputStream fos = requireContext().openFileOutput("roasts", Context.MODE_PRIVATE)) {
                    fos.write(bytes);
                } catch (IOException e) {
                    Log.d(TAG, "IOException: " + e);
                }
            }
        });

        roastContainer.setVisibility(View.VISIBLE);
        FileInputStream fis = getContext().openFileInput("roasts");
        InputStreamReader inputStreamReader =
                new InputStreamReader(fis, StandardCharsets.UTF_8);
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
            String line = reader.readLine();
            while (line != null) {
                stringBuilder.append(line).append('\n');
                line = reader.readLine();
                Log.d(TAG, "roast: " + line);
            }
        } catch (IOException e) {
            // Error occurred when opening raw file for reading.
        } finally {
            String contents = stringBuilder.toString();
        }
    }

视图模型:

public class HomeViewModel extends ViewModel {

    private static final String TAG = "HomeViewModel";
    FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
    StorageReference storageReference = firebaseStorage.getReference();
    private StorageReference roastDocRef = storageReference.child("roasts.txt");
    private MutableLiveData<byte[]> roastLiveData;

    public MutableLiveData<byte[]> getRandomRoast() {
        roastDocRef.getBytes(1024*1024)
                .addOnSuccessListener(new OnSuccessListener<byte[]>() {
                    @Override
                    public void onSuccess(byte[] bytes) {
                        Log.d(TAG, "bytes: " + bytes);
                        roastLiveData.postValue(bytes);
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, "could not download the roast doc " + e);
            }
        });
        return roastLiveData;
    }
}

我不知道问题发生的原因或位置,但我已经尝试过这些方法:

  • 检查了我的安全规则,它们允许读、写
  • 更新了 viewmodel.setValue() TO viewmodel.postValue()

【问题讨论】:

    标签: java android firebase firebase-storage


    【解决方案1】:

    这与身份验证令牌或安全规则无关。

    错误信息提示getRandomRoast() 返回null。事实上,它确实这样做了,因为您从未为 roastLiveData 赋值。它将始终为空。

    【讨论】:

      【解决方案2】:
      while (line.hasNext) {
                     stringBuilder.append(line).append('\n');
                     line = reader.readLine();
                     Log.d(TAG, "roast: " + line);
                 }
      

      试试这个代码

      其次,试试我的代码

      File textfile = new File(address of file);
      if (textFile.exists()) {
                  // if file already exists
                  // Reading data in text file 
      
                  StringBuilder textdata = new StringBuilder("");
                  try {
                      Scanner myReader = new Scanner(textFile);
                      while (myReader.hasNextLine()) {
                          String data = myReader.nextLine();
                          textdata.append(data);
      
                      }
                      myReader.close();
                  } catch (FileNotFoundException e) {
                      Log.d("vijaySee", "textWork: error in reading FIle");
                      e.printStackTrace();
                  }
      
      //now textdata String has all the data for the user.
      

      确保首先下载文件,然后读取 firebase 存储引用的 onsuccessListener 中的数据。下载前读取文本文件可能会导致空指针异常。

      首先,只需下载文件,然后通过将实际地址放在括号中来使用我的文件。然后 textData 变量将包含您需要的字符串中的所有数据。

      【讨论】:

        猜你喜欢
        • 2020-06-26
        • 2020-08-18
        • 2013-10-12
        • 2021-10-25
        • 2021-03-06
        • 2018-02-17
        • 1970-01-01
        • 1970-01-01
        • 2020-12-16
        相关资源
        最近更新 更多