У меня есть мой предыдущий вопрос Почему он не показывает требуемый фрагмент, когда выбрана опция меню ящика навигации Android? , в котором я уже выделил некоторые из моих проблем, но этот вопрос был сформулирован несколько неправильно, поэтому я решил создать новый.
В моем приложении есть два фрагмента, которые выполняют запросы для двух списков сообщений - входящего и исходящего. Код для этих фрагментов можно увидеть ниже:
входящий фрагмент:
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>
Проблема, с которой я столкнулся, довольно проста - я хочу перевести свой проект с помощью вкладок в драйвере навигационного устройства. на вкладках все работало корректно - при активации нужной вкладки запускался фрагмент и отправлялся запрос на заполнение списка. Теперь при выборе пункта меню я только отправляю запрос на полученные сообщения, но не получаю отправленных сообщений.
UPDATE
мой адаптер сообщений 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);
}
}
}
Метод моего отправленного фрагмента sent ():
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) {
}
});
}