Imageview turns white when loading Activity and black when receiving image from gallery

Asked

Viewed 204 times

0

I am saving users with a default image at the time they register in the application and this image is a drawable that is saved as a String in the database:

Method of the Controller class:

public static boolean cadastraUsuario(Context context, String nome, String email, String senha) throws JSONException, IOException {
        Resources resources = context.getResources();
        Bitmap bitmap = BitmapFactory.decodeResource(resources, R.drawable.avatar);

        SocialMarketDB db = new SocialMarketDB(context);

        Usuario usuario = new Usuario(nome, email, senha, bitmap);
        return db.cadastraUsuario(usuario);
    }

Method that saves data in Sqlite:

public boolean cadastraUsuario(Usuario usuario) {
        boolean resp = false;
        String id = usuario.getId();
        SQLiteDatabase db = getWritableDatabase();

        try {
            ContentValues values = new ContentValues();
            values.put("id", usuario.getId());
            values.put("nome", usuario.getNome());
            values.put("url_foto", Util.converteBitmapString(usuario.getFoto()));
            values.put("senha", usuario.getSenha());

            Cursor cursor = db.query("usuario", null, "id=?", new String[]{id}, null, null, null);
            if (cursor.getCount() == 0) {
                db.insert("usuario", "", values);
                resp = true;
            }
        } finally {
            db.close();
        }
        return resp;
    }

Util.converteBitmapString:

public static String converteBitmapString(Bitmap imagemBitmap) {
        final int COMPRESSION_QUALITY = 100;
        String stringImagem;
        ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
        imagemBitmap.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY,
                byteArrayBitmapStream);
        byte[] b = byteArrayBitmapStream.toByteArray();
        stringImagem = Base64.encodeToString(b, Base64.DEFAULT);
        return stringImagem;
    }

Activity:

btncadastro.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {  
            if(Controller.cadastraUsuario(ActivityCriarConta.this,nome,email,senha1)) {
                                Util.alert(getResources().getString(R.string.alert_cadastro_sucesso), ActivityCriarConta.this);
                }
            }
}

When I enter Activity to edit profile, the Imageview that should have the drawable I saved is empty:

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

            Bundle args = getIntent().getExtras();
            if( args !=null) {
                emailUsuario = args.getString("id");
            }

            Usuario usuario = Controller.buscaUsuario(this,id);
            imgperfil = (ImageView) findViewById(R.id.imagemPerfil);
            imgperfil.setImageBitmap(usuario.getFoto());
    }

And when I choose a new image from the gallery, Imageview turns black:

 alterarimg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    carregarGaleria();
                }
            });
    public void carregarGaleria() {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, 1);
        }

        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
           //Verifica se tem permissão, se tiver chama o método escolheImagem()
        }

        //onRequestPermissionsResult...

        public void escolheImagem(int requestCode, int resultCode, Intent data) {
            InputStream stream = null;
            if (requestCode == 1 && resultCode == RESULT_OK) {
                try {
                    if (bitmap != null) {
                        bitmap.recycle();
                    }
                    Uri imageUri = data.getData();
                    imgperfil.setImageURI(imageUri);
                } finally {
                    if (stream != null)
                        try {
                            stream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                }

            }
        }

    public String getImagePath(Uri contentUri) {
        String[] campos = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(contentUri, campos, null, null, null);
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
        cursor.close();
        return path;
    }

I apologize for posting such an extensive code, but it’s just that my mistake could be in any of these parts and I’m having trouble identifying which one. The image-picking part of the gallery was working normally, I don’t remember touching anything that might be making this mistake happen.

  • I could not understand what the problem is, the image is getting black and white when you put in an Imageview, that’s it?

  • When I press Activty it turns white and when I choose a gallery image it turns black. I will change the question title

  • First, the drawable is an int. It is a numerical value. Secondly, it is much easier to manage images with a library called Glide: https://github.com/bumptech/glide. Just use the image like this: Glide.with(context). load(R.drawable.img1). into(imgView);

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.