我已经声明了我的变量,并收集了关于我的主要活动的数据。我已经设置了意图,并在我的结果活动上收集了意图。问题似乎是数据没有从主活动传递到所需的屏幕。
主要目标是在新的活动屏幕上显示结果。
public class MainActivity extends AppCompatActivity {
//variables
Button btnCalculate, btnReset;
Spinner spinSpeaker;
EditText editLength, editWidth, editHeight;
String t1,t2,t3;
int numLength, numWidth, numHeight, numResult=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//connecting variables to GUI elements
btnCalculate= findViewById(R.id.btnCalculate);
btnReset = findViewById(R.id.btnReset2);
spinSpeaker = findViewById(R.id.spinSpeaker);
editLength= findViewById(R.id.editLength);
editWidth = findViewById(R.id.editWidth);
editHeight = findViewById(R.id.editHeight);
//adding function to the calculate button
btnCalculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//parsing text to integers
t1=editLength.getText().toString();
t2=editWidth.getText().toString();
t3=editHeight.getText().toString();
if (t3.equals("")) {
editHeight.setText("11");
}else if (t2.equals("")) {
editWidth.setText("11");
}else if (t1.equals("")) {
editLength.setText("11");
}else{
numLength = Integer.parseInt(t1);
numWidth = Integer.parseInt(t2);
numHeight = Integer.parseInt(t3);
}
//alert to contact Pro design
if ((numLength>=999)||(numWidth>=999)||(numHeight>=20)) {
Toast.makeText(MainActivity.this, R.string.contactPro,
Toast.LENGTH_LONG).show();
}else {
//calculating volume
numResult = numHeight * numWidth * numLength;
//sending data to other activities
Intent intent = new Intent(MainActivity.this, Result.class);
intent.putExtra("varHeight", numHeight);
intent.putExtra("varWidth", numWidth);
intent.putExtra("varLength", numLength);
intent.putExtra("varResult", numResult);
startActivity(intent);
}
}
});
//the following is the result activity
public class Result extends AppCompatActivity {
//Pulling variables from main activity
Intent variables = getIntent();
//int length = variables.getIntExtra("varLength",0);
//int width =variables.getIntExtra("varWidth",0);
int totalResult = variables.getIntExtra("varResult",0);
String result = String.valueOf(totalResult);
TextView tim;
Canvas canvas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
canvas = new Canvas(this);
setContentView(R.layout.activity_result);
//setContentView(canvas);
tim = findViewById(R.id.txtResult);
tim.setText(result);
我原以为R.id.txtResult会在第二个屏幕上显示numResult = numHeight * numWidth * numLength;。
我一直收到的错误信息是::
原因: java.lang.NullPointerException:试图对com.example.project.Result处的空对象引用调用虚方法'int android.content.Intent.getIntExtra(java.lang.String,int)‘。(Result.java:23)
https://stackoverflow.com/questions/56570810
复制相似问题