Get a list of friends met from the server when the pit

In recent parodies micro letter, the list needs to be a friend after the user logs displayed.
The basic idea is that when the user clicks the login button will save the user name (username) to the intent, and then start activities at the event through
Intent intent = getIntent();String username = intent.getStringExtra();在这里插入代码片
to get username, and then open thread, send a request list of friends packet to the server, like the following

// 新开线程,向服务端发送一个请求朋友列表的包
        new Thread() {
            @Override
            public void run() {
                try {
                    RequestFriendsPacket packet = new RequestFriendsPacket(username);
                    Socket socket = new Socket("10.0.2.2", 2018);
                    OutputStream out = socket.getOutputStream();
                    InputStream in = socket.getInputStream();

                    out.write(packet.serialize());
                    out.flush();

                    byte[] buffer = new byte[1024];
                    int length = in.read(buffer);
                    String friendsInThread = new String(buffer, 0, length);

                    // 通过消息机制修改主线程中的friends
                    Message message = new Message();
                    message.what = 0x0001;
                    message.obj = friendsInThread;
                    mainActHandler.sendMessage(message);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

This resulted in a friend list information (Friends), then disassemble the string array to obtain the name of a group of friends, as shown below

String allFriends[] = friends.split("[|]");// 拆解得到本用户所有的朋友
for (int i = 0; i < allFriends.length; i++)
	Log.d("friends=====", allFriends[i]);

Then initialize RecyerView in chat summary list (chatItemList) can be.

But here pay attention to several issues (that is, I encountered the pit, whining):
1, requesting buddy information (friends) thread is running slower than the main thread, so initFragment originally executed in the main thread () ; is to be placed in the Handler, Handler here is to send a request to complete post-processing sub-thread to the main thread of the message must be initialized here our Fragment, or will lead to a summary of Fragment chat friends name is missing. I wrote Handler as follows:

public Handler mainActHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x0001) {
                friends = (String) msg.obj;
                Log.d("mainActHandler===", friends + "====");
//                fragments[0] = new WeixinFragment(friends);
                initFragment();
            }
        }
    };在这里插入代码片

2, when acquiring Activity in the Fragment associated therewith, the method is preferably placed in the body and not on the outside as on the outside, then there may not be performed as follows:

public class WeixinFragment extends Fragment {
    private List<ChatItem> chatItemList = new ArrayList<>();

    private MainActivity mainActivity;

    private String friends = "";



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

        mainActivity = (MainActivity) getActivity();// 获取主活动

        // 得到主活动中的当前用户名,然后根据这个发送一个请求朋友列表的包给服务端,服务端根据用户名
        // 进入数据库查询都该用户的所有朋友,然后将信息(一个包含朋友列表的字符串)返回到本地即可
        Log.d("===fragmentIndex:", Integer.toString(mainActivity.getFragmentIndex()));




        friends = mainActivity.getFriends();// 这句话如果报空指针异常,将mainActivity = (MainActivity) getActivity();// 获取主活动移动到onCreateView()方法中






        Log.d("===friends:", friends);

        initChatItems();// 初始化各个聊天子项

        // 获取“微信”碎片
        LinearLayout chatItemLayout = (LinearLayout) inflater.inflate(R.layout.fragment_weixin, container, false);

        // 获取”微信“碎片中的RecyclerView,也就是聊天项目列表
        RecyclerView chatItemRecyclerView = chatItemLayout.findViewById(R.id.chat_item_recycler_view);

        // 设置分割线
//        chatItemRecyclerView.addItemDecoration(new DividerItemDecoration(mainActivity, DividerItemDecoration.VERTICAL));

        chatItemRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.VERTICAL));


        // 获取布局管理
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mainActivity);
        chatItemRecyclerView.setLayoutManager(linearLayoutManager);

        ChatItemAdapter chatItemAdapter = new ChatItemAdapter(getActivity(), chatItemList);
        chatItemRecyclerView.setAdapter(chatItemAdapter);

        // 这里要注意,重新渲染的话R.layout.fragment_weixin
        // 是会被重置的,这就解释了为什么页面会加载不出来了
        // 所以直接将chatItemLayout返回就可以了
//        return inflater.inflate(R.layout.fragment_weixin, container, false);
        return chatItemLayout;
    }

3, requesting buddy list information (friends), finished data to the server must read the data returned from the server immediately, or wait for the current socket turned off, then the program in other locations can not get this to create a socket of the socket , not to mention get his data the (white level is limited, in this place cards for a long time ......)

Published 19 original articles · won praise 5 · Views 4210

Guess you like

Origin blog.csdn.net/qq_41409120/article/details/84333301