gpt4 book ai didi

java - 自动刷新不起作用,因为我希望它起作用

转载 作者:行者123 更新时间:2023-12-02 02:20:47 25 4
gpt4 key购买 nike

我有一个名为 ChatActivity 的 Activity ,用户将在其中互相发送消息。该 Activity 在消息发送时检索消息,但当消息显示在此处时,会显示每条消息的重复项。

enter image description here

我确实有自动刷新功能,但它没有按照我希望的方式刷新。在我的 Activity 中也有滑动刷新,当我滑动时它会正确刷新。这是使用滑动刷新时的快照:

enter image description here

如何让自动刷新显示我的消息,就像我滑动刷新时那样?这是我的代码:

public class ChatActivity extends AppCompatActivity {


private Toolbar mChatToolbar; //used
private String mChatUser; //used
private String mthumb_image;
private String userName;
private String mCurrentUserId;
private TextView mUserStatus;
private EditText mChatMessageView;

private CircleImageView mProfileImage;
private FirebaseAuth mAuth;
private ImageButton mChatAddBtn;

private DatabaseReference mRootRef;
// Storage Firebase
private StorageReference mImageStorage;
private static final int GALLERY_PICK = 1;

private RecyclerView mMessagesList;
private SwipeRefreshLayout mRefreshLayout;

private ArrayList<Messages> arrayList_Messages = new ArrayList<>();

private MessageAdapter mAdapter;

private static final int TOTAL_ITEMS_TO_LOAD = 10;
private int mCurrentPage = 1;

private final Handler handler = new Handler();








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


mChatMessageView = (EditText) findViewById(R.id.chat_message_view);
mChatAddBtn = (ImageButton) findViewById(R.id.chat_add_btn);

mChatToolbar = (Toolbar) findViewById(R.id.chat_app_bar);
setSupportActionBar(mChatToolbar);

ActionBar actionBar = getSupportActionBar();

actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);

//for Custom Action bar
actionBar.setDisplayShowCustomEnabled(true);

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View customBar = inflater.inflate(R.layout.chat_custom_bar,null);

actionBar.setCustomView(customBar);

//getting intent Data
gettingIntentData();

// initializing user view
intCustomBarViewAndSetData();

doTheAutoRefresh();


mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();



//------- IMAGE STORAGE ---------
mImageStorage = FirebaseStorage.getInstance().getReference();

mRootRef.child("Chat").child(mCurrentUserId).child(mChatUser).child("seen").setValue(true);


LoadMessages();

//getting information about user online or offline and thumb image
mRootRef.child("Users").child(mChatUser).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();
Picasso.with(ChatActivity.this).load(thumb_image).placeholder(R.drawable.my_profile).into(mProfileImage);

String lastSeen = dataSnapshot.child("online").getValue().toString();

if(lastSeen.equals("true")){
mUserStatus.setText("Online");
}
else{

//converting string into long
Long lastTime = Long.parseLong(lastSeen);

// creating an instance of GetTimeAgo class
GetTimeAgo getTimeAgo = new GetTimeAgo();
String lastSeenTime = GetTimeAgo.getTimeAgo(lastTime,getApplicationContext());
mUserStatus.setText(lastSeenTime);
}
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});


//for creating chat object
mRootRef.child("Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

if(!dataSnapshot.hasChild(mChatUser)){

Map chatAddMap = new HashMap();
chatAddMap.put("seen",false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);

Map chatUserMap = new HashMap();
chatUserMap.put("Chat/"+mCurrentUserId+"/"+mChatUser, chatAddMap);
chatUserMap.put("Chat/"+mChatUser+"/"+mCurrentUserId, chatAddMap);

mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

if(databaseError!= null){
Toast.makeText(ChatActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();

}
}
});
}
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});


// Retrieving the chat messages into recyclerview
LoadMessages();
mRefreshLayout.setRefreshing(true);
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {

mCurrentPage++;

//onRefresh remove the current messages from arraylist and load new messages
arrayList_Messages.clear();

// Load message
LoadMessages();


}
});


}

private void doTheAutoRefresh()
{
handler.postDelayed(new Runnable() {
@Override
public void run()
{
LoadMessages();
// Write code for your refresh logic
doTheAutoRefresh();
}
}, 5000);
}

// Load all messages from database into recyclerView
private void LoadMessages() {

DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);

//Query to load message per page i.e. 10
/*
per page load 10 message and onRefresh mCurrentpage is increment by 1
page 1 => load 10 messages (mCurrentPage = 1 then 1*10 =10)
page 2 => load 20 messages (mCurrentPage = 2 then 2*10 =20) and so on
*/

Query messageQuery = messageRef.limitToLast(mCurrentPage * TOTAL_ITEMS_TO_LOAD);

messageQuery.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {

Messages messages = dataSnapshot.getValue(Messages.class);
arrayList_Messages.add(messages);
mRefreshLayout.setRefreshing(true);
mAdapter.notifyDataSetChanged();

mMessagesList.scrollToPosition(arrayList_Messages.size()-1);

//when data load completely set refreshing
mRefreshLayout.setRefreshing(false);
}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});
}


// send button
public void chatSendButton(View view){

sendMessage();
}

//sending a message
private void sendMessage() {

String message = mChatMessageView.getText().toString().trim();

if(!TextUtils.isEmpty(message)){

mChatMessageView.setText("");
String current_user_ref="messages/"+mCurrentUserId+"/"+mChatUser;
String chat_user_ref= "messages/"+mChatUser+"/"+mCurrentUserId;

DatabaseReference chat_push_key = mRootRef.child("messages").child(mCurrentUserId).
child(mChatUser).push();

String push_key = chat_push_key.getKey();

Map messageMap = new HashMap();
messageMap.put("message",message);
messageMap.put("type","text");
messageMap.put("from",mCurrentUserId);
messageMap.put("seen",false);
messageMap.put("time", ServerValue.TIMESTAMP);

Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref+ "/"+push_key,messageMap);
messageUserMap.put(chat_user_ref+ "/"+push_key,messageMap);

mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

if(databaseError!=null){
Log.d("TAG",databaseError.getMessage().toString());
}
}
});
}
}

//add button
public void chatAddButton(View view){
mChatAddBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
}
});


}

@Override
protected void onResume() {
super.onResume();


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){

Uri imageUri = data.getData();

final String current_user_ref = "messages/" + mCurrentUserId + "/" + mChatUser;
final String chat_user_ref = "messages/" + mChatUser + "/" + mCurrentUserId;

DatabaseReference user_message_push = mRootRef.child("messages")
.child(mCurrentUserId).child(mChatUser).push();

final String push_id = user_message_push.getKey();


StorageReference filepath = mImageStorage.child("message_images").child( push_id + ".jpg");

filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

if(task.isSuccessful()){

String download_url = task.getResult().getDownloadUrl().toString();


Map messageMap = new HashMap();
messageMap.put("message", download_url);
messageMap.put("seen", false);
messageMap.put("type", "image");
messageMap.put("time", ServerValue.TIMESTAMP);
messageMap.put("from", mCurrentUserId);

Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref + "/" + push_id, messageMap);
messageUserMap.put(chat_user_ref + "/" + push_id, messageMap);

mChatMessageView.setText("");

mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

if(databaseError != null){

Log.d("CHAT_LOG", databaseError.getMessage().toString());

}

}
});


}

}
});

}

}


private void intCustomBarViewAndSetData() {
TextView mTitleView = (TextView) findViewById(R.id.custom_bar_title);
mUserStatus = (TextView) findViewById(R.id.custom_bar_seen);
mProfileImage = (CircleImageView) findViewById(R.id.custom_bar_image);
mMessagesList = (RecyclerView) findViewById(R.id.messages_list);

mMessagesList.setLayoutManager(new LinearLayoutManager(this));
mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.message_swipe_layout);
mMessagesList.setHasFixedSize(true);

mAdapter = new MessageAdapter(this, arrayList_Messages);
mMessagesList.setAdapter(mAdapter);

//showing name on toolbar
mTitleView.setText(userName);
mTitleView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent profileIntent = new Intent(ChatActivity.this, ProfileActivity.class);
profileIntent.putExtra("user_id", mChatUser);
startActivity(profileIntent);
}
});




}

private void gettingIntentData() {
Intent intent =getIntent();
userName = intent.getStringExtra("Username");
mChatUser = intent.getStringExtra("user_id");
}
}

最佳答案

doTheAutoRefresh() 中加载之前清除列表。

arrayList_Messages.clear();
LoadMessages();

关于java - 自动刷新不起作用,因为我希望它起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48534604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com