В функции чата приложения я могу отправлять и получать текстовые сообщения.Я пытаюсь реализовать, где я могу отправлять и получать графические сообщения, и у меня возникают ошибки.
StudentChatActivity.java
public class StudentChatActivity extends AppCompatActivity {
private FirebaseListAdapter<ChatMessage> adapter;
private ListView listView;
public static String tutorID = "";
public String tutorName = "";
private String mChatUser;
private FirebaseAuth mAuth;
private DatabaseReference mRootRef;
FirebaseDatabase database;
private MessageAdapter mAdapter;
private static final int TOTAL_ITEMS_TO_LOAD = 10;
private int mCurrentPage = 1;
private static final int GALLERY_PICK = 1;
private FirebaseUser mCurrentUser;
private StorageReference mImageStorage;
private int itemPos = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Intent intt = getIntent();
Bundle b = intt.getExtras();
if (b != null) {
tutorID = (String) b.get("tutorID");
tutorName = (String) b.get("tutorName");
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
listView = (ListView) findViewById(R.id.list);
ImageButton imagebutton = (ImageButton) findViewById(R.id.image_button);
mImageStorage = FirebaseStorage.getInstance().getReference();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = mCurrentUser.getUid();
final EditText input = (EditText) findViewById(R.id.input1);
mRootRef.child("Chat").child(String.valueOf(mCurrentUser)).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/" + mCurrentUser + "/" + mChatUser, chatAddMap);
chatUserMap.put("Chat/" + mChatUser + "/" + mCurrentUser, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null)
Log.d( "Chat_log: ", databaseError.getMessage().toString());
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
showAllOldMessages();
imagebutton.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);
}
});
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (input.getText().toString().trim().equals("")) {
Toast.makeText(StudentChatActivity.this, "Please enter some texts!", Toast.LENGTH_SHORT).show();
} else {
FirebaseDatabase.getInstance()
.getReference()
.push()
.setValue(
new ChatMessage(input.getText().toString(),
StudentHome.info.etFirstname,
FirebaseAuth.getInstance().getCurrentUser().getUid(),
StudentChatActivity.this.tutorName,
StudentChatActivity.this.tutorID,
FirebaseAuth.getInstance().getCurrentUser().getUid()
)
);
input.setText("");
//send notification
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
mRootRef = database.getReference();
// mAuth = FirebaseAuth.getInstance();
final EditText input = (EditText) findViewById(R.id.input1);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){
Uri imageUri = data.getData();
final String current_user_ref = "messages/" + mCurrentUser + "/" + mChatUser;
final String chat_user_ref = "messages/" + mChatUser + "/" + mCurrentUser;
DatabaseReference user_message_push = mRootRef.child("messages").child(String.valueOf(mCurrentUser)).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",mCurrentUser);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref + "/" + push_id,messageMap);
messageUserMap.put(chat_user_ref + "/" + push_id,messageMap);
input.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());
}
});
/* mRootRef.updateChildren(messageUserMap, databaseError, databaseReference){
if (databaseError != null){
Log.d("CHAT_LOG", databaseError.getMessage().toString());
}
}); */
}
}
});
}
}
private void showAllOldMessages() {
try {
adapter = new MessageAdapter(this, ChatMessage.class, R.layout.item_in_message,
FirebaseDatabase.getInstance().getReference());
listView.setAdapter(adapter);
} catch (Exception er) {
System.out.print(er.getMessage());
}
}
}
ChatMessage.Java
package com.rough.tuber.tuber;
import android.media.Image;
import java.util.Date;
public class ChatMessage {
private String messageText;
private String studentName;
private String studentID;
private String tutorName;
private String tutorID;
private String senderId;
private long messageTime;
public ChatMessage(String messageText, String studentName, String studentID, String tutorName, String tutorID, String senderId) {
this.messageText = messageText;
this.studentName = studentName;
this.studentID = studentID;
messageTime = new Date().getTime();
this.tutorID = tutorID;
this.tutorName = tutorName;
this.senderId = senderId;
}
public ChatMessage() {
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getSenderId() {
return senderId;
}
public String getTutorID() {
return tutorID;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public void setTutorID(String tutorID) {
this.tutorID = tutorID;
}
public String getTutorName() {
return tutorName;
}
public void setTutorName(String tutorName) {
this.tutorName = tutorName;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public long getMessageTime() {
return messageTime;
}
public void setMessageTime(long messageTime) {
this.messageTime = messageTime;
}
}
MessageAdapter.Java
package com.rough.tuber.tuber;
import android.text.format.DateFormat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
public class MessageAdapter extends FirebaseListAdapter<ChatMessage> {
private StudentChatActivity activity;
public MessageAdapter(StudentChatActivity activity, Class<ChatMessage> modelClass, int modelLayout, DatabaseReference ref) {
super(activity, modelClass, modelLayout, ref);
this.activity = activity;
}
@Override
protected void populateView(View v, ChatMessage model, int position) {
if (v != null) {
TextView messageText = (TextView) v.findViewById(R.id.message_text);
TextView messageUser = (TextView) v.findViewById(R.id.message_user);
TextView messageTime = (TextView) v.findViewById(R.id.message_time);
// ImageView messagaImage = (ImageView) v.fin
messageText.setText(model.getMessageText());
if (model.getSenderId() != null && model.getSenderId().equals(FirebaseAuth.getInstance().getCurrentUser().getUid())) {
messageUser.setText("You");
} else {
messageUser.setText(model.getTutorName());
}
// Format the date before showing it
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
}
}
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
ChatMessage chatMessage = getItem(position);
if (chatMessage.getTutorID() != null && chatMessage.getStudentID() != null && chatMessage.getSenderId() != null && chatMessage.getStudentID().equals(FirebaseAuth.getInstance().getCurrentUser().getUid()) && chatMessage.getTutorID().equals(StudentChatActivity.tutorID)) {
if (chatMessage.getSenderId() != null && chatMessage.getSenderId().equals(FirebaseAuth.getInstance().getCurrentUser().getUid())
)
view = activity.getLayoutInflater().inflate(R.layout.item_out_message, viewGroup, false);
else
view = activity.getLayoutInflater().inflate(R.layout.item_in_message, viewGroup, false);
//generating view
populateView(view, chatMessage, position);
return view;
}
view = activity.getLayoutInflater().inflate(R.layout.item_empty, viewGroup, false);
return view;
}
@Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
@Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
}
Я получаю эту ошибку.
Это сообщение об ошибке.ИСКЛЮЧИТЕЛЬНОЕ ИСКЛЮЧЕНИЕ: main Процесс: com.rough.tuber.tuber, PID: 3931 java.lang.NullPointerException: Попытка вызвать метод интерфейса int java.lang.CharSequence.length () для нулевой ссылки на объект в java.util.regex.Matcher.reset (Matcher.java:1052) в java.util.regex.Matcher. (Matcher.java:180) в java.util.regex.Pattern.matcher (Pattern.java:1006) в com.google.android.gms.internal.zzelv.zzqh (неизвестный источник: 2) на com.google.firebase.database.DataSnapshot.hasChild (неизвестный источник: 12) на com.rough.tuber.tuber.StudentChatActivity $ 1.onDataChange (StudentChatActivity.java): 92) на com.google.android.gms.internal.zzegf.zza (неизвестный источник: 13) на com.google.android.gms.internal.zzeia.zzbyc (неизвестный источник: 2) на com.google.android.gms.internal.zzeig.run (неизвестный источник: 71) на android.os.Handler.handleCallback (Handler.java:790) на android.os.Handler.dispatchMessage (Handler.java:99) на android.os.Looper.цикл (Looper.java:164) на android.app.ActivityThread.main (ActivityThread.java:6494) на java.lang.reflect.Method.invoke (собственный метод) в com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run (RuntimeInit.java:438) в com.android.internal.os.ZygoteInit.main (ZygoteInit.java:807)
Firebase введите описание изображения здесь введите описание изображения здесь