简体   繁体   English

Android-全局变量java.lang.NullPointerException

[英]Android - global variable java.lang.NullPointerException

I have 2 methods which use same 2 buttons + 1 TextView. 我有2个方法使用相同的2个按钮+ 1个TextView。 Something like this: 像这样:

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
}

everything worked fine.. But as soon as I made this buttons and textview global variable I got java.lang.NullPointerException. 一切正常。但是,一旦我创建了这个按钮和textview全局变量,我就得到了java.lang.NullPointerException。 Any idea how to fix it? 知道如何解决吗?

Edit: Problem solved. 编辑:问题解决了。 Only think you have to do is to define buttons and textview in onCreate method not in global definition.. 只有想不到你要做的是定义按钮和TextView的在onCreate方法不是全局定义..

Example: 例:

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

You must add setContentView(R.layout.main); 您必须添加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);
    }
}

Problem solved. 问题解决了。 Only think you have to do is to define buttons and textview in onCreate method not in global definition.. 只有想不到你要做的是定义按钮和TextView的在onCreate方法不是全局定义..

Example: 例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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