dimanche 25 décembre 2016

Communication between Fragment and Activity in Android

I considered this documentation and several SO questions or different tutorials for fragment to activity communication. I'm building a simple chat for my App. When I click a chat room in my InboxFragment I want to pass the name of the chat room to my ChatActivity and add the name of the chat room to the ListView inside the ChatActivity.

The Problem is that I always get the error message that the ChatActivity doesn't implement the interface OnChatRommSelected.

The error message is:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.lyl.nairad, PID: 3018
                  java.lang.ClassCastException: com.lyl.nairad.Activities.MainAppActivity@2600f9ae must implement OnChatRoomSelected
                      at com.lyl.nairad.Fragments.InboxFragment.onStart(InboxFragment.java:137)

My InboxFragment looks like this:

EDIT: In the InboxFragment are some more variables, etc. but I let them away to keep the code as short as possible.

public class InboxFragment extends Fragment {

    // [BEGIN: Communication instances
    OnChatRoomSelected mCallback;
    // END]

    private final String TAG = "InboxFragment";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_inbox, container, false);
        callingActivity = getActivity();
        // Some Code...

        chats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                sendChatRoomName(String.valueOf(chats.getItemAtPosition(position)));
                Intent i = new Intent(getActivity(), ChatActivity.class);
                startActivity(i);
            }
        });

        return view;
    }
    public void refresh(){

        ((TextView)getActivity().findViewById(R.id.toolbar_title)).setText("Chats");
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    // [BEGIN: Interface for Fragment to Activity Communication
    public interface OnChatRoomSelected {
        public void selectedChatRoom(String chatRoomName);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onStart() {
        super.onStart();
        try {
            mCallback = (OnChatRoomSelected) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString()
                    + " must implement OnChatRoomSelected");
        }
    }

    public void sendChatRoomName(String chatRoomName) {
        mCallback.selectedChatRoom(chatRoomName);
    }
    // END}
}

My ChatActivity looks like this:

public class ChatActivity extends Activity implements InboxFragment.OnChatRoomSelected {

    Button send;
    EditText msgField;
    ListView newsExtending;
    ArrayList<String> messages;
    ArrayAdapter<String> adapter;

    private final String TAG = "ChatActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        messages = new ArrayList<>();
        send = (Button) findViewById(R.id.sendMsgBtn);
        msgField = (EditText) findViewById(R.id.aMessage);
        newsExtending = (ListView) findViewById(R.id.privateMessagesList);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, messages);
        newsExtending.setAdapter(adapter);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = msgField.getText().toString();
                messages.add(text);
                adapter.notifyDataSetChanged();
                msgField.setText("");
            }
        });

    }
    @Override
    public void selectedChatRoom(String chatRoomName) {
        messages.add(chatRoomName);
        adapter.notifyDataSetChanged();
    }

}



When I comment out

@Override
    public void onStart() {
        super.onStart();
       /* try {
            mCallback = (OnChatRoomSelected) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString()
                    + " must implement OnChatRoomSelected");
        }*/
    }

in the InboxFragment, my error looks like this:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.lyl.nairad, PID: 3334
                  java.lang.NullPointerException: Attempt to invoke interface method 'void com.lyl.nairad.Fragments.InboxFragment$OnChatRoomSelected.selectedChatRoom(java.lang.String)' on a null object reference
                      at com.lyl.nairad.Fragments.InboxFragment.sendChatRoomName(InboxFragment.java:143)
                      at com.lyl.nairad.Fragments.InboxFragment$2.onItemClick(InboxFragment.java:102)

Aucun commentaire:

Enregistrer un commentaire