Cannot Upload Image to App And Firebase Android Studio

依然范特西╮ 提交于 2020-06-29 04:08:09

问题


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

this is my manifest

<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();

camera permissions

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);
    }
}

database

rule database


回答1:


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();
        }
    }
});

This is a pretty direct merge of your code with the flow from the Firebase documentation on getting a download URL after uploading an image.




回答2:


That problem in the code requestcode == result_ok. That must change like resultcode==result_ok. That's why my problem solved.

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

    if (requestCode == RESULT_OK){

requestCode replace wirh resultCode.

        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);
}


来源:https://stackoverflow.com/questions/62281212/cannot-upload-image-to-app-and-firebase-android-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!