我的目标是添加新产品,每个产品包含图片和pdf文件到Firebase存储中,然后将每个链接保存到Firebase数据库中。
我遇到了问题,上传了图片和pdf。我无法从每个文件获取下载URL,然后返回null
,我尝试发布到数据库。
代码:
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();
}
});
}
错误:
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)
答案 0 :(得分:1)
根据您的评论,我了解您由于以下代码行而收到该错误:
produk produk = new produk(id_produk,nama_produk,ket_produk,URL_JPG.toString(),URL_PDF.toString());
这是因为您无法将URL_PDF
变量创建为全局变量,并且无法正常工作。您现在不能使用尚未加载的内容。换句话说,您不能简单地在URL_PDF
方法之外使用onComplete()
对象,因为由于该方法的异步行为,它将始终为null
。这意味着,当您尝试在该方法之外使用该结果时,数据尚未从数据库中完成加载,因此无法访问。快速解决此问题的方法是仅在URL_PDF
方法内部使用onComplete()
变量,否则,我建议您从此 post 看到我的答案的最后一部分。在其中,我已经解释了如何使用自定义回调来完成。您也可以查看此 video 以获得更好的理解。