2

So I'm making a code that uses int value in a string(hardcoded btw), it works but when I incremented the value of the int by button click, the int in the string does not change as the increment.

int indexOfQuestion= 1; 
numberOfQuestion.setText("Question " + indexOfQuestion + " from " + lengthOfQuestion + " :" );
switch(v.getId()):
case R.id.next:
indexOfQuestion = indexOfQuestion+1;

so when I clicked the button, indexOfQuestion in numberOfQuestion stays 1. How do i change it automatically as I intended without long verbose codes? thanks

4
  • 3
    post complete code so that we can see context. Commented Jan 9, 2019 at 7:59
  • may be you are assigning int indexOfQuestion = 1 each time. Commented Jan 9, 2019 at 7:59
  • Post the complete method Commented Jan 9, 2019 at 8:03
  • you have to declare int indexOfQuestion= 1; globally or set text in your click event Commented Jan 9, 2019 at 8:33

2 Answers 2

5

What actually you are doing is calling this statement each time whenever you click the button:

 int indexOfQuestion = 1; 

What you need to do is change the scope of int indexOfQuestion = 1; and take it to outside of the method body.

public class Test {
     private int indexOfQuestion = 1; 
}

Instead of putting it inside onClick function.

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

Comments

1

it won't change because you setText before you increment int value. if you want to apply changes, you should setText again after the incrementation.

int indexOfQuestion= 1;

numberOfQuestion.setText("Question " + indexOfQuestion + " from " + lengthOfQuestion + " :" );
switch(v.getId()):
case R.id.next: indexOfQuestion = indexOfQuestion+1;
numberOfQuestion.setText("Question " + indexOfQuestion + " from " + lengthOfQuestion + " :" );

1 Comment

Okay, I had in mind of doing this, but I thought it was too verbose than necessary. Thanks!

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.