You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Android中TextView赋值随机字符串触发空引用异常

问题说明

需要实现每次打开对应页面时,从预定义的字符串数组中随机选取一条内容显示到TextView控件上。
但每次跳转至该页面执行随机字符串赋值逻辑时,都会在txt1.Text = ans;代码行抛出异常:System.NullReferenceException: 'Object reference not set to an instance of an object.'
原实现代码:

namespace App4
{
    [Activity(Label = "Winner")]
    public class Winner : Activity
    {

        TextView txt1;
        Button btn1;

        String[] array_of_strings =
            {
                "Congratulations!",
                "Did you get lucky? either way grats!",
                "Roses are red, violets are blue. Congrats! I am oh-so happy for you!",
                "Funny how easy this game is aint i right",
                "Wow so you have attention span greater than a goldFish",
            };

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.layout2);

            randomCongratulations();
            txt1 = FindViewById<TextView>(Resource.Id.Txt1);
            btn1 = FindViewById<Button>(Resource.Id.btn1);

            btn1.Click += (o, e) =>
            {
                Intent NextPage = new Intent(this, typeof(MainActivity));
                StartActivity(NextPage);
            };
        }
        public void randomCongratulations()
        {
            String ans = array_of_strings[new Random().Next(array_of_strings.Length)];
            txt1.Text = ans;
        }
    }
}
报错原因
  • 核心问题是执行顺序错误:OnCreate方法中先调用了randomCongratulations()给txt1赋值,之后才通过FindViewById初始化txt1控件。执行文本赋值逻辑时txt1还处于未赋值的null状态,访问其Text属性必然触发空引用异常。
  • 附带潜在问题:每次生成随机数都新建Random实例,短时间内快速进入页面时,由于Random默认以系统时钟滴答数作为随机种子,会连续生成相同的随机索引,导致展示内容重复。
修复方法
  • 调整OnCreate中的执行顺序:先加载布局、初始化所有控件,再执行随机内容赋值逻辑。
  • 将Random实例提升为类级别的单例字段,避免短时间生成重复随机值。

修复后的完整代码:

namespace App4
{
    [Activity(Label = "Winner")]
    public class Winner : Activity
    {
        TextView txt1;
        Button btn1;
        // 全局初始化Random实例,避免短时间生成重复值
        private readonly Random _rnd = new Random();

        String[] array_of_strings =
            {
                "Congratulations!",
                "Did you get lucky? either way grats!",
                "Roses are red, violets are blue. Congrats! I am oh-so happy for you!",
                "Funny how easy this game is aint i right",
                "Wow so you have attention span greater than a goldFish",
            };

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.layout2);

            // 先初始化控件
            txt1 = FindViewById<TextView>(Resource.Id.Txt1);
            btn1 = FindViewById<Button>(Resource.Id.btn1);
            // 控件初始化完成后再赋值
            randomCongratulations();

            btn1.Click += (o, e) =>
            {
                Intent NextPage = new Intent(this, typeof(MainActivity));
                StartActivity(NextPage);
            };
        }
        public void randomCongratulations()
        {
            String ans = array_of_strings[_rnd.Next(array_of_strings.Length)];
            txt1.Text = ans;
        }
    }
}

内容的提问来源于stack exchange,提问作者nson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 09:36:25