I am trying to display the messages received in the firebase database to the desired user.
The text, user1 sends is displayed properly on his device, but not in user2 device even though, the message reaches the firebase database. This is the main problem.
I am using the following code to check for new messages:
private void checkMessage(){
final DatabaseReference rRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference uRef = rRef.child("users");
final DatabaseReference mRef = uRef.child(toUid);
final DatabaseReference kRef = mRef.child("rec_msg");
kRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if(mAuth.getCurrentUser().getUid().equals(toUid)) {
Map map = (Map) dataSnapshot.getValue();
assert map != null;
String message = map.get("rec_msg").toString();
addMessageBox(message, 2);
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if(mAuth.getCurrentUser().getUid().equals(toUid)) {
Map map = (Map) dataSnapshot.getValue();
assert map != null;
String message = map.get("rec_msg").toString();
addMessageBox(message, 2);
}
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.i("Error", databaseError.getDetails());
}
});
The code that prints the box and shows the text on the screen is like:
private void addMessageBox(String message, int type){
TextView tv = new TextView(Main5Activity.this);
tv.setText(message);
tv.setPadding(20, 30, 30, 20);
tv.setTextSize(1, (float) 20.1);
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp2.weight = 1.0f;
if (type == 1) {
lp2.gravity = Gravity.END;
tv.setBackgroundResource(R.drawable.rounded_rectangle_grey);
} else {
lp2.gravity = Gravity.START;
tv.setBackgroundResource(R.drawable.rounded_rectangle_violet);
}
tv.setLayoutParams(lp2);
layout.addView(tv);
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
The send button code works as following:
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String meText = message.getText().toString();
if (!meText.equals("")) {
addMessageBox(meText, 1);
storeToUID(toUid, fromUid);
sendMessage(message.getText().toString(), toUid);
checkMessage();
}
message.setText("");
}
});
The database looks something like this:
The 'sendMessage()' and 'storeToUID()' just store the values on the firebase database.
Also, the 'checkMessage()' when not added inside the send button's listener code, crashes the app.
Where and how should I place the checkMessage() code so that the app works as it should?
Related
I am showing Firebase data in a RecyclerView and it is working fine.
I have also implemented a SwipeRefreshLayout and when user swipe it, it is getting latest data from Firebase. But whenever I swipe it more than once, it is showing duplicate values although I am clearing the ArrayList and also I am using `swipeRefresh.setEnabled(true)``
Here I am implementing SwipeRefreshLayout:
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getData();
if (swipeRefresh.isEnabled())
swipeRefresh.setEnabled(false);
}
});
Here is my getData() function:
public void getData() {
pd.setTitle("Loading Data");
pd.setMessage("Please Wait...");
pd.setCancelable(false);
pd.show();
infoList = new ArrayList<>();
distributorList = new ArrayList<>();
infoList.clear();
distributorList.clear();
countChilds = 0;
counter = 0;
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference hotelRef = rootRef.child("Orders");
hotelRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
final String key = String.valueOf(dataSnapshot.getKey());
final String hotelName = String.valueOf(dataSnapshot.child("hotelName").getValue());
final String location = String.valueOf(dataSnapshot.child("location").getValue());
final String quantity = String.valueOf(dataSnapshot.child("quantity").getValue());
final String time = String.valueOf(dataSnapshot.child("time").getValue());
final DatabaseReference progressRef = rootRef.child("Progress").child(key);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
shipment = String.valueOf(dataSnapshot.child("shipment").getValue());
firstMile = String.valueOf(dataSnapshot.child("firstMile").getValue());
distributor = String.valueOf(dataSnapshot.child("distributor").getValue());
}
if (shipment.equals("1") && firstMile.equals("2") && !distributor.equals("2")) {
counter++;
Information information = new Information(key, hotelName, location, quantity, time);
infoList.add(information);
distributorList.add(distributor);
try {
adapter = new DistributorItemAdapter(infoList, distributorList, getContext(), DistributorListFragment.this);
recyclerView.setAdapter(adapter);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
} catch (NullPointerException e) {
Toast.makeText(getContext(), "No more Orders", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else {
shipment = "";
distributor = "";
firstMile = "";
}
if (counter == 0) {
emptyView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(null);
} else
emptyView.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Database Error", databaseError.getMessage());
}
};
progressRef.addListenerForSingleValueEvent(eventListener);
countChilds++;
if (countChilds >= dataSnapshot.getChildrenCount()) {
if (pd.isShowing())
pd.dismiss();
if (!swipeRefresh.isEnabled())
swipeRefresh.setEnabled(true);
swipeRefresh.setRefreshing(false);
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
You should initialize your adapter where you initialize your recylerview and set adapter to recylcerView like the following.
//recyclerView = findViewById.....
infoList = new ArrayList<>();
distributorList = new ArrayList<>();
adapter = new DistributorItemAdapter(infoList, distributorList, getContext(), DistributorListFragment.this);
recyclerView.setAdapter(adapter);
Now modify your getData() like below.
public void getData() {
pd.setTitle("Loading Data");
pd.setMessage("Please Wait...");
pd.setCancelable(false);
pd.show();
infoList.clear();
distributorList.clear();
countChilds = 0;
counter = 0;
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference hotelRef = rootRef.child("Orders");
hotelRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
final String key = String.valueOf(dataSnapshot.getKey());
final String hotelName = String.valueOf(dataSnapshot.child("hotelName").getValue());
final String location = String.valueOf(dataSnapshot.child("location").getValue());
final String quantity = String.valueOf(dataSnapshot.child("quantity").getValue());
final String time = String.valueOf(dataSnapshot.child("time").getValue());
final DatabaseReference progressRef = rootRef.child("Progress").child(key);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
shipment = String.valueOf(dataSnapshot.child("shipment").getValue());
firstMile = String.valueOf(dataSnapshot.child("firstMile").getValue());
distributor = String.valueOf(dataSnapshot.child("distributor").getValue());
}
if (shipment.equals("1") && firstMile.equals("2") && !distributor.equals("2")) {
counter++;
Information information = new Information(key, hotelName, location, quantity, time);
infoList.add(information);
distributorList.add(distributor);
// notify your adapter that data set is changed
adapter.notifyDatasetChanged();
} else {
shipment = "";
distributor = "";
firstMile = "";
}
if (counter == 0) {
emptyView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(null);
} else
emptyView.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Database Error", databaseError.getMessage());
}
};
progressRef.addListenerForSingleValueEvent(eventListener);
countChilds++;
if (countChilds >= dataSnapshot.getChildrenCount()) {
if (pd.isShowing())
pd.dismiss();
if (!swipeRefresh.isEnabled())
swipeRefresh.setEnabled(true);
swipeRefresh.setRefreshing(false);
}
}
//....
});
}
I am using firebase database to retrieve user data into my android studio application. I am looking to sum all of the numbers under the child ("BlueCount") together to get an all time total. I am having trouble retrieving all the "BlueCount" data from each different date.
I am trying to add all the underlined "BlueCount" values together.
I have tried this but i can only retrieve data from the current date...
private TextView blueValue;
private TextView redValue;
private TextView greenValue;
private TextView yellowValue;
private ArrayList<Integer> blist = new ArrayList<>();
private ArrayList<Integer> rlist = new ArrayList<>();
private ArrayList<Integer> glist = new ArrayList<>();
private ArrayList<Integer> ylist = new ArrayList<>();
private ArrayList<Integer> bblist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dataview);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
blueValue = (TextView)findViewById(R.id.blueValue);
redValue = (TextView)findViewById(R.id.redValue);
greenValue = (TextView)findViewById(R.id.greenValue);
yellowValue = (TextView)findViewById(R.id.yellowValue);
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null){
return;
}
final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
final Date date = new Date();
String userID = user.getUid();
String strDate = dateFormat.format(date);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = database.getReference();
databaseReference.child("users")
.child(userID)
.child(strDate)
.child("BlueCount").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
int num = 0;
String holder = String.valueOf(dataSnapshot.getValue());
num += Integer.parseInt(holder.trim());
blist.add(num);
int sum = 0;
for (int counter=0;counter<blist.size();counter++){
sum+= blist.get(counter);
}
blueValue.setText(" "+sum);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Firebase can only load complete nodes, or nodes that can be queries. So you'll have to load all data, and then loop over each level to determine the totals.
Something like this should do the trick:
DatabaseReference databaseReference = database.getReference();
DatabaseReference userReference = databaseReference.child("users").child(userID);
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long totalBlueCount = 0;
for (DataSnapshot yearSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot monthSnapshot: yearSnapshot.getChildren()) {
for (DataSnapshot daySnapshot: monthSnapshot.getChildren()) {
DataSnapshot blueSnapshot = daySnapshot.child("BlueCount");
long dayBlueCount = 0;
for (DataSnapshot daySnapshot: monthSnapshot.getChildren()) {
long count = Long.parseLong(daySnapshot.getValue(String.class));
dayBlueCount += count;
}
System.out.println(yearSnapshot.getKey()+"-"+monthSnapshot.getKey()+"-"+daySnapshot.getKey()+": blue count = "+dayBlueCount);
totalBlueCount += dayBlueCount;
}
}
}
System.out.println("Total blue count = "+totalBlueCount);
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
I would consider if the hierarchy really helps you here, as the code would be a lot simpler if each day was just at the same level under a user "2019-07-16", "2019-07-17", etc.
I have a chat application which is implemented using Firebase Realtime database entities only. No specific messaging components.
I'm adding a listener for the chat entity (or table) where the messages are stored. The listener is added by addChildEventListener which should call the onChildAdded method to bring all the children from chat entity in the moment it's attached and whenever a message is added.
The problem is that when I create the table, send the first message and attach the listener, I can see the table and message being created on the Firebase console, but the onChildAdded method is not called but a lot of time later. Then, as soon as it is called, sometimes more than 5 minutes later, I'm able to send and receive the messages as expected.
What could be causing this long delay?
I already tried to set the listener right after creating the table it listens to, but didn't work.
Creating the chat entity (table)
final DatabaseReference chat = dbReference.child("chat");
final DatabaseReference user = dbReference.child("user");
chatId = chat.push().getKey();
Log.d("mymessages", "createChat(), chatId = " + chatId);
HashMap newChatMap = new HashMap();
newChatMap.put("id", chatId);
newChatMap.put("users/" + currentUserId, true);
newChatMap.put("users/" + userId, true);
// Creating chats table
chat.child(chatId)
.child("info")
.updateChildren(newChatMap);
Log.d("mymessages", "Chat table created.");
Creating the message and inserting it in the chat entity
DatabaseReference newMessageDb = dbReference.child("chat").child(chatId).push();
Log.d("mymessages", "message created.");
Map newMessageMap = new HashMap<>();
newMessageMap.put("text", editTextMessage);
newMessageMap.put("creator", currentUserId);
newMessageDb.updateChildren(newMessageMap);
Log.d("mymessages", "message's text and creator added.");
Adding the listener
dbReference.child("chat").child(chatId).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists()) {
\\Fetch the messages...
} else {
Log.d("mymessages", "fetchChatMessages(), dataSnapshot does not exists.");
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Entire code that runs inside the button that sends the message
String editTextMessage = messageBodyEditText.getText().toString();
if (!editTextMessage.isEmpty()) {
if (!chatExists) {
final DatabaseReference chat = dbReference.child("chat");
final DatabaseReference user = dbReference.child("user");
chatId = chat.push().getKey();
HashMap newChatMap = new HashMap();
newChatMap.put("id", chatId);
newChatMap.put("users/" + currentUserId, true);
newChatMap.put("users/" + userId, true);
// Creating chats table
chat.child(chatId)
.child("info")
.updateChildren(newChatMap);
//Inserting the contact's id in the current user's chat table
HashMap newUserChatMap = new HashMap();
newUserChatMap.put(chatId + "/contact", userId);
user.child(currentUserId)
.child("chat")
.updateChildren(newUserChatMap);
//Inserting the current user's id in the contact's chat table
HashMap newContactChatMap = new HashMap();
newContactChatMap.put(chatId + "/contact", currentUserId);
user.child(userId)
.child("chat")
.updateChildren(newContactChatMap);
chatExists = true;
newChatCreated = true;
}
if (chatId != null) {
DatabaseReference newMessageDb = dbReference.child("chat").child(chatId).push();
Map newMessageMap = new HashMap<>();
newMessageMap.put("text", editTextMessage);
newMessageMap.put("creator", currentUserId);
newMessageDb.updateChildren(newMessageMap);
messageBodyEditText.setText("");
if (messageList.isEmpty()) {
if (chatExists) {
if (ConnectivityHelper.isConnectedToNetwork(this)) {
dbReference.child("chat").child(chatId).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
loadingMessages.setVisibility(View.VISIBLE);
loadingWarning.setVisibility(View.VISIBLE);
loadingWarning.setText("Loading messages...");
if (dataSnapshot.exists() && !dataSnapshot.getKey().equals("info")) {
loadingWarning.setText("Loading messages...");
String text = "";
String creatorId = "";
Object newText = dataSnapshot.child("text").getValue();
Object newCreatorId = dataSnapshot.child("creator").getValue();
if (newText != null) {
text = newText.toString();
}
if (newCreatorId != null) {
creatorId = newCreatorId.toString();
}
String creatorName = "";
if (!creatorId.equals(currentUserId))
creatorName = userName;
else
creatorName = creatorId;
Message message = new Message(dataSnapshot.getKey(), creatorName, text);
messageList.add(message);
messagesAdapter.notifyDataSetChanged();
recyclerView.smoothScrollToPosition(messagesAdapter.getItemCount() - 1);
loadingMessages.setVisibility(View.INVISIBLE);
loadingWarning.setVisibility(View.INVISIBLE);
sendButton.setVisibility(View.VISIBLE);
} else {
loadingMessages.setVisibility(View.INVISIBLE);
loadingWarning.setText("Messages not found. \nCould not load your messages :/");
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists())
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
loadingMessages.setVisibility(View.INVISIBLE);
loadingWarning.setText("Loading cancelled. \nCould not load your messages :/");
Log.d("mymessages", "fetchChatMessages(), onCancelled called.");
}
});
} else {
lyNoConnection.setVisibility(View.VISIBLE);
Log.d("mymessages", "Not connected to network.");
}
} else {
loadingMessages.setVisibility(View.INVISIBLE);
loadingWarning.setVisibility(View.INVISIBLE);
sendButton.setVisibility(View.VISIBLE);
}
}
} else {
Log.d("mymessages", "chatId = null");
}
}
In my NotificationListener of my application I am listening (and syncronizing with my SQLite) to new or changed data from Firebase.
In the first case I would like to check if the status of a loaned book has changed. Therefor I use the following code in onStartCommand:
databaseLoanedBooks.orderByChild("contactId").equalTo(firebase_uid).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String book_id = dataSnapshot.child("bookId").getValue(String.class);
String book_status = dataSnapshot.child("bookStatus").getValue(String.class);
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
List<String> all_book_ids = db.getAllBookIds();
if (all_book_ids.contains(book_id)){
// some action... check for status, if status=x output of notification
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Moreover I would like to check if there is a new message about the loaned book at the server. Therefor I use the following code in onStartCommand of my NotifiactionListener:
final List<String> all_book_ids = db.getAllBookIds();
// iterate through all book-ids the user has loaned at the moment (and saved in SQL)
for (int i = 0; i < all_book_ids .size(); i++) {
final String check_book_id = all_book_ids.get(i);
databaseMessage.child(check_book_id).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ChatMessage chatMessage = dataSnapshot.getValue(ChatMessage.class);
String message_id = dataSnapshot.child("messageId").getValue(String.class);
String message_book_id = dataSnapshot.child("messageBookId").getValue(String.class);
String message_uid = dataSnapshot.child("messageUid").getValue(String.class);
String message_text = dataSnapshot.child("messageText").getValue(String.class);
String message_time = String.valueOf(chatMessage.getMessageTime());
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
final List<String> all_message_ids = db.getAllMessagesIds();
final List<String> all_book_ids = db.getAllBookIds();
String new_message = getString(R.string.text_new_message);
if (all_book_ids.contains(message_book_id)) {
if (all_message_ids.contains(message_id_changed)) {
// already exists
} else {
ContentValues values_new = new ContentValues();
values_new.put(DatabaseHelper.COLUMN_CHAT_FCM_ID, message_id); values_new.put(DatabaseHelper.COLUMN_CHAT_BOOK_ID, message_book_id);
values_new.put(DatabaseHelper.COLUMN_CHAT_TEXT, message_text_changed); values_new.put(DatabaseHelper.COLUMN_CHAT_BOOK_ID, message_uid);
values_new.put(DatabaseHelper.COLUMN_CHAT_TIME, message_time);
todoUri = getContentResolver().insert(DataContentProvider.CONTENT_URI_CHATS, values_new);
HashMap<String, String> user_session = session.getUserDetails();
// UID from sharedpreferences
String noti_status = user_session.get(SessionManager.KEY_NOTIFICATION);
String user_name_chat_sql = String.valueOf(db.getContactName(message_uid));
String book_name = String.valueOf(db.getBookNameForWA(message_book_id));
user_name_chat_sql = user_name_chat_sql.replaceAll("\\p{P}", "");
book_name = book_name.replaceAll("\\p{P}", "");
showNotificationNewMessage(new_message, user_name_chat_sql, message_text, book_name);
}
}
}
#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) {
}
});
}
With this code I have a data usage of approximately 2 MB per day per user. So my question is: How can I minimize my downloads and following from this my data usage? In the code to check for new messages I tried to use a for-loop to restrict the gathered data only for the books of the respective user, but this is unfortunately not the solution. How can I solve this problem?
Here is my code.
set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
auth = FirebaseAuth.getInstance();
final FirebaseUser user = auth.getCurrentUser();
String emails = user.getEmail().toString().trim();
String titless = mtitle.getText().toString().trim();
String pricess = mprice.getText().toString();
String timess = mtime.getText().toString();
String productss = mproduct.getText().toString();
String detailss = mdetail.getText().toString();
String categorys = mspinner.getSelectedItem().toString().trim();
final ContactsInfo contact = new ContactsInfo(emails,titless,pricess,timess,productss,detailss,categorys);
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
i = (int) dataSnapshot.child("商品").getChildrenCount();
}
#Override
public void onCancelled(DatabaseError error) {
}
});
mRef.child("商品").child(String.valueOf(i)).setValue(contact);
}
});
}}
When I use this code to write into my firebase,it will overwrite number0's data,after that it will work normally, I want to know how should I do if I don't want it to overwrite my previous data.
The onDataChange function code is executed at a later point of time than setValue. The onDataChange function is called asynchronously. Try the following code -
set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
auth = FirebaseAuth.getInstance();
final FirebaseUser user = auth.getCurrentUser();
String emails = user.getEmail().toString().trim();
String titless = mtitle.getText().toString().trim();
String pricess = mprice.getText().toString();
String timess = mtime.getText().toString();
String productss = mproduct.getText().toString();
String detailss = mdetail.getText().toString();
String categorys = mspinner.getSelectedItem().toString().trim();
final ContactsInfo contact = new ContactsInfo(emails, titless, pricess, timess, productss, detailss, categorys);
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
i = (int) dataSnapshot.child("商品").getChildrenCount();
mRef.child("商品").child(String.valueOf(i)).setValue(contact);
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
});