How do I check if a String is null and add to an array?

0

I have a problem, I have several variables (String) with the following names: texttransfer1, texttransfer2 to 73 (texttransfer73).

At times the variable textTransfer2 for example may assume an empty value or not, depending on the situation.

I would like to mount an array, but I need to check if the TextTransfer1 string to TextTransfer73 is empty, otherwise add to the array.

Here is my code:

// RECOVERY INFORMATION

    Bundle extra = getIntent().getExtras();

    String textoTransferido1 = extra.getString("texto1");
    String textoTransferido2 = extra.getString("texto2");
    String textoTransferido3 = extra.getString("texto3");
    String textoTransferido4 = extra.getString("texto4");
    String textoTransferido5 = extra.getString("texto5");
    String textoTransferido6 = extra.getString("texto6");
    String textoTransferido7 = extra.getString("texto7");
    String textoTransferido8 = extra.getString("texto8");

// CREATING ARRAY

        final String[] frases =
                {
                        textoTransferido1,
                        textoTransferido2,
                        textoTransferido3,
                        textoTransferido4,
                        textoTransferido5,
                        textoTransferido6,
                        textoTransferido7,
                        textoTransferido8
                }

In the array I do not know if it was the right thing to create a vector that would check each item and if it is not null then it would add the item to the array.

As the array does not allow the item to be null or empty, I have to check the situation and only add those that have values.

Thank you.

    
asked by anonymous 01.06.2017 / 02:34

2 answers

2

You can use a for + list.

Bundle extra = getIntent().getExtras();

List<String> textos = new ArrayList<>();
int numeroDeTextos = 8;

for (int i = 0; i < numeroDeTextos; i++) {
  String texto = extra.getString("texto" + i);

  // Verifica se é nulo ou vázio.
  if (texto == null || texto.trim().length() == 0) {
    continue;
  }

  textos.add(texto);
}

String[] arrayDeTextos = textos.toArray(new String[0]);
    
01.06.2017 / 02:47
2

If your Extras only have such texts, it would do so, so the code is not dependent on the name of each extra or the amount of them:

Bundle extras = getIntent().getExtras();
if (extras != null) {
   List<String> textos = new ArrayList<>();
   for (String key : extras.keySet()) {
       String value = extras.getString(key);
       if(value != null && value.trim().length() > 0)
          textos.add(value);
   }
}
    
01.06.2017 / 03:22