ServerValue.TIMESTAMP saving and retrieving timestamp in Firebase - java

My code isn't returning the timestamp from Firebase and I don't know why. Furthermore, in the private void setupWidgets method in the if else statement timestamp is showing up red and I don't know why--I put ** next to it... Does anyone know why that is if I declared it above? Why am I not getting the timestamp in the TextView?
I have used these two pages as references
How to save the current date/time when I add new value to Firebase Realtime Database & Convert ServerValue.TIMESTAMP To date aside from all the videos I've watched, but it's still not coming out right.
PostAdapter.java
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile, post_image, like, comment, attend_event, save_event, more_options;
public TextView username, number_of_likes, description, number_of_comments, text_event, text_location, text_date_time,
number_of_people_attending_event, timestamp;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image_profile = itemView.findViewById(R.id.image_profile);
post_image = itemView.findViewById(R.id.post_image);
like = itemView.findViewById(R.id.like);
comment = itemView.findViewById(R.id.comment);
username = itemView.findViewById(R.id.username);
number_of_likes = itemView.findViewById(R.id.number_of_likes);
description = itemView.findViewById(R.id.description);
number_of_comments = itemView.findViewById(R.id.number_of_comments);
timestamp = itemView.findViewById(R.id.timestamp);
}
}
private void saveTimestamp() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Map map = new HashMap();
map.put("timestamp", ServerValue.TIMESTAMP);
reference.child("Posts").updateChildren(map);
}
private void setupWidgets() {
String timestampDifference = getTimestampDifference();
if (!timestampDifference.equals("0")) {
**timestamp.setText(timestampDifference + " days ago");
} else {
**timestamp.setText("Today");
}
}
//Timestamp
private String getTimestampDifference() {
String difference = "";
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
Date today = calendar.getTime();
simpleDateFormat.format(today);
Date timestamp;
final String dateTime = simpleDateFormat.format(calendar.getTime());
try {
timestamp = simpleDateFormat.parse(dateTime);
difference = String.valueOf(Math.round(((today.getTime() - timestamp.getTime()) / 1000 / 60 / 60 / 24)));
} catch (ParseException e) {
difference = "0";
}
return difference;
}
post_item.xml
<TextView
android:id="#+id/timestamp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/description"
android:layout_marginStart="10dp"
android:layout_marginBottom="10dp"
android:text="Have to add a Timestamp" />
PostAdapter.java
package com.e.events.Adapter;
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
public Context mContext;
public List<Post> mPost;
private FirebaseUser firebaseUser;
public PostAdapter(Context mContext, List<Post> mPost) {
this.mContext = mContext;
this.mPost = mPost;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.post_item, parent, false);
return new PostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final Post post = mPost.get(position);
Glide.with(mContext).load(post.getPostimage())
.apply(new RequestOptions().placeholder(R.drawable.placeholderimg))
.into(holder.post_image);
if ("".equals(post.getDescription())) {
holder.description.setVisibility(View.GONE);
} else {
holder.description.setVisibility(View.VISIBLE);
holder.description.setText(post.getDescription());
}
if ("".equals(post.getText_event())) {
holder.text_event.setVisibility(View.GONE);
} else {
holder.text_event.setVisibility(View.VISIBLE);
holder.text_event.setText(post.getText_event());
}
if ("".equals(post.getText_location())) {
holder.text_location.setVisibility(View.GONE);
} else {
holder.text_location.setVisibility(View.VISIBLE);
holder.text_location.setText(post.getText_location());
}
if ("".equals(post.getText_date_time())) {
holder.text_date_time.setVisibility(View.GONE);
} else {
holder.text_date_time.setVisibility(View.VISIBLE);
holder.text_date_time.setText(post.getText_date_time());
}
publisherInfo(holder.image_profile, holder.username, post.getPublisher());
eventLiked(post.getPostid(), holder.like);
number_of_likes(holder.number_of_likes, post.getPostid());
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.like.getTag().equals("like")) {
FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid())
.child(firebaseUser.getUid()).setValue(true);
addNotification(post.getPublisher(), post.getPostid());
} else {
FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid())
.child(firebaseUser.getUid()).removeValue();
}
}
});
publisherInfo(holder.image_profile, holder.username, post.getPublisher());
attending_event(post.getPostid(), holder.attend_event);
number_of_people_attending_event(holder.number_of_people_attending_event, post.getPostid());
getComments(post.getPostid(), holder.number_of_comments);
isSaved(post.getPostid(), holder.save_event);
holder.attend_event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.attend_event.getTag().equals("attend_event")) {
FirebaseDatabase.getInstance().getReference().child("Attending Event").child(firebaseUser.getUid())
.child(post.getPostid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Attending Event").child(firebaseUser.getUid())
.child(post.getPostid()).removeValue();
}
}
});
holder.image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("profileid", post.getPublisher());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("profileid", post.getPublisher());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("postid", post.getPostid());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new PostDetailFragment()).commit();
}
});
holder.save_event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.save_event.getTag().equals("save")) {
FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid())
.child(post.getPostid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid())
.child(post.getPostid()).removeValue();
}
}
});
holder.attend_event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.attend_event.getTag().equals("attend event")) {
FirebaseDatabase.getInstance().getReference().child("Attending Event").child(post.getPostid())
.child(firebaseUser.getUid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Attending Event").child(post.getPostid())
.child(firebaseUser.getUid()).removeValue();
}
}
});
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, CommentsActivity.class);
intent.putExtra("postid", post.getPostid());
intent.putExtra("publisherid", post.getPublisher());
mContext.startActivity(intent);
}
});
holder.number_of_comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, CommentsActivity.class);
intent.putExtra("postid", post.getPostid());
intent.putExtra("publisherid", post.getPublisher());
mContext.startActivity(intent);
}
});
holder.number_of_likes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, FollowersActivity.class);
intent.putExtra("id", post.getPostid());
intent.putExtra("title", "likes");
mContext.startActivity(intent);
}
});
holder.more_options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(mContext, v);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.edit_event:
editPost(post.getPostid());
return true;
case R.id.delete_event:
FirebaseDatabase.getInstance().getReference("Posts").child(post.getPostid()).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(mContext, "Event deleted", Toast.LENGTH_SHORT).show();
}
}
});
return true;
case R.id.report_event:
Toast.makeText(mContext, "Event has been reported", Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
});
popupMenu.inflate(R.menu.event_menu);
if (!post.getPublisher().equals(firebaseUser.getUid())) {
popupMenu.getMenu().findItem(R.id.edit_event).setVisible(false);
popupMenu.getMenu().findItem(R.id.delete_event).setVisible(false);
}
popupMenu.show();
}
});
}
#Override
public int getItemCount() {
if (mPost != null) {
return mPost.size();
} else {
return 0;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile, post_image, like, comment, attend_event, save_event, more_options;
public TextView username, number_of_likes, description, number_of_comments, text_event, text_location, text_date_time,
number_of_people_attending_event, timestamp;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image_profile = itemView.findViewById(R.id.image_profile);
post_image = itemView.findViewById(R.id.post_image);
like = itemView.findViewById(R.id.like);
comment = itemView.findViewById(R.id.comment);
username = itemView.findViewById(R.id.username);
number_of_likes = itemView.findViewById(R.id.number_of_likes);
description = itemView.findViewById(R.id.description);
number_of_comments = itemView.findViewById(R.id.number_of_comments);
text_event = itemView.findViewById(R.id.text_event);
text_location = itemView.findViewById(R.id.text_location);
text_date_time = itemView.findViewById(R.id.text_date_time);
attend_event = itemView.findViewById(R.id.attend_event);
number_of_people_attending_event = itemView.findViewById(R.id.number_of_people_attending_event);
save_event = itemView.findViewById(R.id.save_event);
more_options = itemView.findViewById(R.id.more_options);
timestamp = itemView.findViewById(R.id.timestamp);
}
}
private void saveTimestamp() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Map map = new HashMap();
map.put("timestamp", ServerValue.TIMESTAMP);
reference.child("Posts").updateChildren(map);
}
//Set words for the timestamp "Today" or "___ days ago"
private void setupWidgets() {
String timestampDifference = getTimestampDifference();
if (!timestampDifference.equals("0")) {
timestamp.setText(timestampDifference + " days ago");
} else {
timestamp.setText("Today");
}
}
//Timestamp
private String getTimestampDifference() {
Log.d(TAG, "getTimestampDifference: getting timestamp difference");
String difference = "";
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss", Locale.US);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
Date today = calendar.getTime();
simpleDateFormat.format(today);
Date timestamp;
final String dateTime = simpleDateFormat.format(calendar.getTime());
try {
timestamp = simpleDateFormat.parse(dateTime);
difference = String.valueOf(Math.round(((today.getTime() - timestamp.getTime()) / 1000 / 60 / 60 / 24)));
} catch (ParseException e) {
difference = "0";
}
return difference;
}
private void getComments(String postid, final TextView comments) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Comments").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
comments.setText(dataSnapshot.getChildrenCount() + "");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void eventLiked(String postid, final ImageView imageView) {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(firebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.ic_event_liked_aqua_fill);
imageView.setTag("liked");
} else {
imageView.setImageResource(R.drawable.ic_favorite_heart_hollow);
imageView.setTag("like");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void addNotification(final String userid, final String postid) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications").child(userid);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("userid", firebaseUser.getUid());
hashMap.put("comment", "liked your Event");
hashMap.put("postid", postid);
hashMap.put("ispost", true);
reference.push().setValue(hashMap);
}
private void number_of_likes(final TextView likes, String postid) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
likes.setText(dataSnapshot.getChildrenCount() + "");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void attending_event(String postid, final ImageView imageView) {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Attending Event").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(firebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.ic_person_attending_event_light_green);
imageView.setTag("attending event");
} else {
imageView.setImageResource(R.drawable.ic_person_plus_black_attend_event);
imageView.setTag("attend event");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void number_of_people_attending_event(final TextView number_of_people, String postid) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Attending Event").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
number_of_people.setText(dataSnapshot.getChildrenCount() + "");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void publisherInfo(final ImageView image_profile, final TextView username, String userid) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
Glide.with(mContext).load(user.getImageurl()).into(image_profile);
username.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void isSaved(final String postid, final ImageView imageView) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(postid).exists()) {
imageView.setImageResource(R.drawable.ic_bookmark_darker_version);
imageView.setTag("saved");
} else {
imageView.setImageResource(R.drawable.ic_save_hollow);
imageView.setTag("save");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
//Editing Event
private void editPost(final String postid) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Edit Event");
final EditText editText = new EditText(mContext);
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
editText.setLayoutParams(linearLayoutParams);
alertDialog.setView(editText);
getText(postid, editText);
alertDialog.setPositiveButton("Edit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("description", editText.getText().toString());
FirebaseDatabase.getInstance().getReference("Posts")
.child(postid).updateChildren(hashMap);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void getText(String postid, final EditText editText) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts").child(postid);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
editText.setText(dataSnapshot.getValue(Post.class).getDescription());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
[![screenshot_timestamp][1]][1]
[1]: https://i.stack.imgur.com/TZfI7.png

You are getting that error because you are trying to use a variable that has no visibility in setupWidgets() method. Your timestamp variable is visible only inside your ViewHolder class. That's its scope. See, you can use that variable only in the constructor you cannot use outside the class. To solve this, you either move those metods inside your ViewHolder class or you pass it as an argument when calling them.

Related

Sub total of recycler view nodes keeps increasing in android app

MY ORIGINAL QUESTION
I am making an android app with firebase Realtime database. I am getting sum of the firebase nodes in side recycler view. I have a text view out side the recycler view where I am getting the sub total of the values of the recycler view. MY PROBLEM is that I cannot get the actual sum and also the sum keeps increasing when I scroll up and down. Here is my Main activity JAVA code:
public class MainActivity extends AppCompatActivity {
FirebaseDatabase myfire;
DatabaseReference myRef;
private FirebaseRecyclerOptions<entry> options;
int totalEarned = 0;
int totalSpent = 0;
int totalSaved=0;
#Override
public void onBackPressed() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("Are you sure to exit?");
dialog.setPositiveButton("Play", (dialog1, which) -> {
});
dialog.setNegativeButton("Exit", (dialog12, which) -> {
FirebaseAuth.getInstance().signOut();
MainActivity.this.finish();
});
dialog.show();
}
private String getUID() {
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
if (mUser != null) {
String strUID = mUser.getUid();
if (!TextUtils.isEmpty(strUID)) {
return strUID;
}
}
return "";
}
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//==============
final RecyclerView userlist = (RecyclerView) findViewById(R.id.idRecycleView);
myfire = FirebaseDatabase.getInstance();
userlist.setLayoutManager(new LinearLayoutManager(this));
//==================
final TextView tvTotalIncome = findViewById(R.id.idTotalIncome);
final TextView tvTotalExpanse = findViewById(R.id.idTotalExpanse);
final TextView tvTotalSaved = findViewById(R.id.idTotalSaved);
//==================
final FloatingActionButton btnBudget = findViewById(R.id.idCreateBudget);
myfire = FirebaseDatabase.getInstance();
final String strUID = getUID();
if (TextUtils.isEmpty(strUID)) {
//handle case of null UID
}
final Intent i = getIntent();
final String month = Objects.requireNonNull(i.getExtras()).getString("Month");
//-------------------------------
btnBudget.setOnClickListener(v -> {
Intent o;
o = new Intent(MainActivity.this, AddBudgetActivity.class);
o.putExtra("Month",month);
startActivity(o);
finish();
});
if (type.equals("Income")) {
try {
totalEarned = (totalEarned+sum);
} catch (NumberFormatException ex) {
}
tvTotalIncome.setText("-)"+String.valueOf( totalEarned));
holder.btnIcon.setBackgroundResource(R.drawable.circlegreen);
holder.tvEntry.setText("(+)"+String.valueOf(sum) );
try {
totalSaved = (totalEarned-totalSpent);
} catch (NumberFormatException ex) {
}
tvTotalSaved.setText("(=)"+String.valueOf( totalSaved));
}else if (type.equals("Expanse")) {
try {
totalSpent = (totalSpent+sum);
} catch (NumberFormatException ex) {
}
tvTotalExpanse.setText("-)"+String.valueOf( totalSpent));
holder.btnIcon.setBackgroundResource(R.drawable.circlered);
holder.tvEntry.setText("(-)"+String.valueOf(sum) );
try {
totalSaved = (totalEarned-totalSpent);
} catch (NumberFormatException ex) {
}
tvTotalSaved.setText("(=)"+String.valueOf( totalSaved));
}else {
Toast.makeText(MainActivity.this, " Something Went Wrong !", Toast.LENGTH_SHORT).show();
}
//======================
myRef = myfire.getReference().child("Data").child(strUID).child(month);
//-------------------------
options = new FirebaseRecyclerOptions.Builder<entry>()
.setQuery(myRef, entry.class)
.build();
final FirebaseRecyclerAdapter<entry, holder_menu> adapter = new FirebaseRecyclerAdapter<entry, holder_menu>(options) {
#Override
protected void onBindViewHolder(#NonNull #NotNull holder_menu holder, final int i, #NonNull #NotNull entry model) {
final String title = getRef(i).getKey();
assert title != null;
myRef = myfire.getReference().child("Data").child(strUID).child(month).child(title).child("Budget");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int budget = 0;
if (dataSnapshot.getValue() == null) {
Toast.makeText(getApplicationContext(), "Data Not Available", Toast.LENGTH_LONG).show();
} else {
final String stData1 = (Objects.requireNonNull(dataSnapshot.child("stData1").getValue())).toString();
final String stData2 = (Objects.requireNonNull(dataSnapshot.child("stData2").getValue())).toString();
final String stData3 = (Objects.requireNonNull(dataSnapshot.child("stData3").getValue())).toString();
final String stData4 = (Objects.requireNonNull(dataSnapshot.child("stData4").getValue())).toString();
entry basic = new entry(stData1, stData2, stData3, stData4);
String first = stData2.substring(0, 1);
holder.btnIcon.setText(first);
holder.tvHead.setText(stData2);
String type;
type=(stData3);
holder.tvBudget.setText("#" + stData4);
int amount = 0;
//important line
try {
amount = (Integer.parseInt(stData4));
} catch (NumberFormatException ex) {
}
//======================
budget = amount;
myRef = myfire.getReference().child("Data").child(strUID).child(month).child(title).child("Entry");
final int finalBudget = budget;
myRef.addValueEventListener(new ValueEventListener() {
int sum = 0;
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String section = data.child("stData2").getValue(String.class);
String value = data.child("stData4").getValue(String.class);
assert value != null;
int total = 0;
//important line
try {
total = (Integer.parseInt(value));
} catch (NumberFormatException ex) {
}
//======================
sum = sum + total;
//==============
//======================
if (section.equals("Saving")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.saving));
}else if (section.equals("Paying")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.paying));
}else if (section.equals("Using")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.using));
}else if (section.equals("Earning")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.earning));
}else if (section.equals("Taking")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.taking));
}else if (section.equals("Drawing")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.drawing));
}else {
Toast.makeText(MainActivity.this, " Something Went Wrong !", Toast.LENGTH_SHORT).show();
}
}
holder.tvEntry.setText("(+)" + String.valueOf(sum) );
holder.tvBalance.setText("(=)" + String.valueOf(finalBudget - sum) );
//important line
holder.btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent o;
o = new Intent(MainActivity.this, ViewHistoryActivity.class);
o.putExtra("Title", title);
o.putExtra("Month", month);
o.putExtra("Type", type);
startActivity(o);
finish();
}
});
holder.btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (type.equals("Income")) {
Intent o;
o = new Intent(MainActivity.this, EntryIncomeActivity.class);
o.putExtra("Title", title);
o.putExtra("Month", month);
o.putExtra("Type", type);
startActivity(o);
finish();
}else if (type.equals("Expanse")) {
Intent o;
o = new Intent(MainActivity.this, EntryExpanseActivity.class);
o.putExtra("Title", title);
o.putExtra("Month", month);
o.putExtra("Type", type);
startActivity(o);
finish();
}else {
Toast.makeText(MainActivity.this, " Something Went Wrong !", Toast.LENGTH_SHORT).show();
}
}
});
if (type.equals("Income")) {
try {
totalEarned = (totalEarned+sum);
} catch (NumberFormatException ex) {
}
tvTotalIncome.setText("-)"+String.valueOf( totalEarned));
holder.btnIcon.setBackgroundResource(R.drawable.circlegreen);
holder.tvEntry.setText("(+)"+String.valueOf(sum) );
try {
totalSaved = (totalEarned-totalSpent);
} catch (NumberFormatException ex) {
}
tvTotalSaved.setText("(=)"+String.valueOf( totalSaved));
}else if (type.equals("Expanse")) {
try {
totalSpent = (totalSpent+sum);
} catch (NumberFormatException ex) {
}
tvTotalExpanse.setText("-)"+String.valueOf( totalSpent));
holder.btnIcon.setBackgroundResource(R.drawable.circlered);
holder.tvEntry.setText("(-)"+String.valueOf(sum) );
try {
totalSaved = (totalEarned-totalSpent);
} catch (NumberFormatException ex) {
}
tvTotalSaved.setText("(=)"+String.valueOf( totalSaved));
}else {
Toast.makeText(MainActivity.this, " Something Went Wrong !", Toast.LENGTH_SHORT).show();
}
//======================
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
}
#NonNull
#Override
public holder_menu onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item1, parent, false);
return new holder_menu(v);
}
};
adapter.startListening();
userlist.setAdapter(adapter);
}
}
EDITED QUESTION As per #androidLearner 's suggestion
MAIN ACTIVITY
public class MainActivity extends AppCompatActivity {
FirebaseDatabase myfire;
DatabaseReference myRef;
int totalEarned = 0;
int totalSpent = 0;
int totalSaved=0;
madapter adapter;
String iconsData;
String headsData;
int budgetsData=0;
int enteriesData=0;
int balancesData=0;
#Override
public void onBackPressed() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("Are you sure to exit?");
dialog.setPositiveButton("Play", (dialog1, which) -> {
});
dialog.setNegativeButton("Exit", (dialog12, which) -> {
FirebaseAuth.getInstance().signOut();
MainActivity.this.finish();
});
dialog.show();
}
private String getUID() {
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
if (mUser != null) {
String strUID = mUser.getUid();
if (!TextUtils.isEmpty(strUID)) {
return strUID;
}
}
return "";
}
#RequiresApi(api = Build.VERSION_CODES.N)
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//==============
final RecyclerView userlist = (RecyclerView) findViewById(R.id.idRecycleView);
myfire = FirebaseDatabase.getInstance();
userlist.setLayoutManager(new LinearLayoutManager(this));
//==================
final TextView tvTotalIncome = findViewById(R.id.idTotalIncome);
final TextView tvTotalExpanse = findViewById(R.id.idTotalExpanse);
final TextView tvTotalSaved = findViewById(R.id.idTotalSaved);
//==================
final FloatingActionButton btnBudget = findViewById(R.id.idCreateBudget);
myfire = FirebaseDatabase.getInstance();
final String strUID = getUID();
if (TextUtils.isEmpty(strUID)) {
//handle case of null UID
}
final Intent i = getIntent();
final String month = Objects.requireNonNull(i.getExtras()).getString("Month");
//-------------------------------
btnBudget.setOnClickListener(v -> {
Intent o;
o = new Intent(MainActivity.this, AddBudgetActivity.class);
o.putExtra("Month",month);
startActivity(o);
finish();
});
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&---new method
myRef = myfire.getReference().child("Data").child(strUID).child(month);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String title = dataSnapshot.getKey();
assert title != null;
myRef = myfire.getReference().child("Data").child(strUID).child(month).child(title).child("Budget");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
Toast.makeText(getApplicationContext(), "Data Not Available", Toast.LENGTH_LONG).show();
} else {
final String stData1 = (Objects.requireNonNull(dataSnapshot.child("stData1").getValue())).toString();
final String stData2 = (Objects.requireNonNull(dataSnapshot.child("stData2").getValue())).toString();
final String stData3 = (Objects.requireNonNull(dataSnapshot.child("stData3").getValue())).toString();
final String stData4 = (Objects.requireNonNull(dataSnapshot.child("stData4").getValue())).toString();
entry basic = new entry(stData1, stData2, stData3, stData4);
iconsData = stData2.substring(0, 1);
headsData=stData2;
//---------------------------------------------------------------------------entry
myRef = myfire.getReference().child("Data").child(strUID).child(month).child(title).child("Entry");
myRef.addValueEventListener(new ValueEventListener() {
int sum = 0;
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String section = data.child("stData2").getValue(String.class);
String value = data.child("stData4").getValue(String.class);
assert value != null;
int total = 0;
try {
total=(Integer.parseInt(value));
} catch (NumberFormatException ex) {
}
//==============
sum=sum+total;
}
enteriesData=sum;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&------NewMethod
balancesData=budgetsData-enteriesData;
ArrayList<String> iconList = new ArrayList<>();
iconList.add(iconsData);
ArrayList<String> headList= new ArrayList<>();
headList.add(headsData);
ArrayList<Integer> budgetList = new ArrayList<>();
budgetList.add(budgetsData);
ArrayList<Integer> entryList = new ArrayList<>();
entryList.add(enteriesData);
ArrayList<Integer> balanceList = new ArrayList<>();
balanceList.add(balancesData);
adapter = new madapter ( this, iconList,headList,budgetList,entryList,balanceList);
userlist.setAdapter(adapter);
}
}
RECYCLER VIEW Adapter
public class madapter extends RecyclerView.Adapter<madapter.ViewHolder> {
private List<String> stricon;
private List<String> strhead;
private List<Integer> intbudget;
private List<Integer> intentry;
private List<Integer> intbalance;
//---
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public madapter(MainActivity mainActivity, ArrayList<String> iconList, ArrayList<String> headList, ArrayList<Integer> budgetList, ArrayList<Integer> entryList, ArrayList<Integer> balanceList) {
this.mInflater = LayoutInflater.from(mainActivity);
this.stricon = iconList;
this.strhead = headList;
this.intbudget = budgetList;
this.intentry = entryList;
this.intbalance= balanceList;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.item1, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String icons = stricon.get(position);
String heads = strhead.get(position);
int budgets = intbudget.get(position);
int entries = intentry.get(position);
int balances = intbalance.get(position);
holder.btnIcon.setText(icons);
holder.tvHead.setText(heads);
holder.tvBudget.setText(String.valueOf(budgets));
holder.tvEntry.setText(String.valueOf(entries));
holder.tvBalance.setText(String.valueOf(balances));
}
// total number of rows
#Override
public int getItemCount() {
return stricon.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public Button btnIcon;
public TextView tvHead;
public TextView tvBudget;
public TextView tvEntry;
public TextView tvBalance;
public Button btnView;
public Button btnAdd;
ViewHolder(View itemView) {
super(itemView);
btnIcon= (Button) itemView.findViewById(R.id.idIcon);
tvHead = (TextView) itemView.findViewById(R.id.idHead);
tvBudget = (TextView) itemView.findViewById(R.id.idBudget);
tvEntry = (TextView) itemView.findViewById(R.id.idEntry);
tvBalance = (TextView) itemView.findViewById(R.id.idBalance);
btnView= (Button) itemView.findViewById(R.id.idView);
btnAdd = (Button) itemView.findViewById(R.id.idAdd);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
String getItem(int id) {
return stricon.get(id);
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
THE NEW PROBLEM AFTER EDITING
I am not able to get any data from firebase to my array list by the method datasnapshot. But yes my recycler view shows data if I add hardcore text or numbers to my list manually.
This is the crash report
2021-05-24 00:07:12.368 19933-19933/com.myappname E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myappname, PID: 19933
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.get(ArrayList.java:437)
at com.myappname.model.rvAdapter.onBindViewHolder(mAdapter.java:54)
at com.myappname.model.rvAdapter.onBindViewHolder(mAdapter.java:16)2021-05-24 .......................................
set Adapter after got data from firebase
myRef.addValueEventListener(new ValueEventListener() {
int sum = 0;
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String section = data.child("stData2").getValue(String.class);
String value = data.child("stData4").getValue(String.class);
assert value != null;
int total = 0;
//==============
sum=sum+total;
}
enteriesData=sum;
//Send your data to adapter as per your need from here
adapter = new madapter ( this, iconList,headList,budgetList,entryList,balanceList);
userlist.setAdapter(adapter);
}

Why counter just increase to 1 in firebase?

im trying to increase a visitor counter views when access to read a message, so i made a method called incrementar () and set it where i retrieve info when someone click to open that post. But i dont know why only increase to 1 view in firebase, if i click again it does not increase. should use shared preferences? or there is an other method to increase a counter from firebase?
int views;
int score;
int increment = +1;
DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
setTitle("Chatroom");
threadNameTV = findViewById(R.id.threadNameTV);
newMessageET = findViewById(R.id.newMessageET);
homeButton = findViewById(R.id.homeButton);
sendButton = findViewById(R.id.sendButton);
messagesLV = findViewById(R.id.messagesLV);
final View messageview = getLayoutInflater().inflate(R.layout.messages_listview, null);
messageTV = messageview.findViewById(R.id.messageTV);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
user = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference();
firebaseUser = mAuth.getCurrentUser();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profileimage");
threadNameTV.setTextColor(Color.parseColor("#000000"));
if (getIntent() != null && getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey("messageThreadDetails")) {
messageThread = (MessageThread) getIntent().getSerializableExtra("messageThreadDetails");
threadNameTV.setText(messageThread.title);
getMessages(messageThread.thread_id);
incrementar();
}
} else {
Toast.makeText(this, "No data received", Toast.LENGTH_SHORT).show();
}
homeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (user != null) {
user = null;
mDatabase = null;
mAuth = null;
Intent intent = new Intent(ChatActivity.this, ThreadsActivity.class);
startActivity(intent);
finish();
} else {
user = null;
mDatabase = null;
mAuth = null;
Toast.makeText(ChatActivity.this, "You need to login", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ChatActivity.this, IniciarSesion.class);
startActivity(intent);
finish();
}
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = newMessageET.getText().toString();
String user_name = user.getDisplayName();
String profileimage = user.getPhotoUrl().toString();
if (message.isEmpty()) {
Toast.makeText(ChatActivity.this, "Enter Message", Toast.LENGTH_SHORT).show();
} else {
addMessage(message, user_name, profileimage, messageThread.thread_id);
}
}
});
}
public void addMessage(String message, String user_name, String profileimage, String thread_id) {
if (user != null) {
mDatabase.child("Normas").child(thread_id).child("messages").push().setValue(new Message(message, user.getUid(), user_name, profileimage, new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.US).format(new Date())));
newMessageET.setText("");
} else {
Toast.makeText(this, "No user logged in", Toast.LENGTH_SHORT).show();
}
}
public void getMessages(String thread_id) {
mDatabase.child("Normas").child(thread_id).child("messages").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
messagesList.clear();
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
Message message = messageSnapshot.getValue(Message.class);
if (message != null) {
message.message_id = messageSnapshot.getKey();
Log.d(TAG, "onDataChange: " + message.toString());
}
messagesList.add(message);
}
messagesAdapter = new MessagesAdapter(ChatActivity.this, R.layout.threads_listview, messagesList, ChatActivity.this);
messagesLV.setAdapter(messagesAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ChatActivity.this, "ChatActivity: " + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void deleteMessage(String message_id) {
mDatabase.child("Normas").child(messageThread.thread_id).child("messages").child(message_id).removeValue();
}
public void setimage() {
UsersRef.child(currentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NotNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("profileimage")) {
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(ChatActivity.this).load(image).placeholder(R.drawable.profilefoto).into(fotoforos);
}
}
}
#Override
public void onCancelled(#NotNull DatabaseError error) {
}
});
}
public void incrementar() {
FirebaseDatabase.getInstance().getReference().child("Normas").child(messageThread.thread_id).child("views").setValue(increment);
}
}
Thanks so much
You're setting +1 as the value each time you call:
int increment = +1;
FirebaseDatabase.getInstance().getReference().child("Normas")
.child(messageThread.thread_id).child("views").setValue(increment);
What would work is:
FirebaseDatabase.getInstance().getReference().child("Normas")
.child(messageThread.thread_id).child("views").setValue(ServerValue.increment(1));
Instead of sending the literal value 1, this second snippet sends an instruction to increment the current value by 1.

How to retrieve latest entry from the firebase realtime database?

I am trying to take inputs from one user and send the same data to another user. I am not sure what to put as an argument in child so that it refers to the same data and I can retrieve and show the data to another user for approval. I am able to send the image but for the data fields like visitor,mobile and flat not sure what to do.
My code is as follows.
Data entry File Code
public class Main4Activity extends AppCompatActivity {
private static final int PERMISSION_CODE = 1000;
private static final int IMAGE_CAPTURE_CODE = 1001;
Button btn;
ImageView imageView;
static Uri image_uri;
ImageView mImageView;
TextView mCaptureBtn;
Button uploadbtn;
static String downloadurl;
public static String Dvisitor;
public static String Dmobile;
static DatabaseReference reff;
//for upload
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;
FirebaseStorage storage;
StorageReference storageReference;
//for upload
static String URL;
//Data store of Visitor
static EditText visitor;
static EditText mbnumber;
EditText bnmbr;
static EditText fnmbr;
EditText emal;
EditText pswrd;
HashMap<String,Object> map = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
//for upload
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
//for upload
mImageView = (ImageView) findViewById(R.id.imageView2);
mCaptureBtn = (TextView) findViewById(R.id.textView4);
//Data for Visitor
visitor = (EditText) findViewById(R.id.vname);
mbnumber = (EditText) findViewById(R.id.mnumber);
bnmbr = (EditText) findViewById(R.id.blknmbr);
fnmbr = (EditText) findViewById(R.id.fltnmbr);
emal = (EditText) findViewById(R.id.emailId);
pswrd = (EditText) findViewById(R.id.passwordfield2);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
upload();
FirebaseDatabase.getInstance().getReference().child("Image").push().setValue(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
map.put("visitor",visitor.getText().toString());
map.put("mobile",mbnumber.getText().toString());
map.put("block",bnmbr.getText().toString());
map.put("flat",fnmbr.getText().toString());
map.put("email",emal.getText().toString());
map.put("password",pswrd.getText().toString());
Toast.makeText(Main4Activity.this, "Successful data registration", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Main4Activity.this, "Failed data registration", Toast.LENGTH_SHORT).show();
}
});
}
});
//Camera functionality click and upload starts
mCaptureBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
String[] permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permission, PERMISSION_CODE);
} else {
openCamera();
}
} else {
openCamera();
}
}
});
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main4Activity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void openCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE);
{
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
mImageView.setImageURI(image_uri);
}
}
private void upload(){
if(image_uri != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(image_uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Main4Activity.this, "Uploaded", Toast.LENGTH_SHORT).show();
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
DatabaseReference imagestore = FirebaseDatabase.getInstance().getReference().child("Image").push();
//HashMap<String, String> hasmap = new HashMap<>();
URL = uri.toString();
map.put("imgurl",URL);
//map.put("imageurl", String.valueOf(uri));
imagestore.setValue(map).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Intent intent= new Intent(Main4Activity.this,Main5Activity.class);
startActivity(intent);
}
});
//This is your image url do whatever you want with it.
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Main4Activity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
}
}
}
//Camera functionality click and upload starts
Code for another user to Approve
public class Main5Activity extends AppCompatActivity {
Button btnAllow, btnProhibit;
private String Dvisitor;
private String Dmobile;
private String Dflat;
DatabaseReference reff;
ImageView img;
private DatabaseReference Post;
static TextView textView;
String roadies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
btnAllow = (Button) findViewById(R.id.button);
btnProhibit = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView5);
img = (ImageView) findViewById(R.id.imageView3);
imageshow();
init();
readonetime();
}
private void readonetime() {
Query query = Post.orderByKey().limitToLast(1);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot child: dataSnapshot.getChildren()) {
String post = dataSnapshot.child("visitor").getValue(String.class);
String post1 = dataSnapshot.child("mobile").getValue(String.class);
String post2 = dataSnapshot.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void init() {
Post = FirebaseDatabase.getInstance().getReference().child("Image");
}
private void imageshow() {
reff = FirebaseDatabase.getInstance().getReference().child("Image");
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Picasso.get().load(Main4Activity.URL).fit().into(img);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Main5Activity.this, "OoooooLalalala", Toast.LENGTH_SHORT).show();
}
});
btnAllow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main5Activity.this, Main8Activity.class);
startActivity(intent);
}
});
btnProhibit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main5Activity.this, Main9Activity.class);
startActivity(intent);
}
});
}
}
In your Main5Activity, I think:
This:
for(DataSnapshot child: dataSnapshot.getChildren()) {
String post = dataSnapshot.child("visitor").getValue(String.class);
String post1 = dataSnapshot.child("mobile").getValue(String.class);
String post2 = dataSnapshot.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
Must be like this:
for(DataSnapshot ds: dataSnapshot.getChildren()) {
String post = ds.child("visitor").getValue(String.class);
String post1 = ds.child("mobile").getValue(String.class);
String post2 = ds.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}

First and last switch button getting triggred in recycler view

Hi I have switch button (switchTaskFinished) on my recycler view,when I am clicking any button, the last button is getting selected. Also when I press button it updates the data to firebase. And changes the button status accordingly. But even though buttons value is true it only updates last button status not others.
public class MyAdaptorUser extends RecyclerView.Adapter<MyAdaptorUser.myViewHolder> {
private Context context;
private ArrayList<TaskModel> taskLists;
private Switch switchTaskFinished;
private OnTaskClickListner mTaskListner;
private AlertDialog dialog;
private AlertDialog.Builder builder;
private TaskConfirmationSender taskConfirmationSender;
public MyAdaptorUser(Context c, ArrayList<TaskModel> t, OnTaskClickListner onTaskClickListner) {
context = c;
taskLists = t;
this.mTaskListner = onTaskClickListner;
}
#NonNull
#Override
public MyAdaptorUser.myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
builder = new AlertDialog.Builder(parent.getContext());
builder.setTitle("Please Wait").setView(R.layout.my_progress_view).setCancelable(false);
dialog = builder.create();
return new MyAdaptorUser.myViewHolder(LayoutInflater.from(context).inflate(R.layout.task_preview, parent, false), mTaskListner);
}
#Override
public void onBindViewHolder(#NonNull MyAdaptorUser.myViewHolder holder, final int position) {
//Set title and description to task preview textviews
holder.title.setText(taskLists.get(position).getTaskTitle());
holder.dueDate.setText(taskLists.get(position).getDueDate());
holder.description.setText(taskLists.get(position).getTaskDescription());
//Sets the path of database to taskAwatingConfirmation/task_title/UserEmail
final DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
try {
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
email = removeSpecialCharacter(email);
final DatabaseReference taskConfirmationRef = dbRef
.child("taskAwatingConfirmation")
.child(taskLists.get(position).getTaskTitle())
.child(email);
taskConfirmationRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Fetching switchButton Status (Task finished) from database
switchTaskFinished.setChecked(false);
String buttonStatus = (String) dataSnapshot.child("buttonStatus").getValue();
if (buttonStatus != null) {
Log.d("taskerror", buttonStatus);
if (buttonStatus.equals("true")) {
switchTaskFinished.setChecked(true);
} else if (buttonStatus.equals("false")) {
switchTaskFinished.setChecked(false);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
switchTaskFinished.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
//dialog = builder.show();
taskConfirmationSender = new TaskConfirmationSender();
//When Task Finished button is clicked send data to database
sendConfirmationToAdmin(new FirebaseCallBack() {
#Override
public void Callback(TaskConfirmationSender taskConfirmationSender) {
taskConfirmationSender.setButtonStatus(String.valueOf(buttonView.isChecked()));
taskConfirmationSender.setTaskDueDate(taskLists.get(position).getDueDate());
if (buttonView.isChecked()) {
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}else{
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}
}
});
}
});
} catch (NullPointerException ignored) {
dialog.dismiss();
}
}
private String removeSpecialCharacter(String email) {
StringBuffer sbf = new StringBuffer(email);
email = String.valueOf(sbf.reverse());
int length = email.length();
email = email.substring(4, length);
StringBuffer stringBuffer = new StringBuffer(email);
email = String.valueOf(stringBuffer.reverse());
return email.replace("#", "_");
}
private void sendConfirmationToAdmin(final FirebaseCallBack firebaseCallBack) {
DatabaseReference volunteerRef = FirebaseDatabase.getInstance().getReference()
.child("Volunteer").child("Member")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
taskConfirmationSender = new TaskConfirmationSender();
try {
//Fetching details of users (full name, email) from database and setting their value to taskConfirmation Object
volunteerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("fullName").getValue().toString();
String userEmail = dataSnapshot.child("email").getValue().toString();
String userId = dataSnapshot.getKey();
//TODO: Fetch UID of user and set it to taskConfirmation OBject
taskConfirmationSender.setUserEmail(userEmail);
taskConfirmationSender.setUserName(userName);
taskConfirmationSender.setId(userId);
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
String submissionDate = day + "/" + month + "/" + year;
taskConfirmationSender.setSubmissionDate(submissionDate);
firebaseCallBack.Callback(taskConfirmationSender);
/**/
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} catch (NullPointerException ee) {
}
}
private interface FirebaseCallBack {
void Callback(TaskConfirmationSender taskConfirmationSender);
}
#Override
public int getItemCount() {
return taskLists.size();
}
class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, dueDate, description;
OnTaskClickListner onTaskClickListner;
public myViewHolder(#NonNull View itemView, OnTaskClickListner onTaskClickListner) {
super(itemView);
title = itemView.findViewById(R.id.taskTitle);
dueDate = itemView.findViewById(R.id.taskDueDate);
description = itemView.findViewById(R.id.taskDescription);
switchTaskFinished = itemView.findViewById(R.id.switchTaskFinished);
this.onTaskClickListner = onTaskClickListner;
ConstraintLayout taskBar = itemView.findViewById(R.id.linearLayoutTaskBar);
itemView.setOnClickListener(this);
//hides delete task button
taskBar.setVisibility(View.GONE);
}
#Override
public void onClick(View v) {
onTaskClickListner.onTaskClick(getAdapterPosition());
}
}
public interface OnTaskClickListner {
void onTaskClick(int position);
}
}
Maybe its because of the valueEventListener that stays attached:
Instead of this:
taskConfirmationRef.addValueEventListener(new ValueEventListener() {.........
Do this:
taskConfirmationRef.addListenerForSingleValueEvent(new ValueEventListener() {......
And set the switch to checked or unchecked when you turn on or off:
if (buttonView.isChecked()) {
//here
switchTaskFinished.setChecked(true);
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}else{
//here
switchTaskFinished.setChecked(false);
...................

My app keeps jumping back to an activity when there is a new node in Firebase and Android

I am new to Android and just published my app, the app is called random chat and its basically a chat application. So in order to record all of the user's names I used firebase real-time database. I have stored all of the User's data in a child in firebase called Usernames, in which the child of each User is stored with the user's UID (Obtained from Firebase Auth) as the main name and it has two children: name (which stores the name of the user) and phone (which stores the phone number of the user).
The problem is that in my app, every time a new user signs up, the app automatically switched from its current activity to a profile activity. I really don't understand why its happening, I thought it might be because the event listener in the other activity is still running but i remove the event listener at the onPause and onStop of every activity and I am using singleEventListeners.
My code is :
Profile Activity
public class ProfileActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private FirebaseDatabase mDatabase;
private DatabaseReference mRef;
TextView UsernameP;
AdView mAdView;
private ValueEventListener eventListener;
private ValueEventListener eventListener1;
ArrayList<String> listOfUsernames = new ArrayList<>();
ArrayList<String> listOfGroups = new ArrayList<>();
ProgressDialog pDialog;
String usernameToBePassed;
String useruuid;
String randomGroupName;
int timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Log.d("TDS","3");
timer = 0;
MobileAds.initialize(this, "my-admob-id");
mAdView = (AdView) findViewById(R.id.adView2);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
showProgress();
UsernameP = (TextView)findViewById(R.id.UsernameP);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference();
checkAndSetUserNameAndGetUsernameList();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.log_out:
logOut();
return true;
case R.id.help:
startActivity(new Intent(ProfileActivity.this,HelpActivity.class));
default:
return super.onOptionsItemSelected(item);
}
}
public void logOut(){
mAuth.signOut();
FirebaseUser user = mAuth.getCurrentUser();
if (user == null){
Intent intent = new Intent(ProfileActivity.this,MainActivity.class);
startActivity(intent);
}
}
public void checkAndSetUserNameAndGetUsernameList() {
useruuid = mUser.getUid();
eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (timer==0) {
usernameToBePassed = "" + dataSnapshot.getValue(String.class);
UsernameP.setText(usernameToBePassed);
cancleProgress();
timer = 1;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("Usernames").child(useruuid).child("name").addListenerForSingleValueEvent(eventListener);
/* mRef.child("Usernames").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Dummies.clear();
listOfUsernames.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
String username = "" + user.name;
makeElementsUniqueUsingSet(Dummies,listOfUsernames,username);
if (mUser.getPhoneNumber().equals(user.phone)){
UsernameP.setText(user.name);
usernameToBePassed = user.name;
useruuid = snapshot.getKey();
}
}
cancleProgress();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}); */
}
public void makeElementsUniqueUsingSet(Set<String> sEntries,ArrayList<String> Entries,String entry){
sEntries.add(entry);
Entries.add(entry);
if (sEntries.size() != Entries.size()){
Entries.clear();
List<String> checkers = new ArrayList<String>(sEntries);
for (int i=0; i<sEntries.size();i++){
Entries.add(checkers.get(i));
}
checkers.clear();
}
Entries.removeAll(Collections.singleton(null));
}
public void getRandomChildname(){
showProgress();
final Set<String> sEntries = new HashSet<>();
eventListener1 = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String s = snapshot.child("name").getValue(String.class);
if (!snapshot.child("Users").hasChild(usernameToBePassed) && !s.equals(null)){
makeElementsUniqueUsingSet(sEntries,listOfGroups,s);
}
}
if (listOfGroups.size()>0) {
Random random = new Random();
int r = random.nextInt(listOfGroups.size());
randomGroupName = listOfGroups.get(r);
String randomGroupname = randomGroupName;
String uniqueUUID = UUID.randomUUID().toString();
mRef.child("GrouplistA").child(randomGroupname).child("Users").child(usernameToBePassed).child("name").setValue(usernameToBePassed);
mRef.child("GrouplistA").child(randomGroupname).child("Users").child(usernameToBePassed).child("status").setValue("normal");
mRef.child("GrouplistA").child(randomGroupname).child("status").setValue("hold");
mRef.child("GrouplistA").child(randomGroupname).child("ChatBox").child("CC-Randomizer-" + uniqueUUID).child("message").setValue("How's it going, people? Randomizer here letting you know there is a new user so all your names have been switched again.So Enjoy. Mizer out!");
mRef.child("GrouplistA").child(randomGroupname).child("ChatBox").child("CC-Randomizer-" + uniqueUUID).child("date").setValue(getCurrentDateAndTime());
cancleProgress();
Intent intent = new Intent(ProfileActivity.this, ChatActivity.class);
intent.putExtra("un", usernameToBePassed);
intent.putExtra("gr", randomGroupname);
intent.putExtra("gs", "A");
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(),"Sorry but there are no public sessions for you to barge in on",Toast.LENGTH_SHORT).show();
cancleProgress();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("GrouplistA").addListenerForSingleValueEvent(eventListener1);
}
public void showProgress()
{
pDialog = new ProgressDialog(ProfileActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
public void cancleProgress()
{
if(pDialog!=null)
pDialog.dismiss();
}
public void CreateGroup(View v){
Intent intent = new Intent(ProfileActivity.this,CreateGroupActivity.class);
intent.putExtra("un",usernameToBePassed);
intent.putExtra("uk",useruuid);
startActivity(intent);
finish();
}
public void GroupList(View v){
Intent intent = new Intent(ProfileActivity.this,GroupListActvity.class);
intent.putExtra("un",usernameToBePassed);
startActivity(intent);
finish();
}
public void FriendsList(View v){
Intent intent = new Intent(ProfileActivity.this,FriendsListActivity.class);
intent.putExtra("un",usernameToBePassed);
intent.putExtra("uk",useruuid);
startActivity(intent);
finish();
}
public void JoinGroup(View v){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("This will take you to a random public group. You ready?");
alert.setPositiveButton("Join", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
getRandomChildname();
}
});
alert.setNegativeButton("Nevermind",null);
alert.show();
}
public String getCurrentDateAndTime(){
return DateFormat.getDateTimeInstance().format(new Date());
}
#Override
protected void onPause() {
super.onPause();
mRef.removeEventListener(eventListener);
if (eventListener1!=null) {
mRef.removeEventListener(eventListener1);
}
}
#Override
protected void onStop() {
super.onStop();
mRef.removeEventListener(eventListener);
if (eventListener1!=null) {
mRef.removeEventListener(eventListener1);
}
}
}
Sorry about the bad indenting. The profile activity is the activity that the app keeps jumping back to by the way
SignUpActivity : Im using Phone Auth
EditText MobileNumber;
CountryCodePicker ccp;
public ProgressDialog pDialog;
private DatabaseReference mRef;
private FirebaseAuth mAuth;
private PhoneAuthProvider mPhoneAuth;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
String mVerificationId;
ValueEventListener eventListener;
private static final String TAG = "TDS";
ArrayList<String> MNumbers = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("TDS","1");
new SimpleEula(this).show();
MobileNumber = (EditText) findViewById(R.id.MobileNumber);
ccp = (CountryCodePicker) findViewById(R.id.ccp);
mRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mPhoneAuth = PhoneAuthProvider.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
if (e instanceof FirebaseAuthInvalidCredentialsException) {
MobileNumber.setError("Invalid phone number.");
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(getApplicationContext(),"Quota exceeded.",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
mVerificationId = verificationId;
mResendToken = token;
}
};
}
public void Submit(View v){
if (!TextUtils.isEmpty(MobileNumber.getText().toString())) {
showProgress();
startPhoneVerification(ccp.getDefaultCountryCodeWithPlus() + MobileNumber.getText().toString());
} else {
MobileNumber.setError("Please enter your mobile number");
}
}
public void startPhoneVerification(String phoneNumber) {
mPhoneAuth.verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = task.getResult().getUser();
checkUserSignIn();
// ...
} else {
// Sign in failed, display a message and update the UI
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
Toast.makeText(getApplicationContext(),"Verfication Code Invalid",Toast.LENGTH_SHORT).show();
}
}
}
});
}
private void verifyPhoneNumberWithCode(String verificationId, String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithPhoneAuthCredential(credential);
}
private void resendVerificationCode(String phoneNumber,
PhoneAuthProvider.ForceResendingToken token) {
mPhoneAuth.verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks, // OnVerificationStateChangedCallbacks
token); // ForceResendingToken from callbacks
}
#Override
public void onStart() {
super.onStart();
checkUserSignIn();
}
public void checkUserSignIn() {
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
showProgress();
getandcheckAccount(currentUser);
}
}
public void showProgress()
{
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
public void cancleProgress()
{
if(pDialog!=null)
pDialog.dismiss();
}
public void getandcheckAccount(final FirebaseUser mUser){
eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
MNumbers.add("" + user.phone);
}
String UserNumber = mUser.getPhoneNumber();
if (MNumbers.contains(UserNumber)){
cancleProgress();
startActivity(new Intent(MainActivity.this,ProfileActivity.class));
} else {
startActivity(new Intent(MainActivity.this,UsernameActivity.class));
cancleProgress();
}
cancleProgress();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("Usernames").addValueEventListener(eventListener);
}
#Override
protected void onPause() {
super.onPause();
if (eventListener!=null) {
mRef.removeEventListener(eventListener);
}
}
#Override
protected void onStop() {
super.onStop();
if (eventListener!=null) {
mRef.removeEventListener(eventListener);
}
}</i>
Im adding the username to the realtime database in a different activity
EditText Username;
TextView TitleTextU;
public ProgressDialog pDialog;
private FirebaseDatabase mDatabase;
private DatabaseReference mRef;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
ValueEventListener eventListener;
ArrayList<String> Usernames = new ArrayList<>();
ArrayList<String> MNumbers = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_username);
showProgress();
Log.d("TDS","2");
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference();
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
getListOfUsernames();
Username = (EditText)findViewById(R.id.Username);
TitleTextU = (TextView)findViewById(R.id.TitleTextU);
TitleTextU.setText("Enter a Username to Continue");
Username.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){
//s is the current character in the eddittext after it is changed
if (Usernames.contains(Username.getText().toString())){
Username.setError("This username is taken");
}
}
});
}
public void Select(View v){
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
String UID = mUser.getUid();
String MobileNumber = mUser.getPhoneNumber();
User user = new User(Username.getText().toString(),MobileNumber);
if (!TextUtils.isEmpty(Username.getText().toString())){
mRef.child("Usernames").child(UID).setValue(user);
startActivity(new Intent(UsernameActivity.this,ProfileActivity.class));
} else {
Username.setError("Please enter a username");
}
}
public void getListOfUsernames(){
eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
Usernames.add("" + user.name);
MNumbers.add("" + user.phone);
}
String UserNumber = mUser.getPhoneNumber();
if (MNumbers.contains(UserNumber)){
cancleProgress();
startActivity(new Intent(UsernameActivity.this,ProfileActivity.class));
}
cancleProgress();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("Usernames").addValueEventListener(eventListener);
}
public void showProgress()
{
pDialog = new ProgressDialog(UsernameActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
public void cancleProgress()
{
if(pDialog!=null)
pDialog.dismiss();
}
#Override
protected void onPause() {
super.onPause();
if (eventListener!=null) {
mRef.removeEventListener(eventListener);
}
}
#Override
protected void onStop() {
super.onStop();
if (eventListener!=null) {
mRef.removeEventListener(eventListener);
}
}
Here is the problematic code:
public void getListOfUsernames(){
eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
Usernames.add("" + user.name);
MNumbers.add("" + user.phone);
}
String UserNumber = mUser.getPhoneNumber();
if (MNumbers.contains(UserNumber)){
cancleProgress();
startActivity(new Intent(UsernameActivity.this,ProfileActivity.class));
}
cancleProgress();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("Usernames").addValueEventListener(eventListener);
}
Every user that signs in makes all the users go to profile screen.

Categories

Resources