有 Java 编程相关的问题?

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

Android全局变量java。lang.NullPointerException

我有两种方法使用相同的2个按钮+1个文本视图。比如:

public void startChange(View v) {
    final Button start = (Button) findViewById(R.id.start);
    final Button restart = (Button) findViewById(R.id.restart);
    final TextView check = (TextView) findViewById(R.id.check);
    //TO-DO part - Sets check to something based on buttons TagID
}

public void restartChange (View v) {
    final Button start = (Button) findViewById(R.id.start);
    final Button restart = (Button) findViewById(R.id.restart);
    final TextView check = (TextView) findViewById(R.id.check);
    //TO-DO part - Restars everything to basic position
}

一切都很顺利。。但当我制作这个按钮和textview全局变量时,我得到了java。lang.NullPointerException。 知道怎么修吗

编辑: 问题解决了。 你唯一需要做的就是在onCreate方法中定义按钮和文本视图,而不是在全局定义中

例如:

public class Example extends Activity {
    Button start;
    Button restart;
    TextView t;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        start = (Button) findViewById(R.id.start);
        restart = (Button) findViewById(R.id.restart);
       check = (TextView) findViewById(R.id.check);
    }
}

共 (2) 个答案

  1. # 1 楼答案

    您必须添加setContentView(R.layout.main);

    public class Example extends Activity
    {
        Button start;
        Button restart;
        TextView t;
    
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            start = (Button) findViewById(R.id.start);
            restart = (Button) findViewById(R.id.restart);
            check = (TextView) findViewById(R.id.check);
        }
    }
    
  2. # 2 楼答案

    问题解决了。 你唯一需要做的就是在onCreate方法中定义按钮和文本视图,而不是在全局定义中

    例如:

    public class Example extends Activity {
        Button start;
        Button restart;
        TextView t;
    
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            start = (Button) findViewById(R.id.start);
            restart = (Button) findViewById(R.id.restart);
           check = (TextView) findViewById(R.id.check);
        }
    }