0

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.

4
  • the last line throw the NullPointerException, right? Commented Apr 9, 2015 at 17:53
  • No, the NPE was thrown when I was using the String.format from Android Developers website Commented Apr 9, 2015 at 17:54
  • Android Developers website ?? This line res.getString(R.array.blabla, etastring, nomestring, cittastring); is to getString, but u r using string-array Commented Apr 9, 2015 at 17:57
  • Exactly, that's my problem Commented Apr 9, 2015 at 18:01

1 Answer 1

1

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()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.