Firebase存储在Android中没有身份验证令牌的请求

huangapple go评论78阅读模式
英文:

Firebase Storage no auth token for request in Android

问题

以下是您要翻译的内容:

  1. 从Firebase Cloud Storage下载一个 .txt 文件
  2. 将其存储在我的应用专用存储目录中
  3. 从应用专用存储中获取文件,并逐行读取它。

Logcat:

java.lang.RuntimeException: 发送结果失败 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} }} 到活动 {com.example.android.getroasted/com.example.android.getroasted.MainActivity}: java.lang.NullPointerException: 尝试调用虚拟方法 'void androidx.lifecycle.MutableLiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' 一个空对象引用

Caused by: java.lang.NullPointerException: 尝试调用虚拟方法 'void androidx.lifecycle.MutableLiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' 一个空对象引用

Fragment:

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) {
            // 读取原始文件时发生错误。
        } finally {
            String contents = stringBuilder.toString();
        }
    }

ViewModel:

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, "无法下载烘焙文档 " + e);
            }
        });
        return roastLiveData;
    }
}

我不知道问题发生在何处或为什么,但我已经尝试了以下事项:

  • 检查了我的安全规则,它们允许读取和写入。
  • viewmodel.setValue() 更改为 viewmodel.postValue()
英文:

I don't know how to describe this problem so I will list out the tasks I need to do for app:

  1. Download a .txt file from Firebase Cloud Storage
  2. Store it in my app-specific storage directory
  3. Get the file from the app-specific storage and read it line-by-line.

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 &#39;void androidx.lifecycle.MutableLiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)&#39; on a null object reference

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

Fragment:

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

        roastContainer.setVisibility(View.VISIBLE);
        FileInputStream fis = getContext().openFileInput(&quot;roasts&quot;);
        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(&#39;\n&#39;);
                line = reader.readLine();
                Log.d(TAG, &quot;roast: &quot; + line);
            }
        } catch (IOException e) {
            // Error occurred when opening raw file for reading.
        } finally {
            String contents = stringBuilder.toString();
        }
    }

ViewModel:

public class HomeViewModel extends ViewModel {

    private static final String TAG = &quot;HomeViewModel&quot;;
    FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
    StorageReference storageReference = firebaseStorage.getReference();
    private StorageReference roastDocRef = storageReference.child(&quot;roasts.txt&quot;);
    private MutableLiveData&lt;byte[]&gt; roastLiveData;

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

I don't know why or where the problem is occurring but I have tried these things already:

  • Checked my security rules, they are allow read, write
  • updated viewmodel.setValue() TO viewmodel.postValue()

答案1

得分: 0

Here's the translated code:

while (line.hasNext) {
    stringBuilder.append(line).append('\n');
    line = reader.readLine();
    Log.d(TAG, "roast: " + line);
}

try this code

SECONDLY, TRY MY CODE

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.
}

Make sure you first download the file then read the data in the onSuccessListener of the Firebase storage reference. Before downloading the text file, reading may cause null pointer Exception.

First, just download the file then use my by putting the actual address In the bracket. Then the textData variable will have all the data in the string that you need.
英文:
while (line.hasNext) {
               stringBuilder.append(line).append(&#39;\n&#39;);
               line = reader.readLine();
               Log.d(TAG, &quot;roast: &quot; + line);
           }

try this code

SECONDLY, TRY MY CODE

File textfile = new File(address of file);
if (textFile.exists()) {
            // if file already exists
            // Reading data in text file 

            StringBuilder textdata = new StringBuilder(&quot;&quot;);
            try {
                Scanner myReader = new Scanner(textFile);
                while (myReader.hasNextLine()) {
                    String data = myReader.nextLine();
                    textdata.append(data);

                }
                myReader.close();
            } catch (FileNotFoundException e) {
                Log.d(&quot;vijaySee&quot;, &quot;textWork: error in reading FIle&quot;);
                e.printStackTrace();
            }

//now textdata String has all the data for the user.

Make sure you first download the file then read the data in the onsuccessListener of the firebase storage reference. Before downloading the text file reading may cause null pointer Exception.

First, just download the file then use my by putting the actual address In the bracket. Then the textData variable will have all the data in the string that you need.

答案2

得分: 0

以下是翻译好的部分:

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

错误消息建议getRandomRoast()返回null。确实如此,因为您从未为roastLiveData分配过值。它将始终为null。

英文:

This has nothing to do with auth tokens or security rules.

The error message is suggesting that getRandomRoast() returns null. Indeed, it does do that because you never assigned roastLiveData a value. It will always be null.

huangapple
  • 本文由 发表于 2020年8月1日 14:50:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63202576.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定