This question already has answers here:
What is a NullPointerException, and how do I fix it?
                            
                                (12个答案)
                            
                    
                去年关闭。
        

    

我在Android Studio中制作了一个健身应用程序,并且项目有多项活动(6)。我正在尝试从SixthActivity中的ThirdActivity获取无线电组的值。但是,当我尝试执行此操作时,出现错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.RadioGroup.getCheckedRadioButtonId()' on a null object reference


我已经确保xml代码中变量的所有名称都是正确的,并且仍然遇到相同的问题。


  SixthActivity.java


  Intent intent=getIntent();
  String experience =intent.getStringExtra("Experience");


我希望能够在SixthActivity中从ThirdActivity中的thirdRadioGroup RadioGroup获取值。

新代码:

//ThirdActivity.class

 thirdRadioGroup = findViewById(R.id.thirdRadioGroup);
 int radioIdExperience = thirdRadioGroup.getCheckedRadioButtonId();
 experience = (RadioButton) findViewById(radioIdExperience);
 Intent intent = new Intent(this, SixthActivity.class);
 intent.putExtra("Experience", experience.getText());
 startActivity(intent);


现在,再次抛出NullPointerException

error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference

最佳答案

因为ThirdActivity已暂停,所以您得到了空指针异常。 ThirdActivity已暂停,因为您正在运行第六项。从ThirdActivity获取数据的一种方法是在它们之间导航时将它们作为额外的意图值传递。
示例Java,您可以在ThirdActivity上执行此操作

Intent intent = new Intent(ThirdActivity .this, SixthActivity.class);
intent.putExtra("Experience",experience.getText());
startActivity(intent);


在第六项活动中,您将收到如下数据:

Intent intent=getIntent();
String experience =intent.getStringExtra("Experience");

关于java - 如何从不同的 Activity 中获得RadioGroup的值(value),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55387471/

10-10 18:24