我正在尝试在代码中动态添加TextView小部件,但它在setText()行中不断崩溃:
TextView tv = new TextView(MainActivity.this);
tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
tv.setText("YOU: " + ET_message.getText().toString()); //this line crashes
ll = (LinearLayout) findViewById(R.id.LL);
ll.addView(tv);
有人知道为什么吗?它应该是这里最简单的路线。
编辑:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.guy_sh.messenger.MainActivity.onClick(MainActivity.java:30)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24697)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
编辑#2:代码更改
if(!TextUtils.isEmpty(ET_message.getText())) {
TextView tv = new TextView(MainActivity.this);
tv.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
tv.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
tv.setText("YOU: " + ET_message.getText().toString());
ll = (LinearLayout) findViewById(R.id.LL);
ll.addView(tv);
}
答案 0 :(得分:1)
您的堆栈跟踪告诉您ET_message
为空。我在评论中看到你说过
它肯定不是空的。我写了它。
重要的是要理解以下两件事情可以同时成立:
EditText
,您可以输入ET_message
的变量目前包含null
值找到您为ET_message
分配值的地方(可能是findViewById()
来电)。确保您传递的是正确的ID,并且您使用android:id
标记中包含该值的<EditText>
属性。