我对android很新,可以使用一些帮助。我创建了一个应用程序,使您可以添加用户(在这种情况下,骑手)。点击'enter'后,会出现一个Toast,让用户知道该个人已成功添加。我希望清除editText框中的文本。我知道这里有很多解决方案,但它们都没有为我工作;他们都杀了我的应用程序。有帮助吗?代码参考:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
editText = (EditText) findViewById(R.id.new_rider_name);
setContentView(R.layout.add_rider_screen);
button = (Button) findViewById(R.id.addRiderButton);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
editText.setText("");
Toast.makeText(getApplicationContext(),
"The rider was successfully added!", Toast.LENGTH_LONG).show();
}
});
}
以下是logcat错误消息:
E/AndroidRuntime: FATAL EXCEPTION: main
E/AndroidRuntime: Process: com.example.cherryjp.buttonapp, PID: 8297
E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
E/AndroidRuntime: at com.example.cherryjp.buttonapp.AddRiderScreen$1.onClick(AddRiderScreen.java:38)
E/AndroidRuntime: at android.view.View.performClick(View.java:4780)
E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:19866)
E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime: at android.os.Looper.loop(Looper.java:135)
E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5254)
E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
答案 0 :(得分:3)
看起来您没有初始化onCreate
,在致电setText("")
之前需要在editText = (EditText) findViewById(R.id.yourEditTextId);
添加此行
setContentView
请确保在UITableViewController
之后
答案 1 :(得分:0)
正如Andrew Brooke所说,
您已在
之前初始化了editText setContentView(R.layout.add_rider_screen);
在此之后初始化你的editText,你很高兴.....
做这样的事情:
setContentView(R.layout.add_rider_screen);
editText = (EditText) findViewById(R.id.new_rider_name);