android studio从firebase存储异步下载文件

cvxl0en2  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(416)

我想从firebase存储中下载4张图片,并将它们加载到活动中的4个imagebutton中。
我可以在内部存储器中下载该文件,但无法设置活动中包含的imagebutton中的图片,因为我收到错误“arrayindexoutofboundsexception:length=4;指数=4“
我认为问题是在for循环中从firebase异步下载。可能在循环的第一个循环中,它请求第一个文件,但是当下载第一个文件时,for循环不会等待它并不断增加索引i。当文件被下载时,索引i是“outofbounds”。
你认为这就是问题所在吗?
我该怎么解决?提前告诉你。
错误是:
e/androidruntime:致命异常:主进程:com.example.grigliaconscelta,pid:27029 java.lang.arrayindexoutofboundsexception:length=4;指数=4

public class MainActivity extends AppCompatActivity {

    //NUMBER OF PICTURES I WANT TO DOWNLOAD
    int num_modelli = 4;
    //ARRAY WHERE I'LL STORE THE FILES DOWNLOADED
    File[] mypath = new File[num_modelli];
    int i = 0;
    FirebaseStorage storage = FirebaseStorage.getInstance();
    //FOLDER THAT CONTAINS IMAGE IN FIREBASE
    StorageReference folder = storage.getReference().child("test");
    //WILL CONTAIN THE INFO ABOUT "TEST" FOLDER IN FIREBASE STORAGE
    ListResult listResult;
    Bitmap bitmap;
    String nomeFile;

    //THE ACTIVITY COMPONENT THAT WILL CONTAINS THE PICTURES DOWNLOADED FROM FIREBASE
    ImageButton[] myImageButton = new ImageButton[num_modelli];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // BINDING OF THE IMAGEBUTTON COMPONENT WITH THE ELEMENT OF ARRAY
        myImageButton[0] = findViewById(R.id.imageButton0);
        myImageButton[1] = findViewById(R.id.imageButton1);
        myImageButton[2] = findViewById(R.id.imageButton2);
        myImageButton[3] = findViewById(R.id.imageButton3);

        FirebaseApp.initializeApp(this);

        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        // SET THE DIRECTORY USED TO STORE THE FILE IN INTERNAL STORAGE
        final File directory = cw.getDir("imageGrid", Context.MODE_PRIVATE);

        //GET INFORMATION FROM THE "TEST" FOLDER IN FIREBASE STORAGE
        folder.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
            @Override
            public void onSuccess(ListResult listResult) {
                System.out.println("NUMBER OF FILES : " + listResult.getItems().size());

                //LOOP FOR DOWNLOAD EVERY FILE IN THE "TEST" FOLDER AND SET IT IN THE CORRESPONDENT IMAGEBUTTON IN ACTIVITY
                for (i = 0; i < num_modelli; i++) {
                    //READ THE NAME OF FIRST FILE IN TEST FOLDER
                    nomeFile = listResult.getItems().get(i).getName();
                    //CREATE THE FILE IN THE INTERNAL STORAGE OF DEVICE
                    mypath[i] = new File(directory, nomeFile);
                    //POINT AT THE FILE TO DOWNLOAD
                    folder = storage.getReference().child("test/" + nomeFile);
                    //System.out.println("FOLDER PATH " + folder.getPath());

                    //DOWNLOAD THE FILE POINTED TO FOLDER IN THE FILE INSIDE THE DEVICE REFERENCED IN MYPATH[I]
                    folder.getFile(mypath[i]).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                            System.out.println("FILE CREATED " + directory.getPath());
                            //DECONDE THE FILE DOWNLOADED AND STORED IN DEVICE
                            bitmap = BitmapFactory.decodeFile(directory + "/" +mypath[i].getName());
                            //SET THE IMAGE IN THE COMPONENT OF ACTIVITY
                            myImageButton[i].setImageBitmap(bitmap);
                            //REFRESH THE COMPONENT
                            myImageButton[i].refreshDrawableState();

                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            System.out.println("FILE NOT CREATED " + e.toString());

                        }
                    });
                }

            }

        });

    }
}
41zrol4v

41zrol4v1#

我想从firebase存储中下载4张图片,并将它们加载到活动中的4个imagebutton中。
我想你会发现毕加索的图书馆很满。您需要从每个storagereference获取其下载url,然后就可以完成所有设置。
这里有一种方法(顺便说一句,我个人认为你需要单独拿着你的图像按钮,而不是在一个数组中,但我并不完全熟悉你想要完成什么):

folder.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
        @Override
        public void onSuccess(ListResult listResult) {
            //iterating through all listed results to get their storageReference
            for(StorageReference storageReference: listResult.getItems()){
                //asynchronously you'll get the urls from all of listed storageReferences
                storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        //now we have the url (uri.toString()) and we can use picasso to display it
                        //i would HIGHLY recommend you to check its caching capabilities to prevent downloading from the storage more than once. 
                        //(unless the pictures are bound to change constantly
                        Picasso.get().load(uri.toString()).placeholder([drawable to display untill image is loaded]).into(myImageButton[i], new Callback() {
                            @Override
                            public void onSuccess() {
                                //handle successes 
                            }
                            @Override
                            public void onError(Exception e) {
                                //laoding url to view failed
                                //your way of handling it....
                            }
                        });
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        //getting download url failed
                        //your way of handling it....
                    }
                });
                //dont forget to increment i for the next async task
                i++;
            }
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            //getting storageReferences failed
            //your way of handling it....
        }
    });

祝你好运!

相关问题