0

ボタンとテキストビューを試して学ぶために、この小さなプログラムを作成しました。onLongClick を setText に使用しようとすると、強制的に閉じられます。デバッガーを見ると、45 行目に nullpointerexception があります holdMeAnswer.setText("Nope!");。

nullpointer の下に「クラス ファイル エラー: ソースが見つかりません」というエラーが大量に表示されます。添付されたソースを Java src.zip ファイルと android.jar ファイルの両方に向けようとしましたが、どちらも何も修正していないようです。

コードは次のとおりです。

package com.PickSomeButtons;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Button;
import android.view.View.OnLongClickListener;

public class PickSomeButtons extends Activity {

    RadioButton myButton0;
    RadioButton myButton1;
    TextView myAnswer;
    TextView holdMeAnswer;
    Button longClickButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myButton0=(RadioButton)findViewById(R.id.radio0);
        myButton1=(RadioButton)findViewById(R.id.radio1);
        myAnswer=(TextView)findViewById(R.id.textView1);
        longClickButton=(Button)findViewById(R.id.button1);

        myButton0.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                myAnswer.setText("Me!");                
            }
        });
        myButton1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                myAnswer.setText("Not me!");
            }
        });

        longClickButton.setOnLongClickListener(new Button.OnLongClickListener() {

            public boolean onLongClick(View v) {
                holdMeAnswer.setText("Nope!");
                return true;
            }
        });
    }
}
4

1 に答える 1

1

onCreate メソッドでは、myAnswer を初期化しますが、holdMeAnswer は初期化しません。したがって、holdMeAnswer は null です。

Eclipse の [Preferences] > [Java] > [Compiler] > [Errors/Warnings] で、さらに多くの警告を有効にしてみてください。初期化されていないプライベート メンバーに対して警告が表示される可能性があると思います (余談ですが、これらのメンバーはおそらくプライベートである必要があります)。

于 2011-06-11T16:10:52.097 に答える