user2606414
user2606414

Reputation: 718

Getting EditText name to array variable android

I am developing an application which randomly chooses a string from the arrays.xml file. Every string has 3 variables (%1$s, %2$s, %3$s). The first is taken from EditText, the second from Spinner (gets from array) and the third from an EditText.

I tried to use String.format but it didn't work, the logcat gives NullPointerException.

<string-array name="blabla"> 
<item>Blabla %1$s blabla %2$s blablabla %3$s.</item>
<item>blablabla %1$s blablabla %3$s blabl %2$s.</item>
</string-array>

and the Java code:

public void invia(View v){
    Spinner eta = (Spinner) findViewById(R.id.etaspin);
    String etastring = eta.getSelectedItem().toString().trim();

    EditText nome = (EditText) findViewById(R.id.nomeins);
    String nomestring = nome.getText().toString();

    EditText citta = (EditText) findViewById(R.id.cittains);
    String cittastring = citta.getText().toString();
    Resources res = getResources();

    String tot = res.getString(R.array.blabla, etastring, nomestring, cittastring);

    tot = myString[rgenerator.nextInt(myString.length)];
     TextView stiusatxt = (TextView) findViewById(R.id.stiusa);
     stiusatxt.setText(tot);
}

As per now the only thing that works is the random string display but none of the variables work.

Upvotes: 0

Views: 123

Answers (1)

rahul.taicho
rahul.taicho

Reputation: 1379

Try doing it this way

int random = new Random().nextInt(2);
String tot = String.format(res.getStringArray(R.array.blabla)[random], etastring, nomestring, cittastring);

Your code is giving problems because you are trying to read a string from an array using getString() instead of getStringArray()

Upvotes: 1

Related Questions