简体   繁体   中英

Firebase Storage no auth token for request in Android

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 '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

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) {
            // Error occurred when opening raw file for reading.
        } 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, "could not download the roast doc " + 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()
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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM