I have been trying to send a custom message in my database (Emergency_Contact) by a button click (mRescue), when a button is clicked it's going to check the user_id of the person who pressed the button after that check in Emergency_Contact for every person who has the senders_user_id as their child, If they have the sender_user_id as their child it sends them the message else it return a Toast message. I tried to run my code but it's crashing i don't know why.
this is my activity where this is carried out.
public class MenuActivity extends AppCompatActivity
{
Button mRescue;
private Double lati;
private GoogleMap mMap;
LocationManager locationManager;
private DatabaseReference mRootRef;
private String mCurrentUserId;
private String userName;
private String mChatUser;
private DatabaseReference mNotificationDatabase;
private String message;
private String value_lat = null;
private String value_long = null;
private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
LocationTrack locationTrack;
private DatabaseReference usersDatabase;
private DatabaseReference emergencyContactDB;
private String user_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
FirebaseApp.initializeApp(this);
usersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
emergencyContactDB = FirebaseDatabase.getInstance().getReference().child("Emergency_Contact");
mNotificationDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Notifications");
mRootRef = FirebaseDatabase.getInstance().getReference();
mLocationDatabase = mRootRef.child("EmergencyMessages");
mAuth = FirebaseAuth.getInstance();
gettingIntent();
mRescue = (Button)findViewById(R.id.rescue);
mRescue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
if(value_lat == null & value_long == null)
{
mRescue.setEnabled(false);
}
else
{
mRescue.setEnabled(true);
usersDatabase.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
final String user_db = dataSnapshot.child("user_id").getValue().toString();
if (!user_db.isEmpty())
{
user_id = dataSnapshot.child("user_id").getValue().toString();
emergencyContactDB.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
final String emergency_db = dataSnapshot.child(user_id).getValue().toString();
if (emergency_db.contains(mCurrentUserId))
{
addEmergencyMessage();
addEmergencyChat();
Toast.makeText(getApplicationContext(), "Emergency Alert message was successfully sent",Toast.LENGTH_LONG).show();
} else
{
Toast.makeText(getApplicationContext(), "You Do not have any emergency contacts. Please add them and try again.",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
else {
Toast.makeText(getApplicationContext(), "The Database is Empty",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Alerts");
toolbar.setTitleTextColor(android.graphics.Color.WHITE);
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
mUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.child("name").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void checkUser() {
if (mCurrentUserId == null) {
sendToStart();
}else{
mUserRef.child("online").setValue("true");
}
}
private void gettingIntent() {
Intent intent =getIntent();
mChatUser = intent.getStringExtra("user_id");
}
private void addEmergencyChat() {
value_lat = String.valueOf(mLastLocation.getLatitude());
value_long = String.valueOf(mLastLocation.getLongitude());
String current_user_ref="Emergency_Messages/"+mCurrentUserId+"/"+user_id;
String chat_user_ref= "Emergency_Messages/"+user_id+"/"+mCurrentUserId;
DatabaseReference chat_push_key = mRootRef.child("Emergency_Messages").child(mCurrentUserId).child(user_id).push();
String push_key = chat_push_key.getKey();
Map messageMap = new HashMap();
messageMap.put("userName", userName + " is in trouble on this location:"+"\nlatitude ="+value_lat +"\nlongitude ="+ value_long);
messageMap.put("open_location", "Tap Here to see "+userName+"'s location");
messageMap.put("type","text");
messageMap.put("latitude",value_lat);
messageMap.put("longitude", value_long);
messageMap.put("from",mCurrentUserId);
messageMap.put("seen",false);
messageMap.put("time", ServerValue.TIMESTAMP);
DatabaseReference newNotificationref = mRootRef.child("Emergency_Notifications").child(user_id).push();
String newNotificationId = newNotificationref.getKey();
HashMap<String, String> notificationData = new HashMap<>();
notificationData.put("from", mCurrentUserId);
notificationData.put("type", "alert");
Map messageNotifMap = new HashMap();
messageNotifMap.put("Emergency_Notifications/" + user_id + "/" + newNotificationId, notificationData);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref+ "/"+push_key,messageMap);
messageUserMap.put(chat_user_ref+ "/"+push_key,messageMap);
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!=null){
Log.d("TAG",databaseError.getMessage().toString());
}
}
});
}
private void addEmergencyMessage() {
mRootRef.child("Emergency_Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(user_id)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen",false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Emergency_Chat/"+mCurrentUserId+"/"+user_id, chatAddMap);
chatUserMap.put("Emergency_Chat/"+user_id+"/"+mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!= null){
Toast.makeText(MenuActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
} else{
mCurrentUserId = mAuth.getCurrentUser().getUid();
mUserRef.child("online").setValue("true");
}
}
#Override
protected void onStop() {
super.onStop();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null) {
mUserRef.child("online").setValue(ServerValue.TIMESTAMP);
}
}
private void sendToStart() {
Intent startIntent = new Intent(MenuActivity.this, Home.class);
startActivity(startIntent);
finish();
}
}
How can I send this message?
this is my logcat
02-12 07:01:23.046 32377-32377/? E/Zygote: no v2
02-12 07:01:23.056 32377-32377/? E/SELinux: [DEBUG] get_category:
variable seinfo: default sensitivity: NULL, cateogry: NULL
02-12 07:01:34.477 32377-32377/com.rescuex_za.rescuex E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.rescuex_za.rescuex, PID: 32377
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.rescuex_za.rescuex.MenuActivity$1$1.onDataChange(MenuActivity.java:128)
at com.google.android.gms.internal.zzegf.zza(Unknown Source)
at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source)
at com.google.android.gms.internal.zzeig.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
This is happening because dataSnapshot is null and you are calling toString() on a null object reference. To solve this, check first the dataSnapshot for existens because using it.
if(dataSnapshot != null && dataSnapshot.exists()) {
//your logic
}
To only get the pJhp..., please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Emergency_Contact").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
Log.d("TAG", key);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
Related
i am trying to fetch all uid from database and put in a loop to compare all uid Reservations with the reservations that i am making. the point is to compare all time and parking with the new one i am booking so there will no be conflict in reservation.
the firebase strcuture:
the code
public class MainActivity5 extends AppCompatActivity {
private Button btnMove;
Button b;
RadioGroup radioGroup;
RadioButton selectedRadioButton;
FirebaseDatabase rootnode, rootnode2;
DatabaseReference reference, reference2;
ReservationClass reservationClass;
String str, TimeGroup;
FirebaseAuth auth;
String currentuser = FirebaseAuth.getInstance().getCurrentUser().getUid();
String allUsers = (String) FirebaseAuth.getInstance().getUid();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
btnMove = findViewById(R.id.ConfirmBooking);
radioGroup = (RadioGroup) findViewById(R.id.ParkingSpace);
TimeGroup = getIntent().getExtras().getString("Selected Time : ");
btnMove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// moveToActivity6();
selectedRadioButton = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());
//get RadioButton text
String parkingSpace = selectedRadioButton.getText().toString();
final String time3 = TimeGroup;
final String parking = parkingSpace;
String id = FirebaseAuth.getInstance().getCurrentUser().getUid();
/*Intent i = new Intent(MainActivity5.this, MainActivity6.class);
i.putExtra("Selected Parking space is: ", parkingSpace);
startActivity(i);*/
reference2 = FirebaseDatabase.getInstance().getReference("Reservation").child(id);
reference2.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (!snapshot.exists()) {
rootnode = FirebaseDatabase.getInstance();
reference = rootnode.getReference("Reservation");
ReservationClass reservationClass = new ReservationClass(time3, parking);
reference.child(currentuser).setValue(reservationClass);
Toast.makeText(MainActivity5.this, "Booking successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity5.this, MainActivity6.class);
startActivity(intent);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
/* final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference("Reservation");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.getValue() != null) {
for (DataSnapshot ds : snapshot.getChildren()) {
String uid = "" + snapshot.getValue();
String allUsers = uid;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});*/
Query query = FirebaseDatabase.getInstance().getReference("Reservation").child(allUsers);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
selectedRadioButton = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());
final String parkingSpace = selectedRadioButton.getText().toString();
final String time1 = TimeGroup;
final String parking = parkingSpace;
final String id = FirebaseAuth.getInstance().getCurrentUser().getUid();
for (DataSnapshot snapShot : snapshot.getChildren()) {
//Toast.makeText(MainActivity5.this, time1, Toast.LENGTH_SHORT).show();
String type = snapshot.child("time").getValue().toString();
String type2 = snapshot.child("parking").getValue().toString();
if (type.equals(time1) && type2.equals(parking)) {
Toast.makeText(MainActivity5.this, allUsers, Toast.LENGTH_SHORT).show();
}
if (!type.equals(time1) || !type2.equals(parking)) {
Toast.makeText(MainActivity5.this, type, Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity5.this, type2, Toast.LENGTH_SHORT).show();
rootnode = FirebaseDatabase.getInstance();
reference = rootnode.getReference("Reservation");
ReservationClass reservationClass = new ReservationClass(time1, parking);
reference.child(id).setValue(reservationClass);
Intent intent = new Intent(MainActivity5.this, MainActivity6.class);
startActivity(intent);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
In your current data structure this requires that you load all reservations and check them individually, meaning the performance linearly depends on the number of reservations in the system.
I highly recommend modifying your (or creating a dedicated) data structure for this, which makes what you want a direct lookup.
Reservations: {
"A1_0800-0900am": "Q1zT9iCw...OHI1",
"A4_0800-0900am": "3ReGkVGF...4Cm2",
}
So the keys here are based on the parking spot and time slot, each combination mapping to a idempotent, unique key.
With the above data structure it becomes impossible to add the new reservation for:
"A1_0800-0900am": "TDBZigbk...7Bs1",
As a reservation for that key already exists.
In fact, it is easy to enforce that existing reservations can't be overwritten in security rules with:
".write": "!data.exists()"
I am trying to create a chat. However, I am facing a big issue. When I delete an entry from the chat recyclerView, the entry stays there, but is removed from the firebase db as expected (I mean only removing from db is working). It only disapears when I close the activity and open it again. My recyclerView has a feature of load 10 more entries each time a user scrolls.
I dont understand how can I remove the entry from the recyclerView?
I need to call the function loadMoreMessages()? Refresh the activity?
MessageAdapter.java
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder>{
public class MessageViewHolder extends RecyclerView.ViewHolder {
public TextView messageText, displayName;
public CircleImageView profileImage;
public ImageView messageImage;
public MessageViewHolder(View itemView) {
super(itemView);
messageText = (TextView) itemView.findViewById(R.id.message_text_layout);
profileImage = (CircleImageView) itemView.findViewById(R.id.message_profile_layout);
displayName = (TextView) itemView.findViewById(R.id.name_text_layout);
messageImage = (ImageView) itemView.findViewById(R.id.message_image_layout);
}
}
private List<Messages> mMessageList;
private FirebaseAuth mAuth;
private DatabaseReference mUserDatabase;
private DatabaseReference mUserDatabaseSettings;
private String rul, fromUser_t;
private UserAccountSettings mUserAccountSettings;
public MessageAdapter(List<Messages> mMessageList) {
this.mMessageList = mMessageList;
}
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_single_layout,parent,false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(v);
}
#Override
public void onBindViewHolder(final MessageViewHolder holder, final int position) {
final String current_user_id = mAuth.getCurrentUser().getUid();
final Messages c = mMessageList.get(position);
final String from_user = c.getFrom();
final String message_type = c.getType();
final String messageContent = c.getMessage();
/**
* popup for text message
*/
// check if the message is from the current user
if(from_user.equals(current_user_id))
{
holder.messageText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//popup menu to select option
CharSequence options[] = new CharSequence[]
{
"Delete from my phone",
"Delete for Everyone" ,
"Cancel"
};
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle("Message Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0)
{
deleteSentMessage(position, holder);
// Intent intent = new Intent(holder.itemView.getContext(), ChatActivity.class);
// holder.itemView.getContext().startActivity(intent);
//MessageViewHolder.class.notify();
holder.messageText.setPaintFlags(holder.messageText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
else if(i == 1)
{
deleteMessageForEveryOne(position, holder);
// Intent intent = new Intent(holder.itemView.getContext(), ChatActivity.class);
// holder.itemView.getContext().startActivity(intent);
//notifyDataSetChanged();
//holder.messageText.setVisibility(View.GONE);
}
}
});
builder.show();
}
});
}else
{
// similar code to check if the message is from the other user
}
holder.messageText.setVisibility(View.GONE);
holder.messageImage.setVisibility(View.GONE);
if("text".equals(message_type))
{
holder.messageText.setVisibility(View.VISIBLE);
if(from_user.equals(current_user_id))
{
holder.messageText.setBackgroundResource(R.drawable.message_text_background);
holder.messageText.setTextColor(Color.WHITE);
//todo left right not working
holder.messageText.setGravity(Gravity.LEFT);
}else
{
holder.messageText.setBackgroundColor(Color.WHITE);
holder.messageText.setTextColor(Color.BLACK);
holder.messageText.setGravity(Gravity.RIGHT);
}
holder.messageText.setText(c.getMessage());
}else
{
holder.messageImage.setVisibility(View.VISIBLE);
UniversalImageLoader.setImage(messageContent,holder.messageImage,null,"");
}
}
#Override
public int getItemCount() {
return mMessageList.size();
}
/**
function to Delete from my phone
**/
private void deleteSentMessage(final int position, final MessageViewHolder holder)
{
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("messages")
.child(mMessageList.get(position).getFrom())
.child(mMessageList.get(position).getTo())
.child(mMessageList.get(position).getMessageID())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(holder.itemView.getContext(), "Deleted Successfully.", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(holder.itemView.getContext(), "Error Occurred.", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
function to Delete from receiver phone
**/
private void deleteReceiveMessage(final int position, final MessageViewHolder holder)
{
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("messages")
.child(mMessageList.get(position).getTo())
.child(mMessageList.get(position).getFrom())
.child(mMessageList.get(position).getMessageID())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(holder.itemView.getContext(), "Deleted Successfully.", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(holder.itemView.getContext(), "Error Occurred.", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
function to Delete from both sides
**/
private void deleteMessageForEveryOne(final int position, final MessageViewHolder holder)
{
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("messages")
.child(mMessageList.get(position).getTo())
.child(mMessageList.get(position).getFrom())
.child(mMessageList.get(position).getMessageID())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
rootRef.child("messages")
.child(mMessageList.get(position).getFrom())
.child(mMessageList.get(position).getTo())
.child(mMessageList.get(position).getMessageID())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(holder.itemView.getContext(), "Deleted Successfully.", Toast.LENGTH_SHORT).show();
}
}
});
}else
{
Toast.makeText(holder.itemView.getContext(), "Error Occurred.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
ChatActivity.java
public class ChatActivity extends AppCompatActivity {
private static final String TAG = "ChatActivity";
//todo check is user is logedin
//user with whom Iam talking to
private String mChatUser;
private Toolbar mChatToolbar;
private DatabaseReference mRootRef;
private TextView mTitleView, mLastSeenView;
private CircleImageView mProfileImage;
private FirebaseAuth mAuth;
private String mCurrentUserId;
private ImageButton mChatAddBtn;
private ImageButton mChatSendBtn;
private EditText mChatMessageView;
private RecyclerView mMessagesList;
private SwipeRefreshLayout mRefreshLayout;
private final List<Messages> messagesList = new ArrayList<>();
private LinearLayoutManager mLinearLayout;
private MessageAdapter mAdapter;
private static final int TOTAL_ITEMS_TO_LOAD = 10;
private int mCurrentPage = 1;
private int itemPos =0;
private String mLastKey = "";
private String mPrevKey = "";
private static final int GALLERY_PICK = 1;
//Storage Firebase
private StorageReference mImageStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
// create a toolbar and set the title as the user with we are chatting to
mChatToolbar = (Toolbar) findViewById(R.id.chat_app_bar);
setSupportActionBar(mChatToolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// to add a custom view to the toolbar
actionBar.setDisplayShowCustomEnabled(true);
mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();
mChatUser = getIntent().getStringExtra("user_id");
String userName = getIntent().getStringExtra("user_name");
getSupportActionBar().setTitle(userName);
// String userName = getIntent().getStringExtra("user_name");
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = inflater.inflate(R.layout.chat_custom_bar, null);
actionBar.setCustomView(action_bar_view);
// ---------- Custom Action bar items ---
mTitleView = (TextView) findViewById(R.id.custom_bar_title);
mLastSeenView = (TextView) findViewById(R.id.custom_bar_seen);
mProfileImage = (CircleImageView) findViewById(R.id.custom_bar_image);
mChatAddBtn = (ImageButton) findViewById(R.id.chat_add_btn);
mChatSendBtn = (ImageButton) findViewById(R.id.chat_send_btn);
mChatMessageView = (EditText) findViewById(R.id.chat_message_view);
mAdapter = new MessageAdapter(messagesList);
mImageStorage= FirebaseStorage.getInstance().getReference();
mMessagesList = (RecyclerView) findViewById(R.id.messages_list);
mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.message_swipe_layout);
mLinearLayout = new LinearLayoutManager(this);
mMessagesList.setHasFixedSize(true);
mMessagesList.setLayoutManager(mLinearLayout);
//mMessagesList.setItemViewCacheSize(25);
mMessagesList.setDrawingCacheEnabled(true);
mMessagesList.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
mMessagesList.setAdapter(mAdapter);
loadMessages();
mTitleView.setText(userName);
mRootRef.child("users").child(mChatUser).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String online = dataSnapshot.child("lastSeen").getValue().toString();
//String image = dataSnapshot.child()
if(online.equals("true")){
mLastSeenView.setText("Online");
}else {
GetTimeAgo getTimeAgo = new GetTimeAgo();
long lastTime = Long.parseLong(online);
String lastSeenTime = getTimeAgo.getTimeAgo(lastTime, getApplicationContext());
mLastSeenView.setText(lastSeenTime);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mRootRef.child("Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull 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/" + mCurrentUserId + "/" + mChatUser, chatAddMap); //add map to current user
chatUserMap.put("Chat/" + mChatUser + "/" + mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(#Nullable DatabaseError databaseError, #NonNull DatabaseReference databaseReference) {
if(databaseError != null){
//Log.d(TAG, "onComplete: CHAT LOG", databaseError.getMessage());
Log.e(TAG, "onComplete: CHAT_LOG" + databaseError.getMessage().toString());
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mChatSendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
// open gallery to get an image
mChatAddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent,"SELECT IMAGE"), GALLERY_PICK);
}
});
//pagination
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mCurrentPage++;
// each time it loads a new page should go to position zero
itemPos = 0;
loadMoreMessages();
}
});
}
/**
* load more messages everytime uesr refreshes
*/
private void loadMoreMessages() {
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
Query messageQuery = messageRef.orderByKey().endAt(mLastKey).limitToLast(10);
messageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Messages message = dataSnapshot.getValue(Messages.class);
String messageKey = dataSnapshot.getKey();
if(!mPrevKey.equals(messageKey)){
messagesList.add(itemPos++, message);
Log.d(TAG, "onChildAdded: xx" + mPrevKey + "---" + mLastKey);
} else {
mPrevKey = mLastKey;
}
if(itemPos == 1){
mLastKey = messageKey;
}
Log.d(TAG, "onChildAdded: TOTALKEUS" + "lastkey: " + mLastKey + " | Prev key : " + mPrevKey + " | Message Key : " + messageKey);
mAdapter.notifyDataSetChanged();
mRefreshLayout.setRefreshing(false);
mLinearLayout.scrollToPositionWithOffset(itemPos , 0);
}
#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) {
}
});
}
/**
* method used to load messages once
*/
private void loadMessages() {
//query to get pagination and last 10 messages
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
Query messageQuery = messageRef.limitToLast(mCurrentPage * TOTAL_ITEMS_TO_LOAD);
messageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Messages message = dataSnapshot.getValue(Messages.class);
itemPos++;
if(itemPos == 1){
// get the key to be user as a start point when loading more items
String messageKey = dataSnapshot.getKey();
mLastKey = messageKey;
mPrevKey = messageKey;
Log.d(TAG, "onChildAdded: last " +mLastKey + " prev " + mPrevKey + " messa " + messageKey + "-----------");
}
messagesList.add(message);
mAdapter.notifyDataSetChanged();
//pagination - define the bottom of the recycler view
//automatic scroll to bottom
mMessagesList.scrollToPosition(messagesList.size() - 1);
mRefreshLayout.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) {
}
});
}
/**
* send photo message
* #param requestCode
* #param resultCode
* #param data
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){
Uri imageUri = data.getData();
final String current_user_ref = "messages/" + mCurrentUserId + "/" + mChatUser;
final String chat_user_ref = "messages/" + mChatUser + "/" + mCurrentUserId;
DatabaseReference user_message_push = mRootRef.child("messages")
.child(mCurrentUserId).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()){
Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String download_url = uri.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", mCurrentUserId);
messageMap.put("to", mChatUser);
messageMap.put("messageID", push_id );
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref + "/" + push_id, messageMap);
messageUserMap.put(chat_user_ref + "/" + push_id, messageMap);
mChatMessageView.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());
}
}
});
}
});
}
}
});
}
}
}
``
You're using a ChildEventListener in your messageQuery, which has these main methods:
onChildAdded, which is called initially for every child node matching your messageQuery query, and subsequently when any child node is added to the database that falls into messageQuery.
onChildRemoved, which is called when any child node (that falls) is removed from the database (or at least to the part that messageQuery is listening to).
onChildChanged, which is called when any child node that messageQuery is listening is modified in the database.
If I look at your implementation, you've only implemented onChildAdded. So when you remove a child node from the database, Firebase tells your ChildEventListener about it, but that then does nothing.
To remove the message from the UI when it gets removed from the database, you will need to implement:
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
// TODO: remove the message matching dataSnapshot from messagesList
// TODO: call adapter.notifyDataSetChanged() so that the UI gets updates
}
The list changes size so you have to give new list size to your logic.
Thanks Frank and Vedprakash. It was a quit obvious. At that time I did not understand how to pass the position and remove the item using onChildRemoved. Now I understand. What I did was based on this post: How to use onChildRemoved in Firebase Realtime Database?
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
Toast.makeText(ChatActivity.this, "Entered on this part!", Toast.LENGTH_SHORT).show();
int index = keyList.indexOf(dataSnapshot.getKey());
messagesList.remove(index);
keyList.remove(index);
//mAdapter.notifyDataSetChanged();
mAdapter.notifyItemRemoved(index);
}
I tested it and is working fine. However, It has a little issue. My chat loads 10 items (defined by: private static final int TOTAL_ITEMS_TO_LOAD = 10;). If the user scrolls it will load more items.
When I open the chat page, the items loaded are from "2" to "11" But, when I delete item, for example, "9" the item "1" show up. Meaning that, the item right before the position zero of the messagesList will show up.
I tried several things. My last try was set the mLinearLayout.scrollToPosition, decrease the TOTAL_ITEMS_TO_LOAD. And the issue stays alive. :(
Before delete
After delete item
hi guys I would like as a title to read a single node created previously in my realtime firebase database, the database is thus created:
Users
---- UID1
---- Email:
---- Fullname:
---- Phone:
---- Coins:
---- UID2
---- Email:
---- Fullname:
---- Phone:
---- Coins:
so my database has a structure like the one shown and I need to read in onDataChange and then write the data in a TextView.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_coins_);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Utenti");
myRef.child("Rapp Coins %").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coinsRapp = dataSnapshot.getValue(String.class);
mCoins.setText(coinsRapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
this method I used doesn't work as I can't get it to take the data I need.
I need to take the Coins value: within each different logged user, so each logged in user reads his data.
I the UID value that identifies each user, I created it based on his mobile number, so each user has his own mobile number that identifies him as UID.
this is all my code, as you can see the data that saves the UID is contained in mPhone, which was saved and then brought into this activity through the SharedPreferences.
public class PageCoins_Activity extends AppCompatActivity implements RewardedVideoAdListener {
private static final String TAG = MainActivity.class.getName();
private FirebaseAuth mAuth;
private AdView mBannerTop;
private AdView mBannerBot;
private RewardedVideoAd mRewardedVideoAd;
public double Coins;
double coinsOp = 0.00;
double coinsCl = 0.00;
double coinssum = 0.00;
Button mButton;
Button mPhonebtn;
TextView mCoinscounter;
TextView mCoins;
FirebaseDatabase mDatabase;
EditText mPhoneEdt;
TextView mPhone;
#Override
protected void onStart(){
super.onStart();
updateUI();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_coins_);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Utenti");
myRef.child("Rapp Coins %").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coinsRapp = dataSnapshot.getValue(String.class);
mCoins.setText(coinsRapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mAuth = FirebaseAuth.getInstance();
initFirebase();
//counter CRD
mCoinscounter = (TextView)findViewById(R.id.Textcoins);
mButton = (Button)findViewById(R.id.btn2);
mPhoneEdt = (EditText)findViewById(R.id.NumberPhEdt);
mPhone = (TextView) findViewById(R.id.NumberPhTxt);
mCoins = (TextView)findViewById(R.id.txtGen);
mPhonebtn = (Button)findViewById(R.id.buttonPhone);
//mPhoneEdt.setVisibility(View.GONE);
//mPhone.setVisibility(View.VISIBLE);
findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins Day %").setValue(mCoinscounter.getText().toString());
}
});
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
//Set Orientation Portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Banner Top View Coins
mBannerTop = (AdView) findViewById(R.id.adViewTopcoins);
AdRequest adRequest = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
mBannerTop.loadAd(adRequest);
// Banner Bot View Coins
mBannerBot = (AdView) findViewById(R.id.adViewBotcoins);
AdRequest adRequest1 = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
mBannerBot.loadAd(adRequest1);
getnumberprefs();
//ADMob Video
loadRewardedVideoAd();
}
private void getnumberprefs() {
SharedPreferences numb = getSharedPreferences(Register_Activity.NUMB, MODE_PRIVATE);
String numberphn = numb.getString(Register_Activity.KEY_NUMB,null);
mPhone.setText(numberphn);
}
//boolean changepgcoins = true;
public void changeNumber(View view) {
/*if (changepgcoins == true){
mPhoneEdt.setVisibility(View.GONE);
mPhone.setVisibility(View.VISIBLE);
changepgcoins = false;
}else{
mPhoneEdt.setVisibility(View.VISIBLE);
mPhone.setVisibility(View.GONE);
changepgcoins = true;
}*/
}
private void initFirebase() {
mDatabase = FirebaseDatabase.getInstance();
}
public void HomeClick(View view){
Intent intenthome = new Intent(this, MainActivity.class);
finish();
startActivity(intenthome);
}
public void displayCrd (double amount){
mCoinscounter.setText(String.format("%.2f", amount));
}
private void loadRewardedVideoAd() {
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
new AdRequest.Builder().build());
}
public void logout(View view) {
mAuth.signOut();
updateUI();
}
private void updateUI() {
FirebaseUser currentuser = mAuth.getCurrentUser();
if(currentuser == null){
Intent intTologin = new Intent(this, Login_Activity.class);
finish();
startActivity(intTologin);
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d(TAG, "Video Caricato");
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, " RAPp " + " COINS " + " : " + rewardItem.getAmount(), Toast.LENGTH_LONG).show();
Coins += rewardItem.getAmount();
displayCrd(Coins/40200*100);
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Log.d(TAG, "Caricamento Fallito");
}
#Override
public void onRewardedVideoCompleted() {
loadRewardedVideoAd();
}
#Override
protected void onDestroy() {
if (!isEmpty(mCoins)){
String coinsopen = mCoins.getText().toString();
String coinscounter = mCoinscounter.getText().toString();
coinsOp = Double.parseDouble(String.format(coinsopen.replace(',', '.'), "%.2f"));
coinsCl = Double.parseDouble(String.format(coinscounter.replace(',', '.'), "%.2f"));
coinssum = (coinsOp + coinsCl);
mCoinscounter.setText(String.valueOf(coinssum));
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins %").setValue(mCoinscounter.getText().toString());
}else{
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins %").setValue(mCoinscounter.getText().toString());
}
super.onDestroy();
}
private boolean isEmpty(TextView mCoins) {
String input = mCoins.getText().toString();
return input.length() == 0.00;
}
}
I really ask for help on the solution of this thing because it's the last thing I need to finish and I can't thank you.
{
"Utenti" : {
"3********4" : {
"E-Mail" : "",
"Full Name" : "",
"Phone" : "",
"Rapp Coins %" : "",
"Rapp Coins Day %" : ""
},
"3********1" : {
"E-Mail" : "",
"Full Name" : "",
"Phone" : "",
"Rapp Coins %" : "",
"Rapp Coins Day %" : ""
},
}
}
this is my database so composed.
I am making an chat app and I want to do the following:
When starting the MainActivity, check if the user is logged in. If not, start FirebaseAuthUI.
But FirebaseAuth only supports a few parameters and, to add more, I created a Database node do each user, which store other parameters.
To get this parameters, after finishing FirebaseAuth, the user is redirected to an Activity that get all extra information and store in the user's node in the Database. All of this is working just fine.
But after the user fill the information in this Info Activity and finish the register, it should go back to MainActivity and stay there. How can I do that?
I am trying it this way:
I added to each user a Boolean variable called userCompleted, which informs if the user have already gave their information. I check if this variable is false, and if so, I call the Info Activity intent and, in the when the user press the button to complete the registration in this Activity, it sets the userCompleted value to true in the user node in the Database and then start an intent that leads to MainActivity.
The problem is that in the Database, userCompleted is set to true and then immediately goes back to false, and I don't know why. Also, I guess I am having trouble on reading userCompleted from the Database, probably because I haven't worked much with asynchronous tasks.
I used a variable isUserCompleted declared in Main Activity to get track of the userCompleted value.
A way to check if is the first time the user is logging in would be useful too, although it wouldn't solve my whole problem.
This is my current code:
(if need more to try to understand the problem just ask in the comments)
Create AuthStateListener
public void setAuthStateListener(){
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
onSignInInitialize(user);
Log.d(TAG, "userUid = " + user.getUid());
Toast.makeText(SearchActivity.this, "Signed in!", Toast.LENGTH_SHORT).show();
} else {
onSignOutCleanup();
startLoginUI();
}
}
};
}
onSignInInitialize()
public void onSignInInitialize(final FirebaseUser user){
mLoggedFBUser = user;
mUserReference = mUsersDatabaseReference.child(user.getUid());
mUserReference.child("uid").setValue(user.getUid());
mUserReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
isUserCompleted = user.isUserCompleted();
Log.d(TAG, "UserCompleted (onDataChanged) "+ isUserCompleted);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Log.d(TAG, "UserCompleted (Before startActivity if) "+ isUserCompleted);
if (!isUserCompleted) {
startCreateProfileActivity(user);
}
Log.d(TAG, "UserCompleted (After startActivity if) "+ isUserCompleted);
mUserReference.child("username").setValue(user.getDisplayName());
mUserReference.child("email").setValue(user.getEmail());
attachChildEventListener();
}
Go back to Main Activity
mFinishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mUserDatabaseReference.child("userCompleted").setValue(true);
Intent intent = new Intent (CreateVolunteerProfile.this, SearchActivity.class);
startActivity(intent);
}
});
Entire MainActivity block (Actually it's called SearchActivity)
public class SearchActivity extends AppCompatActivity implements RecyclerAdapter.UserItemClickListener {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<User> users = new ArrayList<User>();
private String mLoggedUserId = "user2";
private String mLoggedUsername;
private User mLoggedUser;
private FirebaseUser mLoggedFBUser;
//private boolean isUserCompleted;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mPreferencesEditor;
private boolean firstTime = true;
private static final String TAG = "Search Activity";
private static final int USER_CLICK = 1;
private static final int RC_SIGN_IN = 1;
private static final int RC_CREATE_PROFILE = 2;
//Firebase
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mUsersDatabaseReference;
private DatabaseReference mUserReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
View loadingView = findViewById(R.id.cl_loading);
loadingView.setVisibility(View.VISIBLE);
//RecyclerView
recyclerView = findViewById(R.id.rv_users);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerAdapter(users, this);
recyclerView.setAdapter(adapter);
//Firebase
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mUsersDatabaseReference = mFirebaseDatabase.getReference().child("users");
setAuthStateListener();
loadingView.setVisibility(View.GONE);
}
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null)
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
detachChildEventListener();
clearAdapter();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.wtf(TAG, "onSaveInstanceState userId = "+ mLoggedUserId);
//Log.wtf(TAG, "UserCompleted (onSaveInstanceState) " + isUserCompleted);
outState.putString("userId", mLoggedUserId);
//outState.putBoolean("isUserCompleted", isUserCompleted);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mLoggedUserId = savedInstanceState.getString("userId");
//isUserCompleted = savedInstanceState.getBoolean("isUserCompleted");
//Log.wtf(TAG, "UserCompleted (onRestoreInstanceState) " + isUserCompleted);
Log.wtf(TAG, "onRestoreInstanceState userId = "+ mLoggedUserId);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if((requestCode == RC_SIGN_IN) && firstTime){
if (resultCode == RESULT_OK){
//Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED){
Toast.makeText(this, "Sign in canceled!", Toast.LENGTH_SHORT).show();
finish();
}
}
if((requestCode == RC_CREATE_PROFILE)){
if (resultCode == RESULT_OK){
//isUserCompleted = true;
}
}
}
#Override
public void onUserItemClick(int clickedUserIndex) {
Intent intent = new Intent (this, ChatActivity.class);
FirebaseUser user = mFirebaseAuth.getCurrentUser();
if(user != null) {
mLoggedUserId = user.getUid();
intent.putExtra("user1", mLoggedUserId);
String mUserRecieverId = users.get(clickedUserIndex).getUid();
intent.putExtra("user2", mUserRecieverId);
Log.wtf(TAG, "SearchActivity // user = " + users.get(clickedUserIndex));
Log.wtf("1", "SearchActivity // mLoggedUserId = " + mLoggedUserId + " // users.getUid() = " + users.get(clickedUserIndex).getUid());
startActivityForResult(intent, USER_CLICK);
}
else {
Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show();
}
}
public void setAuthStateListener(){
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
mUserReference = mUsersDatabaseReference.child(user.getUid());
onSignInInitialize(user);
Log.wtf(TAG, "userUid = " + user.getUid());
Toast.makeText(SearchActivity.this, "Signed in!", Toast.LENGTH_SHORT).show();
} else {
onSignOutCleanup();
startLoginUI();
}
}
};
}
public void onSignInInitialize(final FirebaseUser user){
mLoggedFBUser = user;
mUserReference = mUsersDatabaseReference.child(user.getUid());
mUserReference.child("uid").setValue(user.getUid());
boolean isUserCompleted = false;
mUserReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
isUserCompleted = user.isUserCompleted();
Log.wtf(TAG, "UserCompleted (onDataChanged) "+ isUserCompleted);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Log.wtf(TAG, "UserCompleted (Before startActivity if) "+ isUserCompleted);
if (!isUserCompleted) {
startCreateProfileActivity(user);
}
Log.wtf(TAG, "UserCompleted (After startActivity if) "+ isUserCompleted);
mUserReference.child("username").setValue(user.getDisplayName());
mUserReference.child("email").setValue(user.getEmail());
attachChildEventListener();
}
public void onSignOutCleanup(){
mLoggedUser = null;
mLoggedUserId = null;
mLoggedUsername = null;
detachChildEventListener();
clearAdapter();
}
public void attachChildEventListener(){
if (mChildEventListener == null){
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
User user = dataSnapshot.getValue(User.class);
users.add(user);
Log.d(TAG, "onChildAdded userId = "+ user.getUid());
//adapter.notifyItemInserted(users.size()-1);
adapter.notifyDataSetChanged();
}
#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) { }
};
}
mUsersDatabaseReference.addChildEventListener(mChildEventListener);
}
public void detachChildEventListener(){
if (mChildEventListener != null){
mUsersDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
public void clearAdapter() {
final int size = users.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
users.remove(0);
}
adapter.notifyItemRangeRemoved(0, size);
}
}
public void startCreateProfileActivity(FirebaseUser user){
mUsersDatabaseReference.child(user.getUid()).child("userCompleted").setValue(false);
Intent intent = new Intent(SearchActivity.this, CreateProfileActivity.class);
intent.putExtra("userId", user.getUid());
startActivityForResult(intent, RC_CREATE_PROFILE);
}
public void startLoginUI(){
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setLogo(R.mipmap.logo)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.GoogleBuilder().build(),
//new AuthUI.IdpConfig.FacebookBuilder().build(),
//new AuthUI.IdpConfig.TwitterBuilder().build(),
//new AuthUI.IdpConfig.GitHubBuilder().build(),
new AuthUI.IdpConfig.EmailBuilder().build()))
//new AuthUI.IdpConfig.PhoneBuilder().build(),
//new AuthUI.IdpConfig.AnonymousBuilder().build()))
.build(),
RC_SIGN_IN);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.search_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_item:
AuthUI.getInstance().signOut(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I think the simplest way is if a user clicked on finish Btn successfully make a flag with true else make it false
in your MainActivity
firebase.auth().onAuthStateChanged(function(user) {
// User signed in and not registered
if (user&&!isPressedOnFinishBtn) {
// User is signed in.
}
user clicked on finish btn
else if(isPressedOnFinishBtn) {
// No user is signed in.
}
});
This is how you can do that .
Create a method inside your Login activity .
private void AllowUserToLogin() {
String userName = userEmail.getText().toString();
String userPass = userPassword.getText().toString();
if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(userPass)) {
Toast.makeText(this, "Enter user Name / password first . . .", Toast.LENGTH_SHORT).show();
} else {
dialogBar.setTitle("Sign In ");
dialogBar.setMessage("Please Wait . . .");
dialogBar.setCanceledOnTouchOutside(true);
dialogBar.show();
mAuth.signInWithEmailAndPassword(userName, userPass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
String currentUserID = mAuth.getCurrentUser().getUid();
String deviceToken = Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
UsersRef.child(currentUserID).child("device_token")
.setValue(deviceToken)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
sendUserToMainActivity();
Toast.makeText(LoginPage.this, "Logged in Successfull . . . ", Toast.LENGTH_SHORT).show();
dialogBar.dismiss();
}
}
});
} else {
String error = task.getException().toString();
Toast.makeText(LoginPage.this, "Wrong Email or Password: " + error, Toast.LENGTH_SHORT).show();
dialogBar.dismiss();
}
}
});
}
}
and on ur onClick() method .
#Override
public void onClick(View v) {
if (v == needNewAccount) {
sendUserToRegisterActivity();
} else if (v == loginButton) {
AllowUserToLogin();
}else if(v == phone_button){
Intent phoneLoginIntent = new Intent(LoginPage.this , PhoneLoginActivity.class);
startActivity(phoneLoginIntent);
}
}
this is sendUserToRegisterActivity()
private void sendUserToRegisterActivity() {
Intent registerIntent = new Intent(LoginPage.this, RegisterationForm.class);
startActivity(registerIntent);
}
This is sendUserToMainActivity() .
private void sendUserToMainActivity() {
Intent mainIntent = new Intent(LoginPage.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
I have an Activity called ChatActivity where the users are going to be messaging each other. The activity is retrieving the messages as they are sent but when messages are displayed here are's duplicates of every message.
I do have AutoRefresh but it's not refreshing the way I want it to refresh. In my Activity there is swipe refresh as well and when I swipe it refreshes properly. This is the snap when swipe refresh is used:
How can I make my Auto Refresh display my messages like how it does when I swipe to refresh it? here is my code:
public class ChatActivity extends AppCompatActivity {
private Toolbar mChatToolbar; //used
private String mChatUser; //used
private String mthumb_image;
private String userName;
private String mCurrentUserId;
private TextView mUserStatus;
private EditText mChatMessageView;
private CircleImageView mProfileImage;
private FirebaseAuth mAuth;
private ImageButton mChatAddBtn;
private DatabaseReference mRootRef;
// Storage Firebase
private StorageReference mImageStorage;
private static final int GALLERY_PICK = 1;
private RecyclerView mMessagesList;
private SwipeRefreshLayout mRefreshLayout;
private ArrayList<Messages> arrayList_Messages = new ArrayList<>();
private MessageAdapter mAdapter;
private static final int TOTAL_ITEMS_TO_LOAD = 10;
private int mCurrentPage = 1;
private final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mChatMessageView = (EditText) findViewById(R.id.chat_message_view);
mChatAddBtn = (ImageButton) findViewById(R.id.chat_add_btn);
mChatToolbar = (Toolbar) findViewById(R.id.chat_app_bar);
setSupportActionBar(mChatToolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
//for Custom Action bar
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View customBar = inflater.inflate(R.layout.chat_custom_bar,null);
actionBar.setCustomView(customBar);
//getting intent Data
gettingIntentData();
// initializing user view
intCustomBarViewAndSetData();
doTheAutoRefresh();
mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();
//------- IMAGE STORAGE ---------
mImageStorage = FirebaseStorage.getInstance().getReference();
mRootRef.child("Chat").child(mCurrentUserId).child(mChatUser).child("seen").setValue(true);
LoadMessages();
//getting information about user online or offline and thumb image
mRootRef.child("Users").child(mChatUser).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();
Picasso.with(ChatActivity.this).load(thumb_image).placeholder(R.drawable.my_profile).into(mProfileImage);
String lastSeen = dataSnapshot.child("online").getValue().toString();
if(lastSeen.equals("true")){
mUserStatus.setText("Online");
}
else{
//converting string into long
Long lastTime = Long.parseLong(lastSeen);
// creating an instance of GetTimeAgo class
GetTimeAgo getTimeAgo = new GetTimeAgo();
String lastSeenTime = GetTimeAgo.getTimeAgo(lastTime,getApplicationContext());
mUserStatus.setText(lastSeenTime);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//for creating chat object
mRootRef.child("Chat").child(mCurrentUserId).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/"+mCurrentUserId+"/"+mChatUser, chatAddMap);
chatUserMap.put("Chat/"+mChatUser+"/"+mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!= null){
Toast.makeText(ChatActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// Retrieving the chat messages into recyclerview
LoadMessages();
mRefreshLayout.setRefreshing(true);
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mCurrentPage++;
//onRefresh remove the current messages from arraylist and load new messages
arrayList_Messages.clear();
// Load message
LoadMessages();
}
});
}
private void doTheAutoRefresh()
{
handler.postDelayed(new Runnable() {
#Override
public void run()
{
LoadMessages();
// Write code for your refresh logic
doTheAutoRefresh();
}
}, 5000);
}
// Load all messages from database into recyclerView
private void LoadMessages() {
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
//Query to load message per page i.e. 10
/*
per page load 10 message and onRefresh mCurrentpage is increment by 1
page 1 => load 10 messages (mCurrentPage = 1 then 1*10 =10)
page 2 => load 20 messages (mCurrentPage = 2 then 2*10 =20) and so on
*/
Query messageQuery = messageRef.limitToLast(mCurrentPage * TOTAL_ITEMS_TO_LOAD);
messageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
arrayList_Messages.add(messages);
mRefreshLayout.setRefreshing(true);
mAdapter.notifyDataSetChanged();
mMessagesList.scrollToPosition(arrayList_Messages.size()-1);
//when data load completely set refreshing
mRefreshLayout.setRefreshing(false);
}
#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) {
}
});
}
// send button
public void chatSendButton(View view){
sendMessage();
}
//sending a message
private void sendMessage() {
String message = mChatMessageView.getText().toString().trim();
if(!TextUtils.isEmpty(message)){
mChatMessageView.setText("");
String current_user_ref="messages/"+mCurrentUserId+"/"+mChatUser;
String chat_user_ref= "messages/"+mChatUser+"/"+mCurrentUserId;
DatabaseReference chat_push_key = mRootRef.child("messages").child(mCurrentUserId).
child(mChatUser).push();
String push_key = chat_push_key.getKey();
Map messageMap = new HashMap();
messageMap.put("message",message);
messageMap.put("type","text");
messageMap.put("from",mCurrentUserId);
messageMap.put("seen",false);
messageMap.put("time", ServerValue.TIMESTAMP);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref+ "/"+push_key,messageMap);
messageUserMap.put(chat_user_ref+ "/"+push_key,messageMap);
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!=null){
Log.d("TAG",databaseError.getMessage().toString());
}
}
});
}
}
//add button
public void chatAddButton(View view){
mChatAddBtn.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);
}
});
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){
Uri imageUri = data.getData();
final String current_user_ref = "messages/" + mCurrentUserId + "/" + mChatUser;
final String chat_user_ref = "messages/" + mChatUser + "/" + mCurrentUserId;
DatabaseReference user_message_push = mRootRef.child("messages")
.child(mCurrentUserId).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", mCurrentUserId);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref + "/" + push_id, messageMap);
messageUserMap.put(chat_user_ref + "/" + push_id, messageMap);
mChatMessageView.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());
}
}
});
}
}
});
}
}
private void intCustomBarViewAndSetData() {
TextView mTitleView = (TextView) findViewById(R.id.custom_bar_title);
mUserStatus = (TextView) findViewById(R.id.custom_bar_seen);
mProfileImage = (CircleImageView) findViewById(R.id.custom_bar_image);
mMessagesList = (RecyclerView) findViewById(R.id.messages_list);
mMessagesList.setLayoutManager(new LinearLayoutManager(this));
mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.message_swipe_layout);
mMessagesList.setHasFixedSize(true);
mAdapter = new MessageAdapter(this, arrayList_Messages);
mMessagesList.setAdapter(mAdapter);
//showing name on toolbar
mTitleView.setText(userName);
mTitleView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent profileIntent = new Intent(ChatActivity.this, ProfileActivity.class);
profileIntent.putExtra("user_id", mChatUser);
startActivity(profileIntent);
}
});
}
private void gettingIntentData() {
Intent intent =getIntent();
userName = intent.getStringExtra("Username");
mChatUser = intent.getStringExtra("user_id");
}
}
Clear the list before load in doTheAutoRefresh().
arrayList_Messages.clear();
LoadMessages();