[英]Null Pointer Exception when passing value from Fragment to Activity
The parent activity has a String List that's instantiated like this. 父活动具有这样的实例化的字符串列表。
List<String> taskList = asList("Write some code", "Database stuff", "Test the cloud!");
It also has a HeadlineSelected-listener implemented as an interface, along with an ArticleSelected-method. 它还具有HeadlineSelected-listener实现为接口,以及ArticleSelected-method。 The ArticleSelected-method removes an element from the list.
ArticleSelected方法从列表中删除一个元素。
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
@Override
public void onArticleSelected(int position) {
taskList.remove(position);
}
In the fragment, I have a HeadlineListener to send stuff to it's parent activity. 在该片段中,我有一个HeadlineListener来向其父活动发送内容。
OnHeadlineSelectedListener mCallback;
In the fragment, I use the HeadlineListener once an Item is chosen. 在片段中,选择项目后,我将使用HeadlineListener。
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mCallback.onArticleSelected(position);
finish();
}
I can start the app just fine, but when I select an item the app stops and I get a Null Pointer Excpetion. 我可以很好地启动该应用程序,但是当我选择一个项目时,该应用程序将停止并且出现空指针异常。 What am I doing wrong?
我究竟做错了什么?
but when I select an item the app stops and I get a Null Pointer Excpetion.
但是当我选择一个项目时,应用程序停止运行,并且出现空指针异常。 What am I doing wrong?
我究竟做错了什么?
You need to initialize mCallBack
. 您需要初始化
mCallBack
。 I am not sure if initialize is the right term. 我不确定初始化是否正确。
But you need the below. 但是您需要以下内容。
Quoting docs 报价文件
The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.
片段在其onAttach()生命周期方法中捕获接口实现,然后可以调用Interface方法以与Activity通信。
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
The reason I got the error was because I'd made the List un-alterable by setting it's values in the cosntructor. 我收到错误的原因是因为我通过在cosntructor中设置其值使List不可更改。 If I didn't set the values at all when taskList was created as a member variable.
如果在创建taskList作为成员变量时根本没有设置任何值。
private List<String> taskList;
I could then make it into a clean List in the onCreate 然后,我可以将其放入onCreate中的干净列表中
taskList = new ArrayList<String>();
and add the elements afterwards. 然后添加元素。 Since I was going to scale it up to read from a database in it's onCreate, this wasn't an issue.
由于我打算将其放大以从onCreate的数据库中读取,因此这不是问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.