Steve
Steve

Reputation: 552

How to use global variable in onCreate method of Android

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.

Upvotes: 1

Views: 876

Answers (2)

user8421421
user8421421

Reputation:

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 + "");

Upvotes: 1

Goku
Goku

Reputation: 9692

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

Upvotes: 6

Related Questions