Невозможно отобразить мгновенное сообщение, полученное или отправленное в разговоре — android

Я создаю функцию обмена мгновенными сообщениями в моем приложении, используя модификацию 2.0, php и mysql. Но я не знаю, как показать и обновить полученные и отправленные сообщения в обзоре переработчика.

Активность разговора

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);

dp=findViewById(R.id.conversationUser);
back=findViewById(R.id.goBackFromCoversation);
name=findViewById(R.id.conversationUserName);
activeStatus=findViewById(R.id.conversationUserSeen);
shareTitle=findViewById(R.id.conversationStatusTitle);
typeMessage=findViewById(R.id.typeMessage);
attach=findViewById(R.id.attachFiles);
send=findViewById(R.id.sendMessage);
recyclerView=findViewById(R.id.conversationRv);
toolbar=findViewById(R.id.converationToolbar);

setSupportActionBar(toolbar);

if (SharedPrefManager.getInstance(this).contains("keyid")) {
id = SharedPrefManager.getInstance(this).getUser().getId();
Toast.makeText(this, "user id is " + id, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "no id found", Toast.LENGTH_SHORT).show();
}

getUserId= getIntent().getIntExtra("userId",0);
getUserName=getIntent().getStringExtra("userName");
getUserDp=getIntent().getStringExtra("dpUrl");
chatType=getIntent().getIntExtra("chatType",0);

if(getUserDp==null){
Toast.makeText(getApplicationContext(),"user dp is null, value is "+getUserDp,Toast.LENGTH_SHORT).show();
}else {
loadDp(getUserDp);
}

name.setText(getUserName);

RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
((LinearLayoutManager) mLayoutManager).setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setNestedScrollingEnabled(true);

fetchConversation(id,getUserId);

cla=new ConversationAdapter(this,conversation);
recyclerView.setAdapter(cla);

back.setOnClickListener(this);
name.setOnClickListener(this);
attach.setOnClickListener(this);
send.setOnClickListener(this);

}

@Override
public void onClick(View view) {
switch (view.getId()){

case R.id.goBackFromCoversation:
finish();
break;
case R.id.conversationUserName:
Intent intent= new Intent(ConversationActivity.this,ViewProfileActivity.class);
intent.putExtra("userId",getUserId);
startActivity(intent);
break;
case R.id.attachFiles:
break;
case R.id.sendMessage:
getTextMessage=typeMessage.getText().toString();
messageType=0;
sendMessage(chatType,id,getUserId,messageType,getTextMessage);
onCreate(null);
break;

}
}

private void fetchConversation(int id, int getUserId) {

Gson gson = new GsonBuilder()
.setLenient()
.create();

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

Retrofit retrofi = new Retrofit.Builder()
.baseUrl("http://192.168.56.110/app2/")
.addConverterFactory(GsonConverterFactory.create(gson))
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.build();
RetrofitApi service = retrofi.create(RetrofitApi.class);
Call<Message> call = service.getMessages(id,getUserId);

/*  Call<Message> call = RetrofitClient
.getmInstance()
.getApi()
.getMessages(id, Integer.parseInt(getUserId));*/

call.enqueue(new Callback<Message>() {
@Override
public void onResponse(Call<Message> call, Response<Message> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Message sr = response.body();
int count=sr.getConversation().toArray().length;
if(sr.getSuccess()==1){
for(int i=0;i<sr.getConversation().toArray().length;i++){

messageId=sr.getConversation().get(i).getMessageId();
fromId=sr.getConversation().get(i).getSenderId();
toId=sr.getConversation().get(i).getReceiverId();
type=sr.getConversation().get(i).getType();
timeSent=sr.getConversation().get(i).getTime_sent();
message=sr.getConversation().get(i).getMessage();
Conversation c=new Conversation(messageId,fromId,toId,type,message,timeSent);
conversation.add(c);
cla.notifyDataSetChanged();
}
}else{
Log.v(TAG,"success is not 1");
}

} else {
Log.v(TAG, "fetchConvo, response is null ");
Toast.makeText(getApplicationContext(), "resposne is null", Toast.LENGTH_SHORT).show();
}
} else {
Log.v(TAG, "fetchConvo, Something went wrong");
Toast.makeText(getApplicationContext(), "Something went wrong- ", Toast.LENGTH_SHORT).show();
}
}

@Override
public void onFailure(Call<Message> call, Throwable t) {
Log.v(TAG, "fetchConvo, response is" + t.getMessage());
Toast.makeText(getApplicationContext(), "Failure, response is- " + t.getMessage(), Toast.LENGTH_LONG).show();
Log.v(TAG, "fetchConvo, Failed, cause is " + t.getCause());
Toast.makeText(getApplicationContext(), "Failed, cause is - " + t.getCause(), Toast.LENGTH_LONG).show();
}
});

}

private void loadDp(String getUserDp) {

String[] parts= getUserDp.split("htdocs");
String newString="http://192.168.56.110"+ parts[1];
Log.e(TAG, newString );

GlideApp.with(this).
load(newString)
.diskCacheStrategy( DiskCacheStrategy.ALL )
.into(dp);

}



private void sendMessage(int chat,int id, int getUserId, int messageType, String getTextMessage) {

Log.v(TAG,"id is"+ id);
Log.v(TAG,"userId is"+ getUserId);
Log.v(TAG,"type is"+ messageType);
Log.v(TAG,"message is"+getTextMessage);

Gson gson = new GsonBuilder()
.setLenient()
.create();

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

Retrofit retrofi = new Retrofit.Builder()
.baseUrl("http://192.168.56.110/app2/")
.addConverterFactory(GsonConverterFactory.create(gson))
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.build();
RetrofitApi service = retrofi.create(RetrofitApi.class);
Call<com.example.user.myapplication.Model.Response> call = service.saveMessages(id,getUserId,getTextMessage,messageType);

/*    Call<com.example.user.myapplication.Model.Response> call = RetrofitClient
.getmInstance()
.getApi()
.saveMessages(id,getUserId,getTextMessage,messageType);*/

call.enqueue(new Callback<com.example.user.myapplication.Model.Response>() {
@Override
public void onResponse(Call<com.example.user.myapplication.Model.Response> call, Response<com.example.user.myapplication.Model.Response> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
com.example.user.myapplication.Model.Response sr = response.body();
if(sr.getSuccess()==1){
Log.v(TAG,"Response is successful");
}
} else {
Log.v(TAG, "saveMessage, response is null ");
Toast.makeText(getApplicationContext(), "resposne is null", Toast.LENGTH_SHORT).show();
}
} else {
Log.v(TAG, "saveMessage, Something went wrong");
Toast.makeText(getApplicationContext(), "Something went wrong- ", Toast.LENGTH_SHORT).show();
}
}

@Override
public void onFailure(Call<com.example.user.myapplication.Model.Response> call, Throwable t) {
Log.v(TAG, "saveMessage, response is" + t.getMessage());
Toast.makeText(getApplicationContext(), "Failure, response is- " + t.getMessage(), Toast.LENGTH_LONG).show();
Log.v(TAG, "saveMessage, Failed, cause is " + t.getCause());
Toast.makeText(getApplicationContext(), "Failed, cause is - " + t.getCause(), Toast.LENGTH_LONG).show();
}
});

}

Адаптер разговора

public class ConversationAdapter extends RecyclerView.Adapter<ConversationAdapter.ViewHolder> {

private static final String TAG = "ChatListAdapter";
private Context context;
private ArrayList<Conversation> conversation= new ArrayList<>();
private int id;

public ConversationAdapter(Context context, ArrayList<Conversation> conversation) {
this.context = context;
this.conversation = conversation;
}



@NonNull
@Override
public ConversationAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_message, viewGroup, false);
ConversationAdapter.ViewHolder viewHolder = new ConversationAdapter.ViewHolder(view);
return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {


if (SharedPrefManager.getInstance(context).contains("keyid")) {
id = SharedPrefManager.getInstance(context).getUser().getId();
Toast.makeText(context, "user id is " + id, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "no id found", Toast.LENGTH_SHORT).show();
}

if(Integer.parseInt(conversation.get(i).getSenderId())==id){
viewHolder.messageSent.setText(conversation.get(i).getMessage());
viewHolder.messaegReceievd.setVisibility(View.GONE);
}else{
viewHolder.messaegReceievd.setText(conversation.get(i).getMessage());
viewHolder.messageSent.setVisibility(View.GONE);
}

if(i==conversation.toArray().length-1) {
viewHolder.messageTime.setText(conversation.get(conversation.toArray().length- 1).getTime_sent());
}else{
viewHolder.messageTime.setVisibility(View.GONE);
}

}

@Override
public int getItemCount() {
return conversation.toArray().length;
}

public class ViewHolder extends RecyclerView.ViewHolder {

BubbleTextView messageSent,messaegReceievd;
TextView messageTime;

public ViewHolder(@NonNull View itemView) {
super(itemView);
Log.v(TAG, "ViewHolder, setting view in variables");

messageSent=itemView.findViewById(R.id.textMessageSent);
messaegReceievd=itemView.findViewById(R.id.textMessageReceived);
messageTime=itemView.findViewById(R.id.messageSentTime);

}
}


}

Всякий раз, когда я отправляю сообщение и пытаюсь перезагрузить действие, чтобы показать полученные сообщения или отправить, я снова запускаю действие и должен снова сделать сетевой запрос, который, я думаю, займет много времени, когда его использует реальный пользователь. Итак, поэтому я хочу реализовать что-то еще, чтобы сделать это мгновенным обменом сообщениями.

Любая помощь будет оценена
заранее спасибо

1

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]