我在为 EditTexts 设置初始输入时遇到了问题。每当我传递一个包含来自先前 Activity 的字符串的 Intent 时,它都会导致强制关闭。
我的程序的主要要点是,先前的 Activity 将包含字符串的 Intent 发送到 editText Activity 。如果未初始化,则 editTexts 为空,否则,它们包含前一屏幕的 TextView 中显示的值。这是我的代码:
EditText month, day, year;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.lab2_082588birthday);
Intent startUp = getIntent();
String receivedString = startUp.getStringExtra(Lab2_082588part2.BIRTHDAY_STRING);
if(receivedString.trim().length() > 0){
String[] separated = receivedString.split("/");
int stringMonth = Integer.parseInt(separated[0]);
int stringDay = Integer.parseInt(separated[1]);
int stringYear = Integer.parseInt(separated[2]);
month.setText(stringMonth);
day.setText(stringDay);
year.setText(stringDay);
}
}
这是我的LogCat
07-06 15:05:19.918: E/AndroidRuntime(276): Caused by: java.lang.NullPointerException
07-06 15:05:19.918: E/AndroidRuntime(276): at com.android.rondrich.Lab2_082588birthday.onCreate(Lab2_082588birthday.java:34)
07-06 15:05:19.918: E/AndroidRuntime(276): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-06 15:05:19.918: E/AndroidRuntime(276): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
最佳答案
如果 receivedString
没有以确保它有 2 个斜杠(“/”)的方式格式化,则字符串数组 separated
将不会有您指定的 3 个值需要。
这将导致 IndexOutOfBoundsException
。
编辑:
您必须使用反斜杠 "\/"
对斜杠字符进行转义。
关于java - numeric TextField 上的 setText 强制应用程序关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11357254/