Home > Back-end >  App is crashing on getting elements in Array
App is crashing on getting elements in Array

Time:04-10

int[] spin_Results = {100, 200, 50, 250, 1000, 300, 400, 500, 10, 700, 800, 20};
Collections.reverse(Arrays.asList(spin_Results));

Toast.makeText(this, spin_Results[0], Toast.LENGTH_SHORT).show();

My app is crashing at this line: Toast.makeText(). Why is this crash happening and how can I solve it?

CodePudding user response:

Your problem is calling the makeText() function with an integer instead of a String, specifically at spin_Results[0].

You need to convert this integer to a String and pass that to the function, since it only accepts Strings. There are two ways to achieve this easily:

  • Use Integer.toString(int) method

    Toast.makeText(this, Integer.toString(spin_Results[0]), Toast.LENGTH_SHORT).show();

  • Use String.valueOf(int) method

    Toast.makeText(this, String.valueOf(spin_Results[0]), Toast.LENGTH_SHORT).show();

  • Use String Concatenation

    Toast.makeText(this, "" spin_Results[0], Toast.LENGTH_SHORT).show();

You can use any of them, but be aware that String.valueOf(int) function will call Integer.toString(int) if you are concerned about that.

CodePudding user response:

The Toast.makeText() needs 3 params.

  1. Context (Context)
  2. Text to display (String)
  3. The display length (Integer)

enter image description here

Now, according to your code, you are not following the second param. This is wrong. You have to give it a String but you give it an int. Why don't you try to parse it to a string using the given methods and then display it ?

Method 1


Convert int to String using the Integer class.

Toast.makeText(this, Integer.toString(spin_Results[0]), Toast.LENGTH_SHORT).show();

Method 2


Convert int to String using the String class.

Toast.makeText(this, String.valueOf(spin_Results[0]), Toast.LENGTH_SHORT).show();

Method 3


Convert int to String using String concentation.

Toast.makeText(this, ""   spin_Results[0], Toast.LENGTH_SHORT).show();

But, I'd prefer you to use the second one. I use that usually so I feel that's better

  • Related