尝试对空对象引用调用虚拟方法java.lang.CharSequence中android.widge

2019-09-29 21:22发布

我得到这个空例外:

显示java.lang.NullPointerException:尝试调用虚拟方法“java.lang.CharSequence中android.widget.TextView.getText()”上的空对象引用

我不知道为什么。

protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setTheme(R.style.LoginRegister);
        setContentView(R.layout.activity_report);

final TextView infoid = (TextView) findViewById(R.id.idInfo);

        RadioGroup rg = (RadioGroup)findViewById(R.id.rg);
        final String radiovalue = ((RadioButton)findViewById(rg.getCheckedRadioButtonId())).getText().toString();

...

        Button sendButton = (Button) findViewById(R.id.button2);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text = infoid.getText().toString(); //what is wrong?
                Log.w("message: ", radiovalue);
            }
        });


}

我的XML

   <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/idInfo"
        android:hint="Add some extra information"
        android:layout_weight="0.09"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp" />

    <Button
        android:text="Report"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button2" />

有任何想法吗?

Answer 1:

  1. 确保TextView idInfo是在你的存在activity_report.xml
  2. 尝试宣告idInfo全球。

     .............. .................... TextView infoid; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_report); infoid = (TextView) findViewById(R.id.idInfo); ............. ................... Button sendButton = (Button) findViewById(R.id.button2); sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String text = infoid.getText().toString(); .......... ................. } }); } 

更新:

要获得所选radioButton的文字:

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.rg);

// get selected radioButton from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();

// find the radioButton by returned id
radioButton = (RadioButton) findViewById(selectedId);

// radioButton text
String radiovalue = radioButton.getText();

希望这将帮助〜



Answer 2:

if (radioGroup.getCheckedRadioButtonId() <= 0) {
    Toast.makeText(yourclass, "Choose Radio Button Please", Toast.LENGTH_SHORT).show();
}


文章来源: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference