简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM