有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

文本上的java NullPointerException。settext(…)

private TextView text;

if(available == true){
        View view = (View)findViewById(R.id.emptyprogram);
        view.setVisibility(View.GONE);
        filldata();
    } else {
        text = (TextView)findViewById(R.id.emptyprogram);
        text.setText("Tiada Rancangan Yang Sedang Atau Akan Disiarkan!!!");
    }
}

当我执行时,它在text.settext("...");行上给了我NullPointerException错误

有什么问题?我在另一边跑,没问题


共 (3) 个答案

  1. # 1 楼答案

    如果您担心textView为空,请尝试此选项以避免异常:

    text = (TextView)findViewById(R.id.emptyprogram);
    if(text != null)
        text.setText("Tiada Rancangan Yang Sedang Atau Akan Disiarkan!!!");
    
  2. # 2 楼答案

    在调用findViewById()之前,您是否调用过setContentView()?您必须创建UI,然后才能使用它

  3. # 3 楼答案

    此方法调用必须返回null

    findViewById(R.id.emptyprogram);
    

    当您尝试在下一行中调用setText方法时,会得到一个NullPointerException