我正在开发android中的聊天应用程序,并使用firebase为我的聊天活动的代码在下面给出
public class Chat extends CustomActivity {
/**
* The Conversation list.
*/
private ArrayList<Conversation> convList;
/**
* The chat adapter.
*/
private ChatAdapter adp;
/**
* The Editext to compose the message.
*/
private EditText txt;
/**
* The user name of buddy.
*/
private ChatUser buddy;
/**
* The date of last message in conversation.
*/
private Date lastMsgDate;
/* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
convList = new ArrayList<Conversation>();
ListView list = (ListView) findViewById(R.id.list);
adp = new ChatAdapter();
list.setAdapter(adp);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
list.setStackFromBottom(true);
txt = (EditText) findViewById(R.id.txt);
txt.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_FLAG_MULTI_LINE);
setTouchNClick(R.id.btnSend);
buddy = (ChatUser) getIntent().getSerializableExtra(Const.EXTRA_DATA);
ActionBar actionBar = getActionBar();
if(actionBar != null)
actionBar.setTitle(buddy.getUsername());
FirebaseDatabase.getInstance().getReference("messages").orderByChild("receiver").endAt(FirebaseAuth.getInstance().getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
//convList=new ArrayList<Conversation>();
for (DataSnapshot ds : dataSnapshot.getChildren() ) {
Conversation conversation = ds.getValue(Conversation.class);
if (conversation.getReceiver().contentEquals(user.getUid()) || conversation.getSender().contentEquals(user.getUid())) {
// if(!convList.contains(conversation)) {
convList.add(conversation);
if (lastMsgDate == null
|| lastMsgDate.before(conversation.getDate()))
lastMsgDate = conversation.getDate();
adp.notifyDataSetChanged();
}
// }
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
/* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
loadConversationList();
}
/* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
}
/* (non-Javadoc)
* @see com.socialshare.custom.CustomFragment#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
super.onClick(v);
if (v.getId() == R.id.btnSend) {
sendMessage();
}
}
/**
* Call this method to Send message to opponent. It does nothing if the text
* is empty otherwise it creates a Parse object for Chat message and send it
* to Parse server.
*/
private void sendMessage() {
if (txt.length() == 0)
return;
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txt.getWindowToken(), 0);
String s = txt.getText().toString();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
final Conversation conversation = new Conversation(s,
Calendar.getInstance().getTime(),
user.getUid(),
buddy.getId(),
"");
conversation.setStatus(Conversation.STATUS_SENDING);
convList.add(conversation);
final String key = FirebaseDatabase.getInstance()
.getReference("messages")
.push().getKey();
//Experiment By Pratap
/* FirebaseDatabase.getInstance().getReference("messages").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
Conversation conversation = dataSnapshot.getValue(Conversation.class);
if (conversation.getReceiver().contentEquals(user.getUid()) || conversation.getSender().contentEquals(user.getUid())) {
convList.add(conversation);
if (lastMsgDate == null
|| lastMsgDate.before(conversation.getDate()))
lastMsgDate = conversation.getDate();
adp.notifyDataSetChanged();
}
}
}
@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) {
}
});*/
//
FirebaseDatabase.getInstance().getReference("messages").child(key)
.setValue(conversation)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
convList.get(convList.indexOf(conversation)).setStatus(Conversation.STATUS_SENT);
} else {
convList.get(convList.indexOf(conversation)).setStatus(Conversation.STATUS_FAILED);
}
FirebaseDatabase.getInstance()
.getReference("messages")
.child(key).setValue(convList.get(convList.indexOf(conversation)))
.addOnCompleteListener(new
OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
adp.notifyDataSetChanged();
}
});
}
}
);
}
adp.notifyDataSetChanged();
txt.setText(null);
}
/**
* Load the conversation list from Parse server and save the date of last
* message that will be used to load only recent new messages
*/
private void loadConversationList() {
FirebaseDatabase.getInstance().getReference("messages").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Conversation conversation = ds.getValue(Conversation.class);
if (conversation.getReceiver().contentEquals(user.getUid()) || conversation.getSender().contentEquals(user.getUid())) {
// if(!convList.contains(conversation)) {
convList.add(conversation);
if (lastMsgDate == null
|| lastMsgDate.before(conversation.getDate()))
lastMsgDate = conversation.getDate();
adp.notifyDataSetChanged();
}
// }
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
/**
* The Class ChatAdapter is the adapter class for Chat ListView. This
* adapter shows the Sent or Receieved Chat message in each list item.
*/
private class ChatAdapter extends BaseAdapter {
/* (non-Javadoc)
* @see android.widget.Adapter#getCount()
*/
@Override
public int getCount() {
return convList.size();
}
/* (non-Javadoc)
* @see android.widget.Adapter#getItem(int)
*/
@Override
public Conversation getItem(int arg0) {
return convList.get(arg0);
}
/* (non-Javadoc)
* @see android.widget.Adapter#getItemId(int)
*/
@Override
public long getItemId(int arg0) {
return arg0;
}
/* (non-Javadoc)
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@SuppressLint("InflateParams")
@Override
public View getView(int pos, View v, ViewGroup arg2) {
Conversation c = getItem(pos);
if (c.isSent())
v = getLayoutInflater().inflate(R.layout.chat_item_sent, null);
else
v = getLayoutInflater().inflate(R.layout.chat_item_rcv, null);
TextView lbl = (TextView) v.findViewById(R.id.lbl1);
lbl.setText(DateUtils.getRelativeDateTimeString(Chat.this, c
.getDate().getTime(), DateUtils.SECOND_IN_MILLIS,
DateUtils.DAY_IN_MILLIS, 0));
lbl = (TextView) v.findViewById(R.id.lbl2);
lbl.setText(c.getMsg());
lbl = (TextView) v.findViewById(R.id.lbl3);
if (c.isSent()) {
if (c.getStatus() == Conversation.STATUS_SENT)
lbl.setText(R.string.delivered_text);
else {
if (c.getStatus() == Conversation.STATUS_SENDING)
lbl.setText(R.string.sending_text);
else {
lbl.setText(R.string.failed_text);
}
}
} else
lbl.setText("");
return v;
}
}
/* (non-Javadoc)
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
我只想在用户发送或接收消息时加载单个消息,任何人都可以帮助我这个我在数据库设计方面的弱点这里是我的json数据库结构在数据库中是否有任何错误?或代码请建议我
{
"messages": {
"-KJNARNlP47TwU1tTPrd": {
"date": {
"date": 3,
"day": 5,
"hours": 17,
"minutes": 31,
"month": 5,
"seconds": 45,
"time": 1464989505080,
"timezoneOffset": 240,
"year": 116
},
"msg": "Hey Joe",
"photoUrl": "",
"receiver": "Uhph7zwnAyQnSqHnw0uWbHI6zpv1",
"sender": "P4hJs5t9BaN6QsFYcGLRw6B5a7P2",
"sent": false,
"status": 1
},
"-KJNCItxjYmAh5XNTLGP": {
"date": {
"date": 3,
"day": 5,
"hours": 17,
"minutes": 39,
"month": 5,
"seconds": 54,
"time": 1464989994581,
"timezoneOffset": 240,
"year": 116
},
"msg": "How are you guys doing",
"photoUrl": "",
"receiver": "Uhph7zwnAyQnSqHnw0uWbHI6zpv1",
"sender": "P4hJs5t9BaN6QsFYcGLRw6B5a7P2",
"sent": true,
"status": 1
},
"-KJNCYPfBfCI5PiqQ4ZX": {
"date": {
"date": 3,
"day": 5,
"hours": 17,
"minutes": 40,
"month": 5,
"seconds": 58,
"time": 1464990058115,
"timezoneOffset": 240,
"year": 116
},
"msg": "OK seems your busy catch you later",
"photoUrl": "",
"receiver": "Uhph7zwnAyQnSqHnw0uWbHI6zpv1",
"sender": "P4hJs5t9BaN6QsFYcGLRw6B5a7P2",
"sent": true,
"status": 1
},
"-KJNDuBgl4eGHzz7jG_U": {
"date": {
"date": 3,
"day": 5,
"hours": 17,
"minutes": 46,
"month": 5,
"seconds": 53,
"time": 1464990413564,
"timezoneOffset": 240,
"year": 116
},
"msg": "Checking back in",
"photoUrl": "",
"receiver": "Uhph7zwnAyQnSqHnw0uWbHI6zpv1",
"sender": "P4hJs5t9BaN6QsFYcGLRw6B5a7P2",
"sent": true,
"status": 1
},
"-KJNEDgwYsIX7I0EGWbM": {
"date": {
"date": 3,
"day": 5,
"hours": 17,
"minutes": 48,
"month": 5,
"seconds": 17,
"time": 1464990497565,
"timezoneOffset": 240,
"year": 116
},
"msg": "Apologies was away for a while",
"photoUrl": "",
"receiver": "P4hJs5t9BaN6QsFYcGLRw6B5a7P2",
"sender": "Uhph7zwnAyQnSqHnw0uWbHI6zpv1",
"sent": true,
"status": 1
},
"-KNcnTK_pg_s2MOOZ8W1": {
"date": {
"date": 26,
"day": 2,
"hours": 16,
"minutes": 3,
"month": 6,
"seconds": 19,
"time": 1469563399536,
"timezoneOffset": 240,
"year": 116
},
"msg": "hey",
"photoUrl": "",
"receiver": "Uhph7zwnAyQnSqHnw0uWbHI6zpv1",
"sender": "P4hJs5t9BaN6QsFYcGLRw6B5a7P2",
"sent": true,
"status": 1
}
},
"users": {
"P4hJs5t9BaN6QsFYcGLRw6B5a7P2": {
"email": "demo@myapptemplates.com",
"id": "P4hJs5t9BaN6QsFYcGLRw6B5a7P2",
"online": true,
"room": ["home"],
"username": "Joe Soap"
},
"Uhph7zwnAyQnSqHnw0uWbHI6zpv1": {
"email": "demo1@myapptemplates.com",
"id": "Uhph7zwnAyQnSqHnw0uWbHI6zpv1",
"online": true,
"room": ["home"],
"username": "Busy Bee"
}
}