简体   繁体   中英

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. The ArticleSelected-method removes an element from the list.

    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.

    OnHeadlineSelectedListener mCallback;

In the fragment, I use the HeadlineListener once an Item is chosen.

    @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 . 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.

@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. If I didn't set the values at all when taskList was created as a member variable.

private List<String> taskList;

I could then make it into a clean List in the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM