How to pass the name of Image Dynamically?

Asked

Viewed 230 times

0

Hello, I’m learning now and I managed to make a Heads or Tails app with Success and decided to create another one based on it. This other app just click on the mainActivity button and it calls a second Activity that randomly displays an image of the 36 images that are in the drawable folder. I would like to share and right here I found the answer to do these tasks, but while trying to create a method to share, I came across the following difficulty: I do not know how to pass the name of the image dynamically so I can reuse the method for all 36 without having to rewrite 36 times, I imagine it is possible but I did not figure out how to treat the information correctly. Below the excerpt of the code I refer to:

I call the check methodFree here:

if( extra != null){

if (opcaoEscolhida.equals("s1")){
    imagem.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.s1));
    imagem.setOnClickListener(new View.OnClickListener() {
                                  @Override
                                  public void onClick(View v) {
                                      checarPermissao("s1");
                                  }
                              }
    );

The methods I found here and adapted:

private void checarPermissao(String img){
    // Verifica  o estado da permissão de WRITE_EXTERNAL_STORAGE
    int permissionCheck = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        // Se for diferente de PERMISSION_GRANTED, então vamos exibir a tela padrão
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, SOLICITAR_PERMISSAO);
    } else {
        // Senão vamos compartilhar a imagem
        sharedImage(img);
    }
}

private void sharedImage(String img){
    // Vamos carregar a imagem em um bitmap

    Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.s1);  //aqui eu queria que recebe cada "sN" das imagens... mas nao sei como fazer...
    Intent share = new Intent(Intent.ACTION_SEND);
    //setamos o tipo da imagem
    share.setType("image/jpeg");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    // comprimomos a imagem
    b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    // Gravamos a imagem
    String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Sorte de Hoje", null);
    // criamos uam Uri com o endereço que a imagem foi salva
    Uri imageUri =  Uri.parse(path);
    // Setmaos a Uri da imagem
    share.putExtra(Intent.EXTRA_STREAM, imageUri);
    // chama o compartilhamento
    startActivity(Intent.createChooser(share, "Compartilhe"));
}

The solution that worked to end was the below, unfortunately repeating the code, because I could not create a method passing the information and I did this trick, Argh...

public class SorteActivity extends AppCompatActivity {

private ImageView imagem;
//private ImageView botaoVoltar;
private static final int SOLICITAR_PERMISSAO = 1;

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

    AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    imagem = (ImageView) findViewById(R.id.sorteId);
    //botaoVoltar = (ImageView) findViewById(R.id.botaoVoltarId);

    Bundle extra = getIntent().getExtras();
    String opcaoEscolhida = extra.getString("opcao");

    if( extra != null){

        if (opcaoEscolhida.equals("s1")){
            imagem.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.s1));
            imagem.setOnClickListener(new View.OnClickListener() {
                                          @Override
                                          public void onClick(View v) {
                                              //checarPermissao();
                                              int permissionCheck = ContextCompat.checkSelfPermission(SorteActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
                                              if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                                                  ActivityCompat.requestPermissions(SorteActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, SOLICITAR_PERMISSAO);
                                              } else {
                                                  Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.s1);
                                                  Intent share = new Intent(Intent.ACTION_SEND);
                                                  //setamos o tipo da imagem
                                                  share.setType("image/jpeg");
                                                  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                                                  // comprimomos a imagem
                                                  b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
                                                  // Gravamos a imagem
                                                  String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Sorte de Hoje", null);
                                                  // criamos uam Uri com o endereço que a imagem foi salva
                                                  Uri imageUri = Uri.parse(path);
                                                  // Setmaos a Uri da imagem
                                                  share.putExtra(Intent.EXTRA_STREAM, imageUri);
                                                  // chama o compartilhamento
                                                  startActivity(Intent.createChooser(share, "Compartilhe"));
                                              }
                                          }
                                      }
            );
        }else if (opcaoEscolhida.equals("s2")) { ... e assim por diante até o s35... #cruzcredo...
  • what it means s1?

  • is the name of the image in the drawable folder. " S1.jpg"

  • right. What R.drawable.s1 returns? I see no reference to this R.

  • I managed to solve it this way, which I found horrific, but I didn’t have more time to figure out how to pass this information dynamically, I had to repeat the same code 35 times... But I’m a beginner, I know the concepts of inheritance, but I have zero skill with the syntax and logic of Java and many blocks in relation to it because it was from a time when programming was structured, but I’m here trying to learn right... rsrs Well the code that solved, If anyone needs it is the below, I did not repeat all so it is not too long. I wanted a method... I will follow the suggestion of the colleague below.

1 answer

0


You can make a list of all your images like this:

list.add(R.drawable.s1);
list.add(R.drawable.s2);
list.add(R.drawable.s3);
list.add(R.drawable.s4);

to pick up the R.drawable.sN just make a for this deals with the problem!

for(int i =1; i<36; i++){
     list.get(i);
}

Any doubt or error says :) I hope this helps!!

  • 1

    Perfect! It was trying to do that. Thank you!

Browser other questions tagged

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