1

I am very much new to Android world. I was just trying to check how a global variable can be used in onCreate() method in Android, whenever i tried doing so, it closed abruptly. When I displayed some random text in the code, it was displayed successfully.

Here's my code:

public class MyActivity extends AppCompatActivity
{
    public static int num_i=0;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_beer);
        TextView tv = findViewById(R.id.textView);
        tv.setText(num_i);
        num_i++;
    }
}



Please help me in this.

2
  • 1
    Ok, let's assume I am a magician, and can see the stacktraceof your exception. It tells you that resource with identifier <some identifier> not found. That happens because TextView.setText() has more than one overload. So TextView.setText(int), which you are calling expects the String resource identifier as a parameter (R.string.something for example). If you want to show an int in the TextVIew, you first have to convert it to string. Commented Nov 13, 2017 at 9:11
  • 1
    Title in this question is completely misleading, can you please update the title of your question to reflect more on the setText with int parameter problem? Commented Nov 13, 2017 at 9:20

2 Answers 2

6

Sets the text to be displayed. it takes String as a parameter not a number

Sample : tv.setText("PREM");

Sets the text to be displayed using a string resource identifier.

Sample : tv.setText(R.string.app_name);

first you have to convert your int value in to a String

Try this use

tv.setText(String.valueOf(num_i));

or

tv.setText(num_i+"");

instead of this

 tv.setText(num_i);
Sign up to request clarification or add additional context in comments.

2 Comments

Also exists: void setText (int resid) which takes an int as parameter
i was just updating my thanks for your suggestion @pleft
1

Don't use tv.setText() with a number as parameter. Try using String.valueOf(num_i).

So in your case: tv.setText(String.valueOf(num_i)) or tv.setText(num_i + "");

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.