[英]Passing EditText integer to TextView via Intent app crashes after clicking (button) three
I am trying just to pass the int user input to the next class and print it, see that it works before continuing on using it or something else. 我试图将int用户输入传递给下一个类并打印它,然后在继续使用它或其他东西之前先查看它是否有效。
Home.java 家.java
start and exit button 开始和退出按钮
public class Home extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button one = (Button) findViewById(R.id.b1);
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
goToSecondActivity();
}
});
Button two = (Button) findViewById(R.id.b2);
two.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private void goToSecondActivity() {
Intent i = new Intent(this, SelectNumberOfPlayers.class);
startActivity(i);
}
}
SelectNumberOfPlayers.java
Taking only the numbers from the input and passing it to StartGame.class 仅从输入中获取数字并将其传递给StartGame.class
public class SelectNumberOfPlayers extends AppCompatActivity {
EditText numberOfPlayers;
Button three;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enter_number_of_players);
three = (Button) findViewById(R.id.button3);
three.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String txt = numberOfPlayers.getText().toString();
Intent i = new Intent(getApplicationContext(), StartGame.class);
i.putExtra("players", txt);
startActivity(i);
}
});
}
}
StartGame.java
Receiving Int and printing to TextView 接收Int并打印到TextView
public class StartGame extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_game);
Intent i = getIntent();
TextView numOfPlayersVal = (TextView) findViewById(R.id.txt2);
numOfPlayersVal.setText(i.getStringExtra("Player number"));
}
}
Where is the error happening? 错误在哪里发生? I've set the input keyboard to take only numbers
我将输入键盘设置为仅包含数字
1. you forgot to initialize youe editext first initialize it in your SelectNumberOfPlayers Activity 1.您忘了初始化自己的editext,然后先在SelectNumberOfPlayers活动中对其进行初始化
numberOfPlayers = (EditText) findViewById(R.id.numberOfPlayers);
2. the key must be same to pass and receive data with intent 2.密钥必须相同,才能有意传递和接收数据
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_game);
Intent i = getIntent();
TextView numOfPlayersVal = (TextView) findViewById(R.id.txt2);
numOfPlayersVal.setText(i.getStringExtra("players"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.