0

My goal is to add new product, for each product contain picture and pdf file to firebase storage, then save each link to firebase database.

I got a problem went upload a picture and pdf. I cant get download URL from each file and return null went I'm try post to database.

code:

private void bukafilemanager(View view) {
    switch (view.getId()){
        case R.id.pilih_gambar:
            Intent gambar = new Intent();
            gambar.setType("image/*");
            gambar.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(gambar, PICK_IMAGE_REQUEST);
            break;

        case R.id.pilih_pdf:
            Intent pdf = new Intent();
            pdf.setType("application/*");
            pdf.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(pdf, PICK_FILE_REQUEST);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData()!= null){
        URI_Image = data.getData();
        daftarupload.add(URI_Image);
        Glide.with(this).load(URI_Image).into(preview_gambar);
        preview_gambar.setImageURI(URI_Image);

    } else if (requestCode == PICK_FILE_REQUEST && resultCode == RESULT_OK && data != null && data.getData()!= null){
        URI_File = data.getData();
        daftarupload.add(URI_File);
    }
}

public String getMimeType(Context context, Uri uri) {
    String extension;

    //Check uri format to avoid null
    if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
        //If scheme is a content
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
    } else {
        //If scheme is a File
        //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
        extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
    }
    return extension;
}

protected void uploadfile(ArrayList<Uri> daftarupload){

    progressDialog.setMessage("Harap Tunggu...");
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.setIndeterminate(true);
    progressDialog.setProgress(count);
    progressDialog.setMax(daftarupload.size());
    progressDialog.show();

    String nama_produk = namaproduk.getText().toString();
    String ket_produk = ketproduk.getText().toString();
    if(!TextUtils.isEmpty(nama_produk) && !TextUtils.isEmpty(ket_produk)) {
        for (Uri uri : daftarupload) {
            switch (getMimeType(getBaseContext(), uri)) {
                case "jpg":
                    final StorageReference lokasijpg = storage.child(id_produk + ".jpg");
                    lokasijpg
                            .putFile(uri)
                            .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                                    if (task.isComplete()){
                                        lokasijpg
                                                .getDownloadUrl()
                                                .addOnSuccessListener(new OnSuccessListener<Uri>() {
                                                    @Override
                                                    public void onSuccess(Uri uri) {
                                                        URL_JPG = uri;
                                                        count += 1;
                                                        progressDialog.setProgress(count);
                                                    }
                                                });
                                    }
                                }
                            });
                    break;
                case "pdf":
                    final StorageReference lokasipdf = storage.child(id_produk + ".pdf");
                    lokasipdf
                            .putFile(uri)
                            .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                                    if(task.isComplete()){
                                            lokasipdf
                                                    .getDownloadUrl()
                                                    .addOnSuccessListener(new OnSuccessListener<Uri>() {
                                                    @Override
                                                    public void onSuccess(Uri uri) {
                                                        URL_PDF = uri;
                                                        count += 1;
                                                        progressDialog.setProgress(count);
                                                    }
                                                });
                                    }
                                }
                            });
                    break;

                default:
                    progressDialog.dismiss();
                    Toast.makeText(getBaseContext(), "Format Tidak Sesuai", Toast.LENGTH_LONG).show();
                    break;

            }
        }

        simpandata(id_produk, nama_produk, ket_produk , URL_JPG, URL_PDF);
        progressDialog.dismiss();

    } else {
        progressDialog.dismiss();
        Toast.makeText(tambahproduk.this,"Semua data harus diisi lengkap!", Toast.LENGTH_LONG).show();
    }
}

protected void simpandata(String id_produk, final String nama_produk, String ket_produk, Uri URL_JPG, Uri URL_PDF){

        produk produk = new produk(id_produk,nama_produk,ket_produk,URL_JPG.toString(),URL_PDF.toString());
        database.child(id_produk).setValue(produk).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                progressDialog.dismiss();
                Toast.makeText(tambahproduk.this, "Produk "+nama_produk.toString()+" Berhasil Ditambahkan", Toast.LENGTH_LONG).show();
                finish();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                progressDialog.dismiss();
                Toast.makeText(tambahproduk.this, e.toString(), Toast.LENGTH_LONG).show();
            }
        });
}

error:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.user.katalog.lulu.user, PID: 27391
              java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.toString()' on a null object reference
                  at com.user.katalog.lulu.user.tambahproduk.simpandata(tambahproduk.java:237)
                  at com.user.katalog.lulu.user.tambahproduk.uploadfile(tambahproduk.java:226)
                  at com.user.katalog.lulu.user.tambahproduk$3.onClick(tambahproduk.java:102)
                  at android.view.View.performClick(View.java:5198)
                  at android.view.View$PerformClick.run(View.java:21147)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
InsaneCat
  • 2,115
  • 5
  • 21
  • 40

1 Answers1

1

According to your comment, I understand that you are getting that error because of the following line of code:

produk produk = new produk(id_produk,nama_produk,ket_produk,URL_JPG.toString(),URL_PDF.toString());

It is because you cannot create the URL_PDF varaible as a global variable and expect to work fine. You cannot use something now that hasn't been loaded yet. With other words, you cannot simply use the URL_PDF object outside the onComplete() method because it will always be null due the asynchronous behaviour of this method. This means that by the time you are trying to use that result outside that method, the data hasn't finished loading yet from the database and that's why is not accessible. A quick solve for this problem would be to use the URL_PDF varaible only inside the onComplete() method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193