How to move to the function which imageView was selected and save to Firebase

Asked

Viewed 248 times

0

I have a User Registration Activity where he must fill in some fields( name, gender, age, etc) and two Imageview where the user can place photos of him by clicking on Imageview and selecting them in the gallery.

I have the method selectedFoto set as onClick in the two Imageview, after the user chooses the photo in onActivityResult, he takes the selected photo and calls the function setImage to place the photo in Imageview. I want the selected photo to appear in the Imageview that he clicked and that’s when the problem begins.

As a step to the function of setting the image to the Imageview that the user clicked, so that it is placed in the correct Imageview?

And how to save the images in Firebase Storage and Database, so you can access them in another Activity(url)?

Follows code:

public class Anunciante extends AppCompatActivity {

    StorageReference storageRef;
    DatabaseReference databaseUsuario;

    private ImageView imgPrincipal, img02;
    private EditText txtNome, txtValor, txtDescricao, txtFone;
    private Spinner spIdade, spSexo;
    private Uri imgUri, imgUri2;

public static final String FB_STORAGE_PATH = "imagem/";
public static final String FB_DATABASE_PATH = "Anuncios";
public static final int REQUEST_CODE_01 = 1910;
public static final int REQUEST_CODE_02 = 2015;

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


    storageRef = getStorage();
    databaseUsuario = FirebaseConfig.getFirebase();

    imgPrincipal = (ImageView) findViewById(R.id.imgPrincipalAnuncio);
    imgPrincipal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent.createChooser(intent, "Selecione sua foto!"), REQUEST_CODE_01);

        }
    });
    img02 = (ImageView) findViewById(R.id.img02);
    img02.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent.createChooser(intent, "Selecione sua foto!"), REQUEST_CODE_02);

        }
    });

    txtNome = (EditText) findViewById(R.id.txtNome);
    txtValor = (EditText) findViewById(R.id.txtValor);
    txtFone = (EditText) findViewById(R.id.txtFone);
    txtDescricao = (EditText) findViewById(R.id.txtDescricao);
    spIdade = (Spinner) findViewById(R.id.spIdade);
    spSexo = (Spinner) findViewById(R.id.spSexo);

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE_01 && resultCode == RESULT_OK && data != null && data.getData() != null) {
        imgUri = data.getData();
        try{
            Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
            imgPrincipal.setImageBitmap(bm);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    if (requestCode == REQUEST_CODE_02 && resultCode == RESULT_OK && data != null && data.getData() != null) {
        imgUri2 = data.getData();
        try{
            Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri2);
            img02.setImageBitmap(bm);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

public String getExtImagem(Uri uri){
    ContentResolver contentResolver = getContentResolver();
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}

@SuppressWarnings("VisibleForTests")
public void salvaDados(View v){

    if (imgUri != null){
        StorageReference reference = getStorage().child(FB_STORAGE_PATH + FirebaseConfig.getFirebaseUser().getUid() + "principal"+"." + getExtImagem(imgUri));
        reference.putFile(imgUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>()  {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Upload upload = new Upload(taskSnapshot.getDownloadUrl().toString().trim(),
                        taskSnapshot.getDownloadUrl().toString().trim(), txtNome.getText().toString(),
                        spIdade.getSelectedItem().toString()+" anos", spSexo.getSelectedItem().toString(),
                        "R$ " + txtValor.getText().toString()+",00",
                        txtFone.getText().toString(), txtDescricao.getText().toString());
                String uid = FirebaseConfig.getFirebaseUser().getUid();
                databaseUsuario.child(uid).setValue(upload);

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
            }
        });
    }
    goMainScreen();
}



public void goMainScreen() {
    Intent main = new Intent(this, MainActivity.class);
    startActivity(main);
    finish();
}

}

1 answer

1


You can replace Imageview with an Imagebutton, it provides click support.

And use your method public void selecionaFoto(View v) to be the onClick of Imagebutton, the View v parameter must provide which Imagebutton was clicked.

  • Exactly what I do not know how to do, I changed the 2 Imageview by Imagebutton, I put the method selectedFoto as onClick in the two.

  • now in selectionFoto vc does so: if(v.getId() == R.id.imageButton1){ }, try this implementation, I did it quickly and did not test.

  • 1

    Hallelujah, thank you very much, it worked perfectly! I just need to optimize the image loading as it got a little slow but this I can solve.

  • You were doing everything right, you just needed to know how to put the pieces together

  • Fixing, worked, but only appears the selected photo after clicking again on Imagebutton...

  • If I’m not mistaken I should call the setImage inside onActivityResult, so that the photo I selected fills the correct imageButton, but it doesn’t work, only works when I call the setImage inside the selectFoto

  • It does so: creates a variable to store the image Utton that was clicked and in the selectFoto you save the view, then in onActivityResult Voce calls the setImage by changing the view of the imageButton

  • I have no idea how to do what you said, but I’ll do a little research and try to do

  • 1

    I managed to accomplish what I wanted, (I don’t know if what I did was what you explained to me, only the part of saving the data that didn’t work yet, because this recording the last photo selected in the gallery twice in Firebase.

Show 4 more comments

Browser other questions tagged

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