如何在android中将多个图像上传到firebase?

时间:2018-01-24 07:47:28

标签: java android firebase image-uploading firebase-storage

我知道这个问题已经在这里被问到并回答了,但由于某些原因,如果解决方案对我不起作用。

所以这就是我试图这样做的方式。我的布局中有两个按钮,一个用于打开图库,另一个用于上传图像。

定义的成员

int SELECT_PICTURES = 1;

ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
Uri imageUri;
int up = 0;
int k =0;

图库按钮代码

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURES);

关于活动结果代码

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == SELECT_PICTURES) {
        if (resultCode == MainActivity.RESULT_OK) {
            if (data.getClipData() != null) {
                int count = data.getClipData().getItemCount();
                Log.i("count", String.valueOf(count));
                int currentItem = 0;
                while (currentItem < count) {
                    imageUri = data.getClipData().getItemAt(currentItem).getUri();


                    Log.i("uri", imageUri.toString());
                    mArrayUri.add(imageUri);
                    currentItem = currentItem + 1;
                }
                Log.i("listsize", String.valueOf(mArrayUri.size()));
            } else if (data.getData() != null) {
                String imagePath = data.getData().getPath();

            }
        }
    }
}

上传按钮代码

  StorageReference filepath = FirebaseStorage.getInstance().getReference().child("gpic");


    while (up < mArrayUri.size()){

        // error is pointing to this line, line 82
        filepath.child(mArrayUri.get(k).getLastPathSegment()).putFile(mArrayUri.get(k)).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Uri downloadURL = taskSnapshot.getDownloadUrl();
                Toast.makeText(TestingActivity.this, downloadURL.toString(), Toast.LENGTH_SHORT).show();
                up++;
                k++;
            }
        });
    }
}

以上代码上传了一张图片,然后崩溃并出现以下错误

01-24 12:37:37.416 8336-8336/com.codenemesis.uploading E/AndroidRuntime: FATAL EXCEPTION: main
                                                                   Process: com.codenemesis.uploading, PID: 8336
                                                                   java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                       at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                                       at android.view.View.performClick(View.java:5610)
                                                                       at android.view.View$PerformClick.run(View.java:22265)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                                    Caused by: java.lang.reflect.InvocationTargetException
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                       at android.view.View.performClick(View.java:5610) 
                                                                       at android.view.View$PerformClick.run(View.java:22265) 
                                                                       at android.os.Handler.handleCallback(Handler.java:751) 
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                       at android.os.Looper.loop(Looper.java:154) 
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6077) 
                                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
                                                                    Caused by: java.util.concurrent.RejectedExecutionException: Task com.google.firebase.storage.zzs@c59b7fe rejected from java.util.concurrent.ThreadPoolExecutor@4b6eb5f[Running, pool size = 2, active threads = 2, queued tasks = 128, completed tasks = 0]
                                                                       at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2049)
                                                                       at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:814)
                                                                       at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1360)
                                                                       at com.google.firebase.storage.zzu.zzt(Unknown Source)
                                                                       at com.google.firebase.storage.UploadTask.schedule(Unknown Source)
                                                                       at com.google.firebase.storage.StorageTask.zzcls(Unknown Source)
                                                                       at com.google.firebase.storage.StorageReference.putFile(Unknown Source)
                                                                       at **com.codenemesis.uploading.TestingActivity.up(TestingActivity.java:82)**
                                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                                       at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                                                                       at android.view.View.performClick(View.java:5610) 
                                                                       at android.view.View$PerformClick.run(View.java:22265) 
                                                                       at android.os.Handler.handleCallback(Handler.java:751) 
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                       at android.os.Looper.loop(Looper.java:154) 
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6077) 
                                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 

2 个答案:

答案 0 :(得分:0)

找到导致问题的原因。我正在增加变量&#34; up&#34;和&#34; k&#34;在onSuccessListener内。这可能会在上传URI之前改变它们的值,所以我将它们递增到onSuccessListener之外,它完全正常。

上传按钮代码

StorageReference filepath = FirebaseStorage.getInstance().getReference().child("gpic");

    while (up < mArrayUri.size()){

        filepath.child(mArrayUri.get(k).getLastPathSegment()).putFile(mArrayUri.get(k)).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Uri downloadURL = taskSnapshot.getDownloadUrl();
                Toast.makeText(TestingActivity.this, downloadURL.toString(), Toast.LENGTH_SHORT).show();

            }
        });
        up++;
        k++;

    }

}

答案 1 :(得分:0)

完全期货是解决这个问题的更好方法。

下面的上传方法返回一个完整的未来。

fun uploadImage(
        path: String, imageUrl: Uri): CompletableFuture<String> {
        val productImagesRef = storage.reference.child("$path/${imageUrl.lastPathSegment}")
        val uploadTask = productImagesRef.putFile(imageUrl)

        val promise = CompletableFuture<String>()

        uploadTask.addOnFailureListener {
            promise.completeExceptionally(it)
        }.addOnSuccessListener {
            productImagesRef.downloadUrl.addOnSuccessListener {
                promise.complete(it.toString())
            }.addOnFailureListener {
                promise.completeExceptionally(it)
            }
        }
        return promise
    }

调用者可以等待多个上传完成的期货,如下所示。此外,在 android 中,调用者为多次上传生成一个新线程而不阻塞 UI 主线程是理想的。

Thread {
    val imageUploadPromises = imageUris.map {
            uploadImage(product.group, product.type, product.name, it)
        }
    // wait for all uploads to finish. join() makes it wait.
    CompletableFuture.allOf(*imageUploadPromises.toTypedArray()).join()

    //To get individual downloadUrls
    val downloadUrls = imageUploadPromises.map { it.get() }
}.start()