0

Я создал регистрацию юзера через страницы. Он заполняет на каждой странице что-то из личных данных и это передается через intent в некст активити. В активити с добавлением фото я создаю объект юзера и закидываю в бд. Но проблема в том, что закидывается все, кроме саомого фото

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

    Intent givenIntent = getIntent();   //Intent предыдущего класса
    User user = givenIntent.getParcelableExtra("user");

    assert user != null;
    user.setPermissions(Permissions.SIMPLE);

    Intent intent = new Intent(RegisterPhotoActivity.this, MainActivity.class);
    registrationNextButton = findViewById(R.id.registrationNextBtn);
    addPhotosImageButton = findViewById(R.id.registerPhotoImgBtn);

    databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
    auth = FirebaseAuth.getInstance();
    storage = FirebaseStorage.getInstance();
    userImagesStorageReference = storage.getReference().child("users_images");

    addPhotosImageButton.setOnClickListener(v -> {
        chooseImage();
    });

    registrationNextButton.setOnClickListener(v ->  {
        String mail = user.getMail();
        String password = user.getPassword();
        createAndAddUser(mail, password, user);
    });
}

private void createAndAddUser(String email, String password, User addUser) {
    auth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, task -> {
                if (task.isSuccessful()) {
                    Log.d("TAG", "createUserWithEmail:success");
                    FirebaseUser user = auth.getCurrentUser();
                    assert user != null;
                    addUser.setID(user.getUid().toString());
                    addUser.setMainPhoto(photoPath);
                    databaseReference.push().setValue(addUser);
                } else {
                    Toast.makeText(RegisterPhotoActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
                    Log.w("TAG", "createUserWithEmail:failure", task.getException());
                }
            });
}

private void chooseImage() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    startActivityForResult(Intent.createChooser(intent, "Выберите изображение"), RC_IMAGE_PICKER);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RC_IMAGE_PICKER && resultCode == RESULT_OK) {
        assert data != null;
        Uri selectedImageUri = data.getData();

        assert selectedImageUri != null;
        StorageReference imageRef = userImagesStorageReference.child(Objects.requireNonNull(selectedImageUri.getLastPathSegment()));

        UploadTask uploadTask = imageRef.putFile(selectedImageUri);

        Task<Uri> urlTask = uploadTask.continueWithTask(task -> {
            if (!task.isSuccessful())
                throw Objects.requireNonNull(task.getException());
            return imageRef.getDownloadUrl();
        }).addOnCompleteListener(task1 ->  {
            if (task1.isSuccessful()) {
                Uri downloadUri = task1.getResult();

                assert downloadUri != null;
                photoPath = downloadUri.toString();
            }
        });
    }
}

}

1
  • Обычно в базе данных хранят ссылки на фотки. 15 апр 2020 в 20:13

1 ответ 1

0

Вариант А - используйте storage, который также предоставляет firebase, а в самой базе данных храните ссылки на картинку. Вариант Б (из ряда костылей) - разбейте всю картинку на бинарный код и сохраняйте его в массив

4
  • Дело в том, что я храню ссылку на картинку addUser.setMainPhoto(photoPath); 16 апр 2020 в 21:51
  • А как на счёт того, что у вас фото возможно не успевает загрузиться в бд? Следовательно переменная не успеваем получить путь, ну и в массив не добавляется.
    – Mr.Krotos
    16 апр 2020 в 21:59
  • А вы не рассматривали возможность загружать фото, присваивая ему вместо названия id пользователя?
    – Mr.Krotos
    16 апр 2020 в 22:02
  • 1
    Спасибо за совет 17 апр 2020 в 10:06

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.