无法将图像上传到App和Firebase

无法将图像上传到App和Firebase

本文介绍了无法将图像上传到App和Firebase Android Studio的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我,我成功地用图库和照相机选择了图像.但图像未显示在图像视图或Firebase存储中.

please help me, I success to pick an image with a gallery and camera. but image not showing in image view or firebase storage.

这是我的清单

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"/>

这是我显示或上传图片的代码

this is my code to show or upload images

    FirebaseAuth firebaseAuth;
    FirebaseUser user;
    ImageView ava,cover2;
    TextView nametv,biotv;
    FirebaseDatabase firebaseDatabase;
    DatabaseReference databaseReference;
    FloatingActionButton floatingActionButton;
    ProgressDialog progressDialog;

    private static final int CAMERA_REQUEST_CODE = 100;
    private static final int STORAGE_REQUEST_CODE = 200;
    private static final int IMAGE_PICK_CAMERA_CODE = 300;
    private static final int IMAGE_PICK_GALLERY_CODE = 400;

    String cameraPermissions[];
    String storagePermissions[];
    Uri image_uri;
    String profilorcover;

    StorageReference storageReference;
    String storagePath = "Users_Profile_Cover_Imgs/";

    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_prof, container, false);

       firebaseAuth = FirebaseAuth.getInstance();
       user = firebaseAuth.getCurrentUser();
       firebaseDatabase = FirebaseDatabase.getInstance();
       databaseReference = firebaseDatabase.getReference("Users");
        progressDialog = new ProgressDialog(getActivity());
       ava = view.findViewById(R.id.avaim);
       nametv = view.findViewById(R.id.namatv);
       biotv = view.findViewById(R.id.biotv);
       cover2 = view.findViewById(R.id.rela);
       floatingActionButton = view.findViewById(R.id.editbtn);
       storageReference = getInstance().getReference();

相机权限

cameraPermissions = new String [] {Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}; storagePermissions = new String [] {Manifest.permission.WRITE_EXTERNAL_STORAGE};

cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};

        Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for(DataSnapshot ds : dataSnapshot.getChildren()){
                    String name = ""+ ds.child("name").getValue();
                    String email = ""+ ds.child("email").getValue();
                    String bio = ""+ ds.child("bio").getValue();
                    String image = ""+ ds.child("image").getValue();
                    String cover = ""+ds.child("cover").getValue();

                    nametv.setText(name);
                    biotv.setText(bio);
                   try {
                       Picasso.get().load(image).into(ava);
                    }
                   catch (Exception e){
                       Picasso.get().load(R.drawable.ic_cam_name).into(ava);
                   }

                    try {
                        Picasso.get().load(cover).into(cover2);
                    }
                    catch (Exception e){

                    }
                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editprofil();
            }
        });

        return view;
    }

    private boolean checkstorage(){
        boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == (PackageManager.PERMISSION_GRANTED);
        return result;


    }

    private  void reqstorage(){
        requestPermissions(storagePermissions, STORAGE_REQUEST_CODE);

    }

    private boolean checkcam(){
        boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
                == (PackageManager.PERMISSION_GRANTED);

        boolean result1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == (PackageManager.PERMISSION_GRANTED);

        return result && result1;


    }

    private  void reqcam(){
       requestPermissions(cameraPermissions, CAMERA_REQUEST_CODE);

    }



    private void editprofil() {

        String pengaturan[] = {"Edit Foto Profil", "Edit Foto Sampul", "Edit Nama", "Edit Bio"};
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Edit Profil");
        builder.setItems(pengaturan, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                if (i == 0){

                    progressDialog.setMessage("Mengubah Profil");
                    profilorcover = "image";
                    showimage();
                }

                else if (i == 1){
                    progressDialog.setMessage("Mengubah Profil");
                    profilorcover = "cover";
                    showimage();
                }

                else if (i == 2){
                    progressDialog.setMessage("Mengubah Profil");
                    shownamebio("name");
                }

                else if (i == 3){
                    progressDialog.setMessage("Mengubah Profil");
                    shownamebio("bio");
                }

            }
        });

        builder.create().show();
    }

 private void showimage() {
        String pengaturan[] = {"Camera", "Gallery"};
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Edit Profil");
        builder.setItems(pengaturan, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                if (i == 0){

                    if (!checkcam()){
                        reqcam();
                    }
                    else{
                        memilih();
                    }

                }

                else if (i == 1){

                    if (!checkstorage()){
                        reqstorage();
                    }
                    else{
                        memilihgal();
                    }

                }



            }
        });

        builder.create().show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode){
            case CAMERA_REQUEST_CODE:{

                if (grantResults.length >0){
                    boolean cameraacc = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean writestor = grantResults[1] == PackageManager.PERMISSION_GRANTED;

                    if(cameraacc && writestor){
                        memilih();
                    }
                    else {
                        Toast.makeText(getActivity(), "Setujui Kamera dan File Manager", Toast.LENGTH_SHORT).show();
                    }
                }

            }
            break;
            case STORAGE_REQUEST_CODE:{

                if (grantResults.length >0){
                     boolean writestor = grantResults[0] == PackageManager.PERMISSION_GRANTED;

                    if(writestor){
                        memilihgal();
                    }
                    else {
                        Toast.makeText(getActivity(), "Setujui File Manager", Toast.LENGTH_SHORT).show();
                    }
                }

            }
            break;
        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if (requestCode == RESULT_OK){

            if(requestCode == IMAGE_PICK_GALLERY_CODE){
                image_uri = data.getData();

                uploadprofile(image_uri);
            }

            if (requestCode == IMAGE_PICK_CAMERA_CODE){
                uploadprofile(image_uri);
            }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void uploadprofile(Uri uri) {

        progressDialog.show();
        String file = storagePath+ ""+ profilorcover +"_"+ user.getUid();

        StorageReference storageReference2 = storageReference.child(file);
        storageReference2.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
                while (!uriTask.isSuccessful());
                Uri downloaduri = uriTask.getResult();

                if (uriTask.isSuccessful()){
                    HashMap<String, Object> results = new HashMap<>();

                    results.put(profilorcover, downloaduri.toString());

                    databaseReference.child(user.getUid()).updateChildren(results)
                            .addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {

                                    progressDialog.dismiss();
                                    Toast.makeText(getActivity(), "Mengubah Gambar...", Toast.LENGTH_SHORT).show();
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {

                            progressDialog.dismiss();
                            Toast.makeText(getActivity(), "Tidak dapat mengubah gambar...", Toast.LENGTH_SHORT).show();
                        }
                    });

                }
                else{
                    progressDialog.dismiss();
                    Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
                }
            }
        })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

    }

    private void memilih() {

        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
        values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");

        image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        Intent camerai = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        camerai.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
        startActivityForResult(camerai, IMAGE_PICK_CAMERA_CODE);

    }

    private void memilihgal() {

        Intent gall = new Intent(Intent.ACTION_PICK);
        gall.setType("image/*");
        startActivityForResult(gall, IMAGE_PICK_GALLERY_CODE);
    }
}

数据库

规则数据库

推荐答案

获取下载URL的方式看起来很糟糕.在您的Android代码中使用任何while (!uriTask.isSuccessful());都不可能获得预期的结果.

The way you're getting the download URL looks fishy. Having any sort of while (!uriTask.isSuccessful()); in your Android code is unlikely to ever give the desired result.

这是我将其标准化的方式:

This is how I'd normalize it:

String file = storagePath+ ""+ profilorcover +"_"+ user.getUid();

StorageReference storageReference2 = storageReference.child(file);
storageReference2.putFile(uri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
    @Override
    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
        if (!task.isSuccessful()) {
            throw task.getException();
        }

        // Continue with the task to get the download URL
        return ref.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();

            HashMap<String, Object> results = new HashMap<>();

            results.put(profilorcover, downloaduri.toString());

            databaseReference.child(user.getUid()).updateChildren(results)
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {

                            progressDialog.dismiss();
                            Toast.makeText(getActivity(), "Mengubah Gambar...", Toast.LENGTH_SHORT).show();
                        }
                }
            });
        } else {
            progressDialog.dismiss();
            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
});

这是您的代码与在上传图片后获取下载网址.

这篇关于无法将图像上传到App和Firebase Android Studio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 11:54