Android应用程序在测试时崩溃
好的,我是这里论坛的新手,所以我不确定这个问题是否足够具体,但我的代码如下Android应用程序在测试时崩溃,android,Android,好的,我是这里论坛的新手,所以我不确定这个问题是否足够具体,但我的代码如下 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String firstNo = ((EditText) findViewById(R.id.txtRent)).getText().toString();
int ApartmentCost = Integer.parseInt(firstNo);
TextView txtTotal = (TextView) findViewById(R.id.lblTotal);
txtTotal.setText(ApartmentCost);
}
});
}
每当我尝试将一个值放入文本框以查看它是否显示时,我都会得到以下错误代码
02-04 10:42:19.496 1072-1072/com.example.itc201.appartmentsharing E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: String resource ID #0x1f4
at android.content.res.Resources.getText(Resources.java:239)
at android.widget.TextView.setText(TextView.java:3844)
at
com.example.itc201.appartmentsharing.MainActivity$1.onClick(MainActivity.java:34)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
任何帮助都会很好 更改此行
txtTotal.setText(ApartmentCost);
这条线
txtTotal.setText(ApartmentCost+"");
由于ApartmentCost是一种int类型,它会与资源id混淆。代码中有3个错误 首先,您不能像在代码中那样在onClick中获取视图,而是在edittext和textview中获取视图。通过stacktrace,当您试图从没有有效resourceid的资源获取数据时,代码会崩溃 第二,将int放入字符串将再次返回错误 修理
TextView txtTotal;
EditText edtFirst;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
txtTotal = (TextView) findViewById(R.id.lblTotal);
edtFirst = (EditText) findViewById(R.id.txtRent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String firstNo = edtFirst.getText().toString();
txtTotal.setText(firstNo);
int ApartmentCost = Integer.parseInt(firstNo); //if you need a int after
}
});
}
另一点,请确保具有此资源(R.id.txtRent)的edittext存在Usetxtotal.setText(String.valueOf(ApartmentCost))代码>问题发生的原因是您正在将int
传递给seText
哪个系统认为是资源ID的可能重复项