uri.tostring () для пустой ссылки на объект - PullRequest
0 голосов
/ 17 апреля 2020
public class profile_activity extends AppCompatActivity implements View.OnClickListener {
    private static final int CHOOSE_IMAGE = 101;
    ImageView imageViewprofile;
    EditText editTextName;
    Uri uriProfile;
    ProgressBar progressbar;
    String profileImageUrl;
    Button buttonSave;
    FirebaseAuth mauth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_activity);
        editTextName = (EditText) findViewById(R.id.editTextName);
        imageViewprofile = (ImageView) findViewById(R.id.imageViewProfile);
        progressbar = (ProgressBar) findViewById(R.id.progressBar2);
        buttonSave =findViewById(R.id.buttonSave);
        mauth = FirebaseAuth.getInstance();
        loadUserInfo();
        imageViewprofile.setOnClickListener(this);
        buttonSave.setOnClickListener(this);



    }

    private void loadUserInfo() {
        if(mauth.getCurrentUser() != null){
            FirebaseUser user = mauth.getCurrentUser();
            if(user != null) {
                if (user.getPhotoUrl() != null) {
                    Glide.with(this).load(user.getPhotoUrl().toString()).into(imageViewprofile);
                }
                if (user.getDisplayName() != null) {
                    editTextName.setText(user.getDisplayName());
                }
                Toast.makeText(getApplicationContext(),"load user info chal rha hai",Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(mauth.getCurrentUser() == null){
            finish();
            startActivity(new Intent(this,MainActivity.class));
        }
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.imageViewProfile:
                showImageChooser();
                break;
            case R.id.buttonSave:
                saveinfo();
                break;
        }

    }

    private void saveinfo(){
        uploadImageToFirebaseStorage();
        String name = editTextName.getText().toString();
        if(name.isEmpty()) {
            editTextName.setError("Name cannot be empty!");
            editTextName.requestFocus();
            return;
        }

        if(profileImageUrl== null){
            Toast.makeText(getApplicationContext(),"User profile nalla h 1",Toast.LENGTH_SHORT).show();
        }
        FirebaseUser user = mauth.getCurrentUser();
        if(user != null && profileImageUrl != null){
            UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder().
                    setDisplayName(name).
                    setPhotoUri(Uri.parse(profileImageUrl)).
                    build();
            user.updateProfile(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if(task.isSuccessful()){
                        Toast.makeText(profile_activity.this,"Profile updated",Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }
        if (user==null){
            Toast.makeText(getApplicationContext(),"User nalla h",Toast.LENGTH_SHORT).show();
        }


    }

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

        if(requestCode==CHOOSE_IMAGE && resultCode==RESULT_OK && data != null && data.getData() != null){
            uriProfile = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),uriProfile);
                imageViewprofile.setImageBitmap(bitmap);


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void uploadImageToFirebaseStorage(){
        final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepic"+System.currentTimeMillis()+".jpg");

        if(uriProfile != null){
            progressbar.setVisibility(View.VISIBLE);
            profileImageRef.putFile(uriProfile)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    progressbar.setVisibility(View.GONE);
                    //profileImageUrl = profileImageRef.getDownloadUrl().toString();
                    profileImageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            profileImageUrl = uri.toString();
                            if(profileImageUrl== null){
                                Toast.makeText(getApplicationContext(),"User profile nalla h",Toast.LENGTH_SHORT).show();
                            }
                            Toast.makeText(profile_activity.this,"Image upload successfull",Toast.LENGTH_SHORT).show();
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(profile_activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
                        }
                    });


                }
            })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            progressbar.setVisibility(View.GONE);
                            Toast.makeText(profile_activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
                        }
                    });

        }
    }

    private void showImageChooser(){
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select Profile Image"),CHOOSE_IMAGE);
    }
}

Моя цель - загрузить информацию в профиль, если она уже сохранена. Но это не сохранение из-за следующего:

profileImageUrl имеет значение null, но только в методе saveinfo, он получает значение в uploadImageToFirebaseStorage, и все же это значение равно null в методе saveinfo, я сделал его вдвое уверенным, что profilimageurl является глобальной переменной. Я не понимаю этого. Я довольно плохо знаком с пожарной базой. Пожалуйста, помогите мне. Вот весь код.

1 Ответ

0 голосов
/ 17 апреля 2020

Как указал zgc7009, проблема возникает из-за асинхронного вызова, когда вы вызываете

 uploadImageToFirebaseStorage(); 

, вы предполагаете, что метод вернется после загрузки изображения и установки URL-адреса на profileImageUrl, но нет, он возвращается сразу после установки ваших слушателей, затем управление достигает if(profileImageUrl== null), что верно, потому что изображение еще не загружено, и ваш обратный вызов слушателя не выполняется для установки profileImageUrl

, тогда управление достигает if(user != null && profileImageUrl != null) что является ложным по той же причине, так что теперь вы получаете это, правильно?

FIX

если я не ошибаюсь, вы хотите показать новое изображение пользователя, когда он меняется профиль, но это может произойти только при загрузке изображения, что означает выполнение onSuccessLisener() на putFile(), что означает, что код зависит от обратного вызова, поэтому переместите его в обратный вызов.

Переместите код из saveInfo() to uploadImageToFirebaseStorage(); вот так

private void uploadImageToFirebaseStorage () {final StorageReference profileImageRef = FirebaseStorage.getInstance (). getReferen ce ("profilepi c" + System.currentTimeMillis () + ". jpg");

    if(uriProfile != null){
        progressbar.setVisibility(View.VISIBLE);
        profileImageRef.putFile(uriProfile)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                progressbar.setVisibility(View.GONE);
                //profileImageUrl = profileImageRef.getDownloadUrl().toString();
                profileImageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        profileImageUrl = uri.toString();

    FirebaseUser user = mauth.getCurrentUser();
    if(user != null){
        UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder().
                setDisplayName(name).
                setPhotoUri(Uri.parse(profileImageUrl)).
                build();
        user.updateProfile(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if(task.isSuccessful()){
                    Toast.makeText(profile_activity.this,"Profile updated",Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    if (user==null){
        Toast.makeText(getApplicationContext(),"User nalla h",Toast.LENGTH_SHORT).show();
    }
                        Toast.makeText(profile_activity.this,"Image upload successfull",Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(profile_activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });


            }
        })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressbar.setVisibility(View.GONE);
                        Toast.makeText(profile_activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });

    }
}











**note** i removed some `if` conditions because those were guranteed to be true,you will also need to make some variable final because now those are getting used within the inner class 

В качестве альтернативы

uploadImageToFirebaseStorage(); сделать этот метод возвращаемым UploadTak, если вы хотите переместить код из saveInfo что-то вроде ниже

private Task<UploadTask> uploadImageToFirebaseStorage(){
    final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepic"+System.currentTimeMillis()+".jpg");

    if(uriProfile != null){
        progressbar.setVisibility(View.VISIBLE);
        return profileImageRef.putFile(uriProfile)
    }
}

Теперь установите слушателя в saveInfo()

. Я также рекомендую вам взломать код в методы, потому что код теперь выглядит грязно, хорошего дня Himanjli

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...