导航抽屉中类似碎片的问题

时间:2018-09-01 09:24:43

标签: android android-fragments android-recyclerview retrofit2

我有上一个问题Why it does not show the required fragment when nav drawer android menu option is selected?,我已经在其中强调了一些问题,但是这个问题的表述方式有些不正确,所以我决定创建一个新问题。

在我的应用程序中,有两个片段执行对两个消息列表的请求-传入和传出。这些片段的代码如下所示:

传入片段:

public class Received extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    private OnFragmentInteractionListener mListener;
    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    ArrayList<Message> messageArrayList;
    SwipeRefreshLayout mSwipeRefreshLayout;
    SharedPreferences sp;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_received, container, false);
        recyclerView = rootView.findViewById(R.id.list_res);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        received();
        mSwipeRefreshLayout = rootView.findViewById(R.id.refresh_2);
        mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        return rootView;
    }

    @Override
    public void onRefresh() {
        received();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    public void received() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://0000/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        adapter = null;

        sp = Objects.requireNonNull(getActivity()).getSharedPreferences("access_token", 0);
        String a_token = sp.getString("access_token", "");

        final APIService mAPIService = retrofit.create(APIService.class);
        mAPIService.getInMess("Bearer " + a_token, 0, 1).enqueue(new Callback<MessageArray>() {

            @Override
            public void onResponse(@NonNull Call<MessageArray> call, @NonNull Response<MessageArray> response) {
                if (response.isSuccessful()) {
                    messageArrayList = (ArrayList<Message>) Objects.requireNonNull(response.body()).getMessages();
                    adapter = new MessageAdapter(messageArrayList, getActivity());
                    recyclerView.setAdapter(adapter);
                    mSwipeRefreshLayout.setRefreshing(false);

                } else {
                    ResponseBody errorBody = response.errorBody();
                    try {
                        if (Objects.requireNonNull(errorBody).string().contains("access_token_expired")) {
                            updateToken();

                        } else if (errorBody.string().contains("invalid_token")) {
                            updateToken();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<MessageArray> call, @NonNull Throwable t) {


            }
        });
    }

    public void updateToken() {

    }


    public void logOut() {

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

去向片段:

public class Sent extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    private OnFragmentInteractionListener mListener;
    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;

    ArrayList<Message> messageArrayList;
    SwipeRefreshLayout mSwipeRefreshLayout;

    private boolean isVisible;
    private boolean isStarted;


    SharedPreferences sp;
    private Context context;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_sent, container, false);
        recyclerView = rootView.findViewById(R.id.list_sen);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        mSwipeRefreshLayout = rootView.findViewById(R.id.refresh_1);
        mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        return rootView;
    }

    @Override
    public void onRefresh() {
        sent();
    }

    @Override
    public void onStart() {
        super.onStart();
        isStarted = true;
        if (isVisible) {
            sent();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        isStarted = false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (isVisible && isStarted) {
            sent();
        }
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    public void sent() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://0000/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        adapter = null;

        sp = Objects.requireNonNull(context).getSharedPreferences("access_token", 0);


        String a_token = sp.getString("access_token", "");
        APIService mAPIService = retrofit.create(APIService.class);
        mAPIService.getInMess("Bearer " + a_token, 1, 1).enqueue(new Callback<MessageArray>() {
            @Override
            public void onResponse(@NonNull Call<MessageArray> call, @NonNull Response<MessageArray> response) {

                if (response.isSuccessful()) {
                    messageArrayList = (ArrayList<Message>) Objects.requireNonNull(response.body()).getMessages();
                    adapter = new MessageAdapter2(messageArrayList, getActivity());
                    recyclerView.setAdapter(adapter);
                    mSwipeRefreshLayout.setRefreshing(false);


                } else {
                    ResponseBody errorBody = response.errorBody();
                    try {

                        if (Objects.requireNonNull(errorBody).string().contains("access_token_expired")) {
                            updateToken();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<MessageArray> call, @NonNull Throwable t) {

            }
        });
    }

    public void updateToken() {


    }


    public void logOut() {

    }


    @Override
    public void onAttach(Context context) {

        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
        this.context = context;
    }


    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

MessageAdapter2类:

public class MessageAdapter2 extends RecyclerView.Adapter<MessageAdapter2.SenderHolder> {
    private List<Message> messageList;
    private Context ctx;
    private static final String keyOutboundMessageId = "outbound_message_id"; // для исходящих

    MessageAdapter2(List<Message> messageList, Context ctx) {
        this.messageList = messageList;
        this.ctx = ctx;
    }

    @NonNull
    @Override
    public SenderHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_of_rec_m, viewGroup, false);
        return new SenderHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull final SenderHolder holder, int position) {
        final Message message = messageList.get(position);

        holder.tvSubject.setText(message.getSubject());
        holder.tvFrom.setText(message.getReceiver_name());
        holder.tvDate.setText(message.getDate());
        holder.tvDate.setText(message.getDate());

        /*boolean attachment = message.isAttachment();
        if (attachment) {
            holder.text.setText("+");
        } else {
            holder.text.setText("-");
        }*/


        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ctx, MessageShow.class);
                intent.putExtra(MessageAdapter.class.getSimpleName() + keyOutboundMessageId, message.getId());
                ctx.startActivity(intent);
            }
        });

        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Toast.makeText(ctx, "Long pressing", Toast.LENGTH_SHORT).show();
                return false;
            }
        });

    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }


    class SenderHolder extends RecyclerView.ViewHolder {

        final TextView tvFrom, tvSubject, tvDate, text;
        //ImageView ivClip;

        SenderHolder(View itemView) {
            super(itemView);
            tvFrom = itemView.findViewById(R.id.tv_from);
            tvSubject = itemView.findViewById(R.id.tv_subject);
            tvDate = itemView.findViewById(R.id.tv_date);
            text = itemView.findViewById(R.id.text);
            //ivClip = itemView.findViewById(R.id.clip);
        }
    }
}

消息模型类:

public class Message {
    @SerializedName("id")
    @Expose
    private int id;
    @SerializedName("subject")
    @Expose
    private String subject;
    @SerializedName("can_delete")
    @Expose
    private boolean can_delete;
    @SerializedName("new") //this is because new is a protected keyword. this annotation is for Gson parsing library. Any library has his own annotation
    private int newField;
    @SerializedName("date")
    @Expose
    private String date;
    @SerializedName("receiver_name")
    @Expose
    private String receiver_name;
    @SerializedName("sender_name")
    @Expose
    private String sender_name;
    @SerializedName("attach")
    @Expose
    private boolean attachment;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getSubject() {
        return subject;
    }

    public boolean isAttachment() {
        return attachment;
    }

    public void setAttachment(boolean attachment) {
        this.attachment = attachment;
    }

    /*public void setSubject(String subject) {
        this.subject = subject;
    }

    public boolean isCan_delete() {
        return can_delete;
    }

    public void setCan_delete(boolean can_delete) {
        this.can_delete = can_delete;
    }

    public int getNewField() {
        return newField;
    }

    public void setNewField(int newField) {
        this.newField = newField;
    }*/

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getReceiver_name() {
        return receiver_name;
    }

   /* public void setReceiver_name(String receiver_name) {
        this.receiver_name = receiver_name;
    }*/

    public String getSender_name() {
        return sender_name;
    }

    /*public void setSender_name(String sender_name) {
        this.sender_name = sender_name;
    }*/
}

发送片段xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/send"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/refresh_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/list_sen"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />


    </android.support.v4.widget.SwipeRefreshLayout>


</android.support.constraint.ConstraintLayout>

回收者视图项目xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingLeft="3dp"
    android:paddingRight="3dp"
    android:paddingTop="8dp">

    <android.support.v7.widget.CardView
        android:id="@+id/cv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/m_list">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/tv_from"
                android:layout_width="wrap_content"
                android:layout_height="20dp"
                android:layout_marginStart="10dp"
                android:gravity="center_horizontal"
                android:textColor="#000"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_date"
                android:layout_width="match_parent"
                android:layout_height="20dp"
                android:layout_marginEnd="5dp"
                android:gravity="end" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginTop="20dp">

            <TextView
                android:id="@+id/tv_subject"
                android:layout_width="wrap_content"
                android:layout_height="20dp"
                android:layout_marginEnd="5dp"
                android:layout_marginStart="10dp"
                android:ellipsize="end"
                android:gravity="center_vertical"
                android:singleLine="true" />

            <!--<ImageView
                android:id="@+id/clip"
                android:layout_width="24dp"
                android:layout_height="24dp"
                android:layout_gravity="end"
                android:contentDescription="TODO" />-->

            <TextView
                android:id="@+id/tv_text"
                android:layout_width="wrap_content"
                android:layout_height="20dp"
                android:layout_marginEnd="5dp"
                android:layout_marginStart="30dp"
                android:ellipsize="end"
                android:gravity="center_vertical"
                android:singleLine="true" />
        </RelativeLayout>
    </android.support.v7.widget.CardView>
</RelativeLayout>

我遇到的问题非常简单-我想使用导航设备驱动程序上的选项卡来翻译我的项目。在选项卡上,所有内容均正常运行-激活所需的选项卡后,将启动片段并发送请求以填充列表。现在,选择菜单项时,我只向收到的消息发送请求,但没有收到任何发送的消息。

更新

我的消息适配器2发送了消息:

public class MessageAdapter2 extends RecyclerView.Adapter<MessageAdapter2.SenderHolder> {
    private List<MessageArray> messageList;
    private Context ctx;
    private static final String keyOutboundMessageId = "outbound_message_id"; // для исходящих

    MessageAdapter2(ArrayList<MessageArray> messageList, Context ctx) {
        this.messageList = messageList;
        this.ctx = ctx;
    }

    @NonNull
    @Override
    public SenderHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_of_rec_m, viewGroup, false);
        return new SenderHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull final SenderHolder holder, int position) {
        final MessageArray message = messageList.get(position);

        holder.tvSubject.setText(message.getSubject());
        holder.tvFrom.setText(message.getReceiver_name());
        holder.tvDate.setText(message.getDate());
        holder.tvDate.setText(message.getDate());

        /*boolean attachment = message.isAttachment();
        if (attachment) {
            holder.text.setText("+");
        } else {
            holder.text.setText("-");
        }*/


        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ctx, MessageShow.class);
                intent.putExtra(MessageAdapter.class.getSimpleName() + keyOutboundMessageId, message.getId());
                ctx.startActivity(intent);
            }
        });

        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Toast.makeText(ctx, "Long pressing", Toast.LENGTH_SHORT).show();
                return false;
            }
        });

    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }


    class SenderHolder extends RecyclerView.ViewHolder {

        final TextView tvFrom, tvSubject, tvDate, text;
        //ImageView ivClip;

        SenderHolder(View itemView) {
            super(itemView);
            tvFrom = itemView.findViewById(R.id.tv_from);
            tvSubject = itemView.findViewById(R.id.tv_subject);
            tvDate = itemView.findViewById(R.id.tv_date);
            text = itemView.findViewById(R.id.text);
            //ivClip = itemView.findViewById(R.id.clip);
        }
    }
}

我发送的片段send()方法:

public void sent() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://00000/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        adapter = null;

        sp = Objects.requireNonNull(context).getSharedPreferences("access_token", 0);


        String a_token = sp.getString("access_token", "");
        APIService mAPIService = retrofit.create(APIService.class);
        mAPIService.getInMess("Bearer " + a_token, 1, 1).enqueue(new Callback<MessageArray>() {
            @Override
            public void onResponse(@NonNull Call<MessageArray> call, @NonNull Response<MessageArray> response) {

                if (response.isSuccessful()) {
                    messageArrayList = (ArrayList<MessageArray>) Objects.requireNonNull(response.body()).getMessages();
                    adapter = new MessageAdapter2(messageArrayList, getActivity());
                    recyclerView.setAdapter(adapter);
                    mSwipeRefreshLayout.setRefreshing(false);


                } else {
                    ResponseBody errorBody = response.errorBody();
                    try {

                        if (Objects.requireNonNull(errorBody).string().contains("access_token_expired")) {
                            updateToken();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<MessageArray> call, @NonNull Throwable t) {

            }
        });
    }

0 个答案:

没有答案