android java onClick 无法执行活动的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29287152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
android java onClick Could not execute method of the activity
提问by svenvdz
This is my first time working with the recyclerview and I am getting some errors about android:onClick="addItem"
here is what I get when I try to add a line of text to my recyclerview. I usually use my phone to test my apps.
这是我第一次使用 recyclerview,android:onClick="addItem"
当我尝试将一行文本添加到我的 recyclerview 时,我遇到了一些关于这里的错误。我通常用我的手机来测试我的应用程序。
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View.onClick(View.java:4012)
at android.view.View.performClick(View.java:4761)
at android.view.View$PerformClick.run(View.java:19767)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View.onClick(View.java:4007)
????????????at android.view.View.performClick(View.java:4761)
????????????at android.view.View$PerformClick.run(View.java:19767)
????????????at android.os.Handler.handleCallback(Handler.java:739)
????????????at android.os.Handler.dispatchMessage(Handler.java:95)
????????????at android.os.Looper.loop(Looper.java:135)
????????????at android.app.ActivityThread.main(ActivityThread.java:5312)
????????????at java.lang.reflect.Method.invoke(Native Method)
????????????at java.lang.reflect.Method.invoke(Method.java:372)
????????????at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
????????????at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.sapps.app.testapp2.MainActivity.addItem(MainActivity.java:53)
????????????at java.lang.reflect.Method.invoke(Native Method)
????????????at java.lang.reflect.Method.invoke(Method.java:372)
????????????at android.view.View.onClick(View.java:4007)
????????????at android.view.View.performClick(View.java:4761)
????????????at android.view.View$PerformClick.run(View.java:19767)
????????????at android.os.Handler.handleCallback(Handler.java:739)
????????????at android.os.Handler.dispatchMessage(Handler.java:95)
????????????at android.os.Looper.loop(Looper.java:135)
????????????at android.app.ActivityThread.main(ActivityThread.java:5312)
????????????at java.lang.reflect.Method.invoke(Native Method)
????????????at java.lang.reflect.Method.invoke(Method.java:372)
????????????at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
????????????at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Here is my code where I think is the error, but I don't know exactly:
这是我认为是错误的代码,但我不确切知道:
public class MainActivity extends ActionBarActivity {
private EditText mText;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView recyclerView;
private Button btn;
private CustomRecyclerAdapter mAdapter;
private List<Data> mData = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing views.
mText = (EditText) findViewById(R.id.textEt);
recyclerView = (RecyclerView) findViewById(R.id.recycler);
// If the size of views will not change as the data changes.
recyclerView.setHasFixedSize(true);
// Setting the LayoutManager.
mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
// Setting the adapter.
CustomRecyclerAdapter mAdapter = new CustomRecyclerAdapter();
recyclerView.setAdapter(mAdapter);
}
// Called when add button is clicked.
public void addItem(View v) {
if(mText!=null) {
Data dataToAdd = new Data(mText.getText().toString()); mData.add(dataToAdd);
}
}
}
}
And here is my recyclerview adapter to know for sure:
这是我要确定的 recyclerview 适配器:
public class CustomRecyclerAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
CustomRecyclerAdapter mAdapter;
private List<Data> mData = Collections.emptyList();
public CustomRecyclerAdapter() {
// Pass context or other static stuff that will be needed.
}
public void updateList(List<Data> data) {
mData = data;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
return mData.size();
}
@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View itemView = inflater.inflate(R.layout.list_item, viewGroup, false);
return new RecyclerViewHolder(itemView);
}
@Override
public void onBindViewHolder(RecyclerViewHolder viewHolder, int position) {
viewHolder.title.setText(mData.get(position).text);
}
public void addItemInRec(int position, Data data) {
mData.add(data);
notifyItemInserted(position);
}
public void removeItem(int position) {
mData.remove(position);
notifyItemRemoved(position);
}
}
My MainActivity xml file:
我的 MainActivity xml 文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/textEt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Text"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:onClick="addItem"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"/>
</LinearLayout>
Maybe it is my ViewHolder:
也许是我的 ViewHolder:
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public RecyclerViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
}
}
Or Data.java class:
或 Data.java 类:
public class Data {
public String text;
public Data(String text) {
this.text = text;
}
}
回答by meda
You are getting a null pointer on the getText()
call
你在getText()
通话中得到一个空指针
It means the following line:
这意味着以下行:
EditText mText = (EditText) findViewById(R.id.textEt);
returns null, solution is to check and correct the layout so that textEt
is on it.
返回 null,解决方案是检查并更正布局,以便textEt
在其上。
Edit:
编辑:
If you are sure that it's in the layout remove EditText
declaration.
如果您确定它在布局中,请删除EditText
声明。
Declare as private EditText mText;
on the class scope
private EditText mText;
在类范围内声明
setContentView(R.layout.name_of_layout_here);
mText = (EditText) findViewById(R.id.textEt);
回答by Kio Krofovitch
The key is in your error message:
关键在您的错误消息中:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.sapps.app.testapp2.MainActivity.addItem(MainActivity.java:53)
A good tip for learning from your error output is to look at each "Caused by" statement, and scan through the log until you find one of your own files referenced. Then that part of the error log will even tell you what line your code was failing on ( in this case it is line 53 on MainActivity.java).
从错误输出中学习的一个很好的技巧是查看每个“Caused by”语句,并扫描日志,直到找到您自己引用的文件之一。然后错误日志的那部分甚至会告诉你你的代码在哪一行失败(在这种情况下它是 MainActivity.java 的第 53 行)。
A Null Pointer Exception in Java is when you attempt to call a method on some object 'A', but that object 'A' is currently null
.
Java 中的空指针异常是当您尝试对某个对象“A”调用方法时,但该对象“A”当前为null
。
So this error message means: "On line 53 of MainActivity.java, you tried to call a method on some object which doesn't exist yet, so I crashed."
所以这个错误信息的意思是:“在 MainActivity.java 的第 53 行,你试图调用某个尚不存在的对象的方法,所以我崩溃了。”
The method that is failing is EditText mText = (EditText) findViewById(R.id.textEt);
失败的方法是 EditText mText = (EditText) findViewById(R.id.textEt);
Usually this type of failure means that you aren't finding the right ID from your layout. Double check that textEt
is the correct ID for this layout element.
通常这种类型的失败意味着您没有从布局中找到正确的 ID。仔细检查textEt
此布局元素的正确 ID。
EDIT:
编辑:
Still not sure why your views aren't getting populated, but I did notice an error with your adapter. You are redefining mAdapter
, so you have 2 copies, one in local scope and one as a member to MainActivity. This will definitely mess things up.
仍然不确定为什么您的视图没有被填充,但我确实注意到您的适配器有错误。您正在重新定义mAdapter
,因此您有 2 个副本,一个在本地范围内,另一个作为 MainActivity 的成员。这肯定会把事情搞砸。
Right here:
就在这儿:
// Setting the adapter.
CustomRecyclerAdapter mAdapter = new CustomRecyclerAdapter();
recyclerView.setAdapter(mAdapter)
You are redefining mAdapter
locally. Do this instead:
您正在mAdapter
本地重新定义。改为这样做:
// Setting the adapter.
mAdapter = new CustomRecyclerAdapter();
recyclerView.setAdapter(mAdapter)
回答by hexicle
The view in addItem(View v)
is referring to the button only.
The EditText
object that you want is not in the button, it is in the button's parent view.
If you try to access the object from the button view it will be null, because the button does not have it.
Instead you need to access the object from the button's parent view.
中的视图addItem(View v)
仅指按钮。EditText
您想要的对象不在按钮中,它在按钮的父视图中。如果您尝试从按钮视图访问该对象,它将为 null,因为该按钮没有它。相反,您需要从按钮的父视图访问该对象。
// Solution:
public void addItem(View v) {
View parentView = (View) v.getParent();
EditText mText = (EditText) parentView.findViewById(R.id.textEt);
Log.d("LOG", mText.getText().toString()));
}
I know that technically this does not solve the code in the question. But the code in the question has been changed from what produced the error so this would solve the original buggy code that actually produced the question. I am guessing that the original buggy code looked like this:
我知道从技术上讲这并不能解决问题中的代码。但是问题中的代码已从产生错误的原因进行了更改,因此这将解决实际产生问题的原始错误代码。我猜原来的错误代码是这样的:
// My guess this was the original buggy code
// MainActivity.java
public void addItem(View v) {
EditText mText = (EditText) v.findViewById(R.id.textEt);
Data dataToAdd = new Data(mText.getText().toString());
mData.add(dataToAdd);
}
// MainActivity.xml
<LinearLayout>
<EditText
android:id="@+id/textEt"
/>
<Button
android:text="Add"
android:onClick="addItem"/>
</LinearLayout>
回答by Swapnil Acharya
Change public void addItemInRec to public void addItem. There is no method for onClick in mainActivity.
将 public void addItemInRec 更改为 public void addItem。mainActivity 中没有 onClick 的方法。