简体   繁体   中英

Image is not uploading from my gallery through Bitmap

This is my RegistrationActivity.java where I want user to choose image while registering time. Everything works fine except image updation! When I register a new user and when I click in image, it opens my image gallery, I choose any image, and it back to register activity but it won't update. Also I'm unable to register because that image is not uploading successfully and I sat (if imagepath == null ), so that's why toast error is coming that fill all the details.

NOTE: 1. I tried multiple images, same issue, also I resize some images and tried. 2.There is no error in logcat. 3.Default image is showing perfectly when we first time try to register that time I sat android logo which is default. 4.I can't register without selecting any image because imagepath == null and I exactly want that user should not register if he/she not upload the image. 5.I sat imageview size :

   android:layout_width="150dp"
   android:layout_height="150dp"

in my activity_registration.xml file. Is there cause any problem?

package com.jimmytrivedi.loginapp;

    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.net.Uri;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.OnFailureListener;
    import com.google.android.gms.tasks.OnSuccessListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.AuthResult;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.FirebaseUser;
    import com.google.firebase.database.DatabaseReference;
    import com.google.firebase.database.FirebaseDatabase;
    import com.google.firebase.storage.FirebaseStorage;
    import com.google.firebase.storage.StorageReference;
    import com.google.firebase.storage.UploadTask;

    import java.io.IOException;

    public class RegistrationActivity extends AppCompatActivity {

        private EditText userName, userEmail, userPassword, userAge;
        private Button SignUp;
        private TextView userLogin;
        private FirebaseAuth firebaseAuth;
        private ImageView profile;
        private FirebaseStorage firebaseStorage;
        private static int PICK_IMAGE = 123;
        String name, email, password, age;
        Uri imagePath;
        private StorageReference storageReference;

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == PICK_IMAGE && requestCode == RESULT_OK && data.getData() != null) {
                imagePath = data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath);
                    profile.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_registration);
            setUpUIViews();
            firebaseAuth = FirebaseAuth.getInstance();
            firebaseStorage = FirebaseStorage.getInstance();

            storageReference = firebaseStorage.getReference();


            SignUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (validate()) {
                        //upload data to the database

                        String user_email = userEmail.getText().toString().trim();
                        String user_password = userPassword.getText().toString().trim();

                        firebaseAuth.createUserWithEmailAndPassword(user_email, user_password)
                                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                                    @Override
                                    public void onComplete(@NonNull Task<AuthResult> task) {
                                        if (task.isSuccessful()) {
                                            sendEmailVerification();
                                        } else {
                                            Toast.makeText(RegistrationActivity.this, "Registration failed!", Toast.LENGTH_SHORT)
                                                    .show();
                                        }
                                    }
                                });
                    }
                }
            });

            userLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
                }
            });
        }

        private void setUpUIViews() {
            userName = findViewById(R.id.userName);
            userEmail = findViewById(R.id.userEmail);
            userPassword = findViewById(R.id.userPassword);
            SignUp = findViewById(R.id.userRegister);
            userLogin = findViewById(R.id.userLogin);
            userAge = findViewById(R.id.userAge);
            profile = findViewById(R.id.profile);

            profile.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE);
                }
            });
        }

        private boolean validate() {
            Boolean result = false;


            name = userName.getText().toString();
            email = userEmail.getText().toString();
            password = userPassword.getText().toString();
            age = userAge.getText().toString();

            if (name.isEmpty() || password.isEmpty() || email.isEmpty() || age.isEmpty()
                    || imagePath == null) {
                Toast.makeText(this, "Please enter all the details", Toast.LENGTH_SHORT)
                        .show();
            } else {
                result = true;
            }
            return result;

        }

        private void sendEmailVerification() {
            FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
            if (firebaseUser != null) {
                firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            sendUserData();
                            Toast.makeText(RegistrationActivity.this, "Successfully registered, Verification email has been sent",
                                    Toast.LENGTH_SHORT).show();
                            firebaseAuth.signOut();
                            finish();
                            startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
                        } else {
                            Toast.makeText(RegistrationActivity.this, "Verification email hasn't been sent",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }


        private void sendUserData() {
            FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
            DatabaseReference myReference = firebaseDatabase.getReference(firebaseAuth.getUid());
            StorageReference imageReference = storageReference.
                    child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
            UploadTask uploadTask = imageReference.putFile(imagePath);
            uploadTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(RegistrationActivity.this, "Upload failed", Toast.LENGTH_SHORT)
                            .show();
                }
            }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(RegistrationActivity.this, "Upload successful", Toast.LENGTH_SHORT)
                            .show();
                }
            });
            UserProfile userProfile = new UserProfile(age, email, name);
            myReference.setValue(userProfile);
        }
    }

Replace your sendUserData with this

 private void sendUserData() {
        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference myReference = firebaseDatabase.getReference(firebaseAuth.getUid());
        StorageReference imageReference = storageReference.
                child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
        imageReference.putFile(imagePath).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(RegistrationActivity.this, "Upload failed", Toast.LENGTH_SHORT)
                        .show();
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(RegistrationActivity.this, "Upload successful", Toast.LENGTH_SHORT)
                        .show();
            }
        });
        UserProfile userProfile = new UserProfile(age, email, name);
        myReference.setValue(userProfile);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM