sydridgm
sydridgm

Reputation: 1062

call fragment method but fragment not prepared complitily

I want to dynamically create fragment. So when click the navigation fragment item, it will trigger the callback function in the activity to communicate with detail fragment. Here is the callback faction in activity:

public void getChatRoomId(long chatroom_id) {
    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    MsgChatRoom msgChatRoom = new MsgChatRoom();

    ft.replace(R.id.activity_chat_MsgChatroom_container, msgChatRoom, "messages");
    ft.addToBackStack(null);
    ft.commit();

    msgChatRoom.startQuery(chatroom_id);
}

I could call the startQuery method, but in that method I need some arguments should be initialize in onCreateActivity(). However, at the time when I call startQuery, the Fragment does not have called OncreateActivity. So there will be a error:

.... on a null object reference

How to solve this problem. Thanks in advance.

Upvotes: 1

Views: 36

Answers (1)

Pooya
Pooya

Reputation: 6136

You can pass arguments to the fragment by using Fragment's setArguments(Bundle) function.

When you create the fragment pass your arguments by setArguments() and then in your fragment retrieve them by calling getArguments() in this way you don't wait for specific fragment's life-cycle to be able to use your data.

For more information you can visit http://developer.android.com/reference/android/app/Fragment.html which also contains couple of examples of using these functions

Upvotes: 1

Related Questions