gpt4 book ai didi

java - 在我的应用程序中发送图像消息时遇到困难并遇到错误。短信工作正常

转载 作者:行者123 更新时间:2023-11-29 18:35:46 51 4
gpt4 key购买 nike

在应用程序的聊天功能中,我可以发送和接收文本消息。我正在尝试实现能够发送和接收图像消息的地方,但我遇到了错误。

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());
}
}
}

聊天消息.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;
}
}

消息适配器.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;
}
}

我收到这个错误。

这是错误信息。 致命异常(exception):主要 过程:com.rough.tuber.tuber,PID:3931 java.lang.NullPointerException:尝试在空对象引用上调用接口(interface)方法“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.loop(Looper.java:164) 在 android.app.ActivityThread.main(ActivityThread.java:6494) 在 java.lang.reflect.Method.invoke( native 方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Firebase enter image description here enter image description here

最佳答案

在您的 onCreate() 方法中,您正在调用 mRootRef 上的 valueEventListener,尽管您尚未对其进行初始化。此外,根据您的数据库结构,数据库路径应来自“current_uid”。

不是在 onActivityResult 上初始化 mRootRef,而是在 onCreateMethod() 上初始化它:

.......
@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
........
mRootRef = FirebaseDatabase.getInstance().getReference();
.......
mRootRef.child("Chat").child(current_uid)
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
.........

更新

针对您持续存在的错误进行了更新。

关于java - 在我的应用程序中发送图像消息时遇到困难并遇到错误。短信工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54450874/

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