0

I have a textfield on my view, and when the text changes on the textfield i have a if statement, so when a certain keyword is in the textview, some code will run. Here is my code for the if statement:

 if (text1.equals("rotate")) {


                red.setRotation(red.getRotation() + 5);

                blue.setRotation(blue.getRotation() + 5);


            }

but when text1 equals 'rotate' and its running this code, the app will crash.

Here is the log cat:

enter image description here

enter image description here

Dr.jacky
  • 3,341
  • 6
  • 53
  • 91
fafafa
  • 57
  • 4

4 Answers4

5

The reason for that is text1 is null and you are trying to call a method on null reference.

Either you forgot to initialize it or no value assigned yet.

If you already have the initialization and if there are chances to get a null value, you need to have a guard condition for that.

 if (text1 !=null && text1.equals("rotate")) {

This first checks for null and then invoke the method.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

It appears like text1 is not initialized. In you method, initialize text1. Here's an example of how to:

text1   = (EditText)findViewById(R.id.text1);

If it is initialized and can have null, then guard it.

 if ("rotate".equals(text1)) {
Aragorn
  • 5,021
  • 5
  • 26
  • 37
0

First: Initialise text1

If it is a TextView then

text1 = (TextView) findViewById(R.id.textview_id);

If it is a EditText then

text1 = (EditText) findViewById(R.id.editText_id);

Second: Compare it like this:

if (text1.getText().toString().equalsIgnoreCase("rotate")) {
   red.setRotation(red.getRotation() + 5);
   blue.setRotation(blue.getRotation() + 5);
 }
Pankaj
  • 7,908
  • 6
  • 42
  • 65
0

First of all you need to initialise the text1 object. From the log it is clear that the text1 object is null.

You can then compare the string using:

if (text1 && "rotate".equals(text1.getText().toString()))
{
}
Midhun MP
  • 103,496
  • 31
  • 153
  • 200