从firebasedatabase

时间:2018-05-21 14:42:01

标签: java android firebase firebase-realtime-database

我有一个Firebase实时数据库,我为它增加了价值,然后我想要检索这些值,但它们不会显示在我的屏幕上。

这是有效的旧代码;

    //ChatActivity class

mDatabaseforAllChatMessages.child(mAuth.getCurrentUser().getUid()).child(allChatId).setValue(allChatMessagesGet);
            mDatabaseforAllChatMessages.child(userID).child(allChatId).setValue(allChatMessagesGet);

//AllChatMessages class
 mDatabaseRef.child(mAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener(){
 @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                AllChatMessagesGet allChatMessagesGet = postSnapshot.getValue(AllChatMessagesGet.class);



            }
            allChatMessagesAdapter = new AllChatMessagesAdapter(AllChatMessages.this, allChatMessagesGetList);

            recyclerView.setAdapter(allChatMessagesAdapter);


        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(AllChatMessages.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();

        }});

我现在已将此代码更改为:

//ChatActivity class
 mDatabaseforAllChatMessages.child(mAuth.getCurrentUser().getUid()).child(userID).child(uploadID).child(allChatId).setValue(allChatMessagesGet);
        mDatabaseforAllChatMessages.child(userID).child(mAuth.getCurrentUser().getUid()).child(uploadID).child(allChatId).setValue(allChatMessagesGet);

//AllChatMessages class
 mDatabaseRef.child(mAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                AllChatMessagesGet allChatMessagesGet = postSnapshot.getValue(AllChatMessagesGet.class);


                allChatMessagesGetList.add(allChatMessagesGet);


            }
            allChatMessagesAdapter = new AllChatMessagesAdapter(AllChatMessages.this, allChatMessagesGetList);

            recyclerView.setAdapter(allChatMessagesAdapter);


        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(AllChatMessages.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();

        }
    });

那么为什么我无法从新代码中恢复我的价值呢?我该如何解决?

public class AllChatMessagesAdapter extends RecyclerView.Adapter<AllChatMessagesAdapter.AllChatViewHolder> {

private Context mCtx;
private List<AllChatMessagesGet> ChatActivityList;

public AllChatMessagesAdapter(Context mctx, List<AllChatMessagesGet> chatActivityList){
    this.mCtx = mctx;
    this.ChatActivityList = chatActivityList;
}

@Override
public AllChatViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(mCtx);

    View viewList_allChatMessagesLayout = inflater.inflate(R.layout.allchatmessages_layout_list, parent, false);


    return new AllChatViewHolder(viewList_allChatMessagesLayout);

}

@Override
public void onBindViewHolder(AllChatViewHolder holder, int position) {
    AllChatMessagesGet allChatMessagesGet = ChatActivityList.get(position);

    //from below class and Allchatmessagesget Class.
    holder.textViewTitleOfUpload.setText(allChatMessagesGet.getUploadTitleString());
    holder.textviewTitleOfMessage.setText(allChatMessagesGet.getMessageTextsent());

    Glide.with(mCtx)
            .load(allChatMessagesGet.getUploadImageURL())
            .into(holder.imageView);
    holder.imageView.setRotation(allChatMessagesGet.getUploadImageRotation());

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //create new intent to start another activity
            //add extras
            //startactivity
        }
    });
}


@Override
public int getItemCount() {
    return ChatActivityList.size();
}

public class AllChatViewHolder extends RecyclerView.ViewHolder {
    public ImageView imageView;
    public TextView textViewTitleOfUpload, textviewTitleOfMessage;

    public AllChatViewHolder(View itemView) {
        super(itemView);
        //taken from allchatmessages_layout_list.xml
        imageView = itemView.findViewById(R.id.imageofupload);
        textViewTitleOfUpload = itemView.findViewById(R.id.textViewTitle);
        textviewTitleOfMessage = itemView.findViewById(R.id.textViewmessage);
    }
}
}

我现在已经添加了Adapter类。

这里是完整的代码:请注意我的课程上的评论,因为它们不是正确的评论并将被删除

public class ChatActivity extends AppCompatActivity {

private String titleString, userID, uploadID, imageURL, userOnlineString, userEmail, uniqueID;
private Boolean userOnlineBoolean;
private int imageRotation;
private TextView titleCustomBar, lastSeenCustomBar;
private ImageView imageCustomBar;
private DatabaseReference mDatabaseRefUser, mDatabaseforAllChatMessages;
private FirebaseAuth mAuth;
private EditText addMessageEditText;
private FloatingActionButton sendMessageFab;
private ImageButton addImageToMessageImageButton;
private FirebaseListAdapter<ChatMessage> adapter;
private String allChatId;



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



    //activity_chat.xml
    addImageToMessageImageButton = findViewById(R.id.add_image_id);
    addMessageEditText = findViewById(R.id.add_message_input_id);
    sendMessageFab = findViewById(R.id.send_message_fab_id);




    mAuth = FirebaseAuth.getInstance();
    mDatabaseRefUser = FirebaseDatabase.getInstance().getReference("Users");
    mDatabaseforAllChatMessages = FirebaseDatabase.getInstance().getReference("AllChatMessages");



    //Log.e("Lol", userOnlineString);

    mDatabaseRefUser.child(mAuth.getCurrentUser().getUid()).child("Online").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            userOnlineBoolean = dataSnapshot.getValue(Boolean.class);
            //if(userOnlineBoolean==true){
              //  userOnlineString = "Online";
                //setCustomOnlineOffline();
            //}

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(ChatActivity.this, "some error", Toast.LENGTH_SHORT).show();
        }
    });


    Intent intent = getIntent();
    titleString = intent.getStringExtra("TITLE");
    userID = intent.getStringExtra("USERID");
    uploadID = intent.getStringExtra("UPLOADID");
    imageRotation = intent.getIntExtra("IMAGEROTATION", 0);
    imageURL = intent.getStringExtra("IMAGEURL");
    userEmail = intent.getStringExtra("USEREMAIL");




    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayShowCustomEnabled(true);

    LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
    View customActionBar = layoutInflater.inflate(R.layout.chat_custombar, null);

    actionBar.setCustomView(customActionBar);

    titleCustomBar = findViewById(R.id.title_textview_id);
    lastSeenCustomBar = findViewById(R.id.last_seen_textview_id);
    imageCustomBar = findViewById(R.id.custom_image_id);

    titleCustomBar.setText(titleString);

    //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    Glide.with(this).load(imageURL)
            .into(imageCustomBar);
    imageCustomBar.setRotation(imageRotation);

    //lastSeenCustomBar.setText(userOnlineString);

    /*mDatabaseRefUser.child(mAuth.getCurrentUser().getUid()).child("Chats").child(userID);
    HashMap<String, String> userMap = new HashMap<>();
    userMap.put("name", mAuth.getCurrentUser().getEmail());
    userMap.put("Chat with;", userEmail);
    userMap.put("image", uploadID);*/


    //mDatabaseRefUser.setValue(userMap);

    //uniqueID = mDatabaseRefUser.push().getKey();

    displayChatMessage();


}

private void setCustomOnlineOffline() {
    lastSeenCustomBar.setText(userOnlineString);
}

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

    if(mAuth.getCurrentUser() == null){
        Intent mainActivityIntent = new Intent(this, MainActivity.class);
        startActivity(mainActivityIntent);
        finish();
    }
    else {
        mDatabaseRefUser.child(mAuth.getCurrentUser().getUid()).child("Online").setValue(true);

    }
}


public void sendMessageToAnotherUser(View view) {
    if(addMessageEditText.getText().toString().isEmpty()){
        return;
    }
    else {
        ChatBetweenUsers chatBetweenUsers = new ChatBetweenUsers(mAuth.getCurrentUser().getUid(), userID,
                mAuth.getCurrentUser().getEmail(), userEmail, uploadID);


        ChatBetweenUsers chatBetweenUsers2 = new ChatBetweenUsers(userID, mAuth.getCurrentUser().getUid(),
                userEmail, mAuth.getCurrentUser().getEmail(), uploadID);
        //user email is null! because old uploaded pics had no useremail in constructor. add new pics for change!

        // add .child"messages" after .childuploadID ???
        mDatabaseRefUser.child("Chat").child(mAuth.getCurrentUser().getUid())
                .child(userID).child(uploadID).setValue(chatBetweenUsers);
        mDatabaseRefUser.child("Chat").child(userID)
                .child(mAuth.getCurrentUser().getUid()).child(uploadID).setValue(chatBetweenUsers2);



        //FirebaseDatabase.getInstance().getReference().push().setValue(new ChatMessage(addMessageEditText.getText().toString(),
          //      FirebaseAuth.getInstance().getCurrentUser().getEmail()));



        //This codes overwrites the previous value, maybe because of above code that setValue(chatbetweenUsers),
        // must be without it
       // mDatabaseRefUser.child("Chat").child(mAuth.getCurrentUser().getUid())
               // .child(userID).child(uploadID).child("Messages").push().setValue(new ChatMessage(addMessageEditText.getText().toString(),
              //  mAuth.getCurrentUser().getEmail()));

        //mDatabaseRefUser.child("Chat").child(userID)
          //      .child(mAuth.getCurrentUser().getUid()).child(uploadID).child("Messages").push().setValue(new ChatMessage(addMessageEditText.getText().toString(),
            //    userEmail));

        mDatabaseRefUser.child("Chatting").child(mAuth.getCurrentUser().getUid())
                .child(userID).child(uploadID).child("Messages").push().setValue(new ChatMessage(addMessageEditText.getText().toString(),
                mAuth.getCurrentUser().getEmail()));

        mDatabaseRefUser.child("Chatting").child(userID)
                .child(mAuth.getCurrentUser().getUid()).child(uploadID).child("Messages").push().setValue(new ChatMessage(addMessageEditText.getText().toString(),
                userEmail));




        allChatId = mDatabaseforAllChatMessages.push().getKey();

        AllChatMessagesGet allChatMessagesGet = new AllChatMessagesGet(imageURL, titleString, imageRotation, addMessageEditText.getText().toString(),
                mAuth.getCurrentUser().getEmail(), userEmail);

        mDatabaseforAllChatMessages.child(mAuth.getCurrentUser().getUid()).child(userID).child(uploadID).child(allChatId).setValue(allChatMessagesGet);
        mDatabaseforAllChatMessages.child(userID).child(mAuth.getCurrentUser().getUid()).child(uploadID).child(allChatId).setValue(allChatMessagesGet);

        //kod behövs ej tror jag.
        addMessageEditText.setText("");
    }


}

private void displayChatMessage() {

    ListView listOfMessages = findViewById(R.id.list_of_messages);
    //fix this code so message shows
    adapter = new FirebaseListAdapter<ChatMessage>(this, ChatMessage.class, R.layout.list_item_message,
            FirebaseDatabase.getInstance().getReference().child("Users").child("Chatting").child(mAuth.getCurrentUser().getUid()).child(userID)
    .child(uploadID).child("Messages")) {
        @Override
        protected void populateView(View v, ChatMessage model, int position) {

            TextView messageText, messageUser, messageTime;

            messageText = v.findViewById(R.id.message_text);
            messageUser = v.findViewById(R.id.message_user);
            messageTime = v.findViewById(R.id.message_time);
            model.setMessageTime(new Date().getTime());

            messageText.setText(model.getMessageText());
            messageUser.setText(model.getMessageUser());
            messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));

        }
    };

    listOfMessages.setAdapter(adapter);

}

}

这是AllChatMessages的代码:

public class AllChatMessages extends AppCompatActivity {

private FirebaseAuth mAuth;
private RecyclerView recyclerView;
private AllChatMessagesAdapter allChatMessagesAdapter;
private List<AllChatMessagesGet> allChatMessagesGetList;
private DatabaseReference mDatabaseRef, mDatabaseRefUser;
private boolean online;
private FirebaseListAdapter<AllChatMessagesGet> adapter;

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

    mAuth = FirebaseAuth.getInstance();
    allChatMessagesGetList = new ArrayList<>();
    //from activity_all_chat_messages.xml
    recyclerView = findViewById(R.id.allchatmessages_recycleview_id);
    recyclerView.setHasFixedSize(true);

    Log.e("lol", mAuth.getCurrentUser().getEmail());


    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    mDatabaseRef = FirebaseDatabase.getInstance().getReference("AllChatMessages");
    mDatabaseRefUser = FirebaseDatabase.getInstance().getReference("Users");

    displayAllChatMessages();



}

private void displayAllChatMessages() {

    //To get data out of uploads DataBase
    mDatabaseRef.child(mAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Loop through all files in Uploads DataBase
            for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                AllChatMessagesGet allChatMessagesGet = postSnapshot.getValue(AllChatMessagesGet.class);
                //add if statement and then allChatMessagesGetList.clear when if statements are fulfilled
                //such as same uploadid, same title, and same users from both side, then clear it? or just update the
                //text somehow.
                //allChatMessagesGetList.clear();
                allChatMessagesGetList.add(allChatMessagesGet);
                //filled the uploadImageList with the data from uploadImage from the Uploads DataBase

            }
            allChatMessagesAdapter = new AllChatMessagesAdapter(AllChatMessages.this, allChatMessagesGetList);

            recyclerView.setAdapter(allChatMessagesAdapter);



        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(AllChatMessages.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();

        }
    });
}

}

1 个答案:

答案 0 :(得分:1)

要解决此问题,请在onStart()onStop()方法中添加以下代码行。

@Override
protected void onStart() {
    super.onStart();
    allChatMessagesAdapter.startListening();
}

@Override
protected void onStop() {
    super.onStop();
    if(allChatMessagesAdapter != null) {
            allChatMessagesAdapter.stopListening();
    }
}

为了使其有效,您需要开始倾听变化。