0

同じ2つのボタン+1つのTextViewを使用する2つのメソッドがあります。このようなもの:

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

2 に答える 2

0

追加する必要があります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);
    }
}
于 2012-11-04T23:59:19.550 に答える
0

問題が解決しました。あなたがしなければならないと思うのは、グローバル定義ではなく、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);
    }
}
于 2014-03-25T09:25:55.003 に答える