如何在打开选项卡时刷新片段?

时间:2016-06-29 13:57:40

标签: android android-fragments android-viewpager

我有一个片段,它从一个活动中调用,在其中一个标签中显示。我希望每次单击片段的选项卡按钮时都会刷新片段数据 这是我的片段 -

public class ChatFragment extends Fragment {

    private String TAG = MainActivity.class.getSimpleName();
    private ArrayList<ChatRoom> chatRoomArrayList;
    private ChatRoomsAdapter mAdapter;
    private RecyclerView recyclerView;
    View convertedView;
    private String selfUserId;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        convertedView = inflater.inflate(R.layout.content_main, null, false);
        return convertedView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

        //setListAdapter(adapter);
        //getListView().setOnItemClickListener(this);
        //registerForContextMenu(getListView());

        recyclerView = (RecyclerView) convertedView.findViewById(R.id.recycler_view);

        selfUserId = MyApplication.getInstance().getPrefManager().getUser().getId();

        chatRoomArrayList = new ArrayList<>();
        mAdapter = new ChatRoomsAdapter(getContext(), chatRoomArrayList);

        final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
                getContext().getApplicationContext()
        ));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

        recyclerView.addOnItemTouchListener(new ChatRoomsAdapter.RecyclerTouchListener(getContext().getApplicationContext(),
                recyclerView, new ChatRoomsAdapter.ClickListener() {
            @Override
            public void onClick(View view, int position) {
                // when chat is clicked, launch full chat thread activity
                ChatRoom userChatRoom = chatRoomArrayList.get(position);
                Intent intent = new Intent(getContext(), ChatRoomActivity.class);
                intent.putExtra("user_id", userChatRoom.getId());
                intent.putExtra("name", userChatRoom.getName());
                startActivity(intent);
            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));

        fetchChats();
    }

    private void fetchChats() {
        String endPoint = EndPoints.CHAT_ROOMS.replace("_ID_", selfUserId);
        Log.e(TAG, "endPoint: " + endPoint);
        StringRequest strReq = new StringRequest(Request.Method.GET,
                endPoint, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.e(TAG, "response: " + response);

                try {
                    JSONObject obj = new JSONObject(response);

                    // check for error flag
                    if (obj.getBoolean("error") == false) {
                        JSONArray chatRoomsArray = obj.getJSONArray("chat_rooms");
                        for (int i = 0; i < chatRoomsArray.length(); i++) {
                            JSONObject chatRoomsObj = (JSONObject) chatRoomsArray.get(i);
                            ChatRoom cr = new ChatRoom();
                            cr.setId(chatRoomsObj.getString("user_id"));
                            cr.setName(chatRoomsObj.getString("name"));
                            cr.setLastMessage("");
                            cr.setUnreadCount(0);
                            cr.setTimestamp(chatRoomsObj.getString("created_at"));

                            chatRoomArrayList.add(cr);
                        }

                    } else {
                        // error in fetching chat rooms
                        Toast.makeText(getContext().getApplicationContext(), "" + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
                    }

                } catch (JSONException e) {
                    Log.e(TAG, "json parsing error: " + e.getMessage());
                    Toast.makeText(getContext().getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

                mAdapter.notifyDataSetChanged();

                // subscribing to all chat room topics
                //subscribeToAllTopics();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                NetworkResponse networkResponse = error.networkResponse;
                Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
                Toast.makeText(getContext().getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        //Adding request to request queue
        MyApplication.getInstance().addToRequestQueue(strReq);
    }
}

每当我打开选项卡以显示此片段时,我希望调用fetchChats()以使用新更新的Chats刷新片段中的视图。我怎么能这样做?
错误日志 -

FATAL EXCEPTION: main
                                                            Process: com.wipro.chat, PID: 19283
                                                            java.lang.NullPointerException: replacement == null
                                                                at java.lang.String.replace(String.java:972)
                                                                at com.wipro.chat.tabs.ChatFragment.fetchChats(ChatFragment.java:112)
                                                                at com.wipro.chat.tabs.ChatFragment.setUserVisibleHint(ChatFragment.java:107)
                                                                at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)
                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1175)
                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
                                                                at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
                                                                at android.view.View.measure(View.java:18788)
                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:668)
                                                                at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:735)
                                                                at android.view.View.measure(View.java:18788)
                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                at android.view.View.measure(View.java:18788)
                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
                                                                at android.view.View.measure(View.java:18788)
                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                at android.view.View.measure(View.java:18788)
                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
                                                                at android.view.View.measure(View.java:18788)
                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
                                                                at android.view.View.measure(View.java:18788)
                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:670)
                                                                at android.view.Choreographer.doFrame(Choreographer.java:606)
                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                at android.os.Looper.loop(Looper.java:148)
                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

2 个答案:

答案 0 :(得分:1)

覆盖片段中的onResume()方法,然后只需拨打fetchChats()中的onResume()

您也可以在片段的onStart()方法中执行此操作。

如果在您的情况下没有调用这些方法,请将fetchChats()从私有更改为公共。然后保留对您的片段的引用。向选中时调用的选项卡添加一个监听器,并在选择所需选项卡时调用fragment.fetchChats()

答案 1 :(得分:0)

覆盖片段中的方法

  @Override
  public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
       //do your work here
    }
  }