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.
Related
So I'm making an app in android studio, its like a fintech app. In one activity/page(SendMoney.java), you put in a number amount and tap the "Send Money" button, from here it goes to the page where you choose who you're sending this money to(SendReceiver.java). You select your desired recepient and tap on a second "Send Money" button, this then takes you to a success page that lists the amount sent and the username of the recepient(SendReceiverSuccessPage).
On the SendMoney page I need to get the amount inputted and pass that data to the SendReceiverSuccessPage, I've done this by using Intent and I've added this code to when the Send Money button is clicked, but in doing this what happens is that it for some reason creates multiple instances of the SendReceiver page it navigates to.
So on the SendReceiver page when I'm done and I hit the second "Send Money" button it just opens a new instance of SendReceiver whiles the SendReceiverSuccessPage is stuck in the background for some reason.
I need it to be one single smooth navigation flow where it goes from SendMoney to SendReceiver to SendReceiverSuccessPage without SendReceiver popping up multiple times and stacking ontop of the success page, all whiles being able to actively pass and retrieve the "AmountSent" data.
SendMoney.java
public class SendMoney extends AppCompatActivity {
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
Context context;
Double userAmountDouble;
MaterialButton sendMoneyButton;
ImageView backspace, back;
TextView amount, currentBalanceText, currency, one, two, three, four, five, six, seven, eight, nine, zero, dot;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_money);
this.context = getApplicationContext();
// Instance of FirebaseAuth and Database
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
// Hooks
back = findViewById(R.id.back);
amount = findViewById(R.id.amount);
currency = findViewById(R.id.currency);
currentBalanceText = findViewById(R.id.current_balance);
one = findViewById(R.id.one);
two = findViewById(R.id.two);
three = findViewById(R.id.three);
four = findViewById(R.id.four);
five = findViewById(R.id.five);
six = findViewById(R.id.six);
seven = findViewById(R.id.seven);
eight = findViewById(R.id.eight);
nine = findViewById(R.id.nine);
zero = findViewById(R.id.zero);
dot = findViewById(R.id.dot);
backspace = findViewById(R.id.backspace);
sendMoneyButton = findViewById(R.id.send_money_button);
sendMoneyButton.setText("Send GH₵0");
// Display send amount on button, in realtime
amount.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//sendMoneyButton.setText("Send GH₵0");
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// This method is called whenever the text in the EditText changes
String userInputAmount = amount.getText().toString();
sendMoneyButton.setText("Send GH₵" + userInputAmount);
}
#Override
public void afterTextChanged(Editable editable) {
//
}
});
// Connect to the database
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
assert firebaseUser != null;
// Get and show available balance
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String currentBalance = snapshot.getValue(String.class);
assert currentBalance != null;
currentBalanceText.setText("GH₵"+ currentBalance + " AVAILABLE");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
// Send Money Button
sendMoneyButton.setOnClickListener(v -> {
String userInputAmount = amount.getText().toString();
if (userInputAmount.equals("") || userInputAmount.equals("0")) {
Toast.makeText(getApplicationContext(),"Please enter an amount",Toast.LENGTH_SHORT).show();
} else {
userAmountDouble = Double.parseDouble(userInputAmount);
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String currentBalance = snapshot.getValue(String.class);
assert currentBalance != null;
double currentBalanceDouble = Double.parseDouble(currentBalance);
if (userAmountDouble > currentBalanceDouble) {
Toast.makeText(getApplicationContext(),"Insufficient Balance",Toast.LENGTH_SHORT).show();
} else {
// Create an Intent and include the value of userInputAmount
Intent sendReceiverIntent = new Intent(getApplicationContext(), SendReceiver.class);
sendReceiverIntent.putExtra("USER_INPUT_AMOUNT", amount.getText().toString());
sendReceiverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Start the SendReceiver activity
finish();
startActivity(sendReceiverIntent);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
}
});
// Click Listeners
back.setOnClickListener(v -> finish());
zero.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("0");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "0");
}
});
one.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("1");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "1");
}
});
two.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("2");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "2");
}
});
three.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("3");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "3");
}
});
four.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("4");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "4");
}
});
five.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("5");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "5");
}
});
six.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("6");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "6");
}
});
seven.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("7");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "7");
}
});
eight.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("8");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "8");
}
});
nine.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("9");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "9");
}
});
dot.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText(".");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + ".");
}
});
backspace.setOnClickListener(v -> {
if (amount.getText().toString().equals("") | amount.getText().toString().equals("0")) {
amount.setText("0");
} else {
amount.setText(amount.getText().toString().substring(0, amount.getText().length() - 1));
}
});
}
}
SendReceiver.java
public class SendReceiver extends AppCompatActivity{
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
Context context;
ArrayList<SearchedUsersModel> searchedUsersModel;
RecyclerView searchedUsersRecycler;
SearchView svSearch;
MaterialButton finalSendBtn;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sendreceiver);
// Retrieve the value of userInputAmount from the Intent
Intent intent = getIntent();
String userInputAmount = intent.getStringExtra("USER_INPUT_AMOUNT");
this.context = getApplicationContext();
// Instance of FirebaseAuth and Database
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
// Hooks
searchedUsersRecycler = findViewById(R.id.recyclerUsers);
svSearch = findViewById(R.id.svSearch);
finalSendBtn = findViewById(R.id.final_send_button);
// Set the hint for the search bar
svSearch.setQueryHint("Enter name or email of user");
// On click listener for when you hit the Send button
finalSendBtn.setOnClickListener(v -> {
DatabaseReference databaseReference = database.getReference("Users");
assert firebaseUser != null;
databaseReference.child(firebaseUser.getUid()).child("transactions").child("sendTransactions").child(Objects.requireNonNull(databaseReference.push().getKey())).child("amount").setValue(userInputAmount);
// Get a reference to the "transactions" collection
DatabaseReference transactionsRef = database.getReference("Transactions");
// Get a reference to the "sendTransactions" sub-collection
DatabaseReference sendTransactionsRef = transactionsRef.child("sendTransactions");
// Generate a unique ID for the new transaction
String transactionUID = sendTransactionsRef.push().getKey();
// Add the new transaction to the "sendTransactions" sub-collection
assert transactionUID != null;
sendTransactionsRef.child(transactionUID).child("amount").setValue(userInputAmount);
// This deducts the same amount from the current users main balance
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String currentBalance = snapshot.getValue(String.class);
DecimalFormat df = new DecimalFormat("0.00");
assert currentBalance != null;
// The current balance minus the amount withdrawn
double amountToSubtract = Double.parseDouble(currentBalance) - Double.parseDouble(userInputAmount);
String newBalance = Double.toString(Double.parseDouble(df.format(amountToSubtract)));
// Write the new balance to the database
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").setValue(newBalance).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
System.out.println("Error updating user main balance: " + task.getException());
} else {
// Print an error message
System.out.println("Error updating user main balance: " + task.getException());
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
finish();
startActivity(new Intent(getApplicationContext(), SendReceiverSuccessPage.class));
});
// Connect to the database
if (svSearch != null) {
svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (!newText.isEmpty()) {
// Connect to the database
String currentUserId = Objects.requireNonNull(firebaseAuth.getCurrentUser()).getEmail();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
assert firebaseUser != null;
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
searchedUsersModel = new ArrayList<>();
for (DataSnapshot ds : snapshot.getChildren()) {
// Removes current user from list
SearchedUsersModel user = ds.getValue(SearchedUsersModel.class);
assert user != null;
if (!user.getMail().equals(currentUserId)) { // check if user's ID does not match current user's ID
searchedUsersModel.add(user); // add this user to the list of searched users
}
}
//Filter through the users based on Name or Email
ArrayList<SearchedUsersModel> myList = new ArrayList<>();
for(SearchedUsersModel object : searchedUsersModel) {
if(object.getMail().toLowerCase().contains(newText.toLowerCase())) {
myList.add(object);
}
else if(object.getName().toLowerCase().contains(newText.toLowerCase())) {
myList.add(object);
}
}
SearchedUsersAdapter searchedUsersAdapter = new SearchedUsersAdapter(myList, finalSendBtn, svSearch);
searchedUsersRecycler.setAdapter(searchedUsersAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
} else {
// Clear the data from the RecyclerView
searchedUsersModel = new ArrayList<>();
SearchedUsersAdapter searchedUsersAdapterClass = new SearchedUsersAdapter(searchedUsersModel, finalSendBtn, svSearch);
searchedUsersRecycler.setAdapter(searchedUsersAdapterClass);
//Set button to disabled
finalSendBtn.setEnabled(false);
}
return false;
}
});
return true;
}
});
}
}
}
SendReceiverSuccessPage
public class SendReceiverSuccessPage extends AppCompatActivity {
MaterialButton greatNextButton;
TextView sendSuccessText;
public static String usersName;
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sendreceiver_success_page);
// Instance of FirebaseAuth and Database
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
greatNextButton = findViewById(R.id.great_next_button);
sendSuccessText = findViewById(R.id.send_success);
//Get sent amount from database
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
assert firebaseUser != null;
DatabaseReference transactionsRef = databaseReference.child(firebaseUser.getUid()).child("transactions");
DatabaseReference sendTransactionsRef = transactionsRef.child("sendTransactions");
//
sendTransactionsRef.orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot transactionSnapshot : dataSnapshot.getChildren()) {
String lastTransactionKey = transactionSnapshot.getKey();
assert lastTransactionKey != null;
sendTransactionsRef.child(lastTransactionKey).child("amount").addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String sentAmount = snapshot.getValue(String.class);
sendSuccessText.setText("GH₵" + sentAmount + " has been sent to " + usersName);
//TODO This can also be where receiveTransactions document is created in the users database
// This sends the money to the chosen user by their name
databaseReference.orderByChild("name").equalTo(usersName).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot userSnapshot : snapshot.getChildren()) {
// Get the main balance of the chosen user
String mainBalance = userSnapshot.child("userMainBalance").getValue(String.class);
DecimalFormat df = new DecimalFormat("0.00");
// Convert the main balance and amount sent to doubles
assert mainBalance != null;
double mainBalanceDouble = Double.parseDouble(mainBalance);
assert sentAmount != null;
double amountSentDouble = Double.parseDouble(sentAmount);
// Add the amount sent to the main balance
double updatedMainBalance = mainBalanceDouble + amountSentDouble;
// Convert the updated main balance back to a string
String updatedMainBalanceString = Double.toString(Double.parseDouble(df.format(updatedMainBalance)));
// Update the main balance in the database for the chosen user
userSnapshot.getRef().child("userMainBalance").setValue(updatedMainBalanceString);
userSnapshot.getRef().child("transactions").child("receivedTransactions").child(Objects.requireNonNull(databaseReference.push().getKey())).child("amount").setValue(sentAmount);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Handle error
}
});
greatNextButton.setOnClickListener(v -> {
startActivity(new Intent(getApplicationContext(), MainDashboard.class));
});
}
}
There are also some Adapter classes I can add if needed.
I've been trying to figure it out with ChatGPT and have literally tried out everything.
Through testing I found out that anytime I take the
Intent sendReceiverIntent = new Intent(getApplicationContext(), SendReceiver.class);
sendReceiverIntent.putExtra("USER_INPUT_AMOUNT", amount.getText().toString());
sendReceiverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
lines out of the sendMoney button it ended up not creating multiple instances and working exactly like how I need it to. The only problem is that the amount sent that I need to pass to the success page isn't recoreded or passed. So ideally, if I could find a way or alternative to getting this data to the desired page without putting it into the button OnClick or having it create multiple instances of the activity.
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
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 am completely noob (again sorry about my ignorance in this field I relly need help) in java and I need to make an app with firebase. Here is my register account code(its all the code I have copied from GitHub :P) I want to make it just to register with username, the register with email and password functionality and the verification sending future completely to be disabled , also I need to make it to go on a different activity or simply to login the user and show the posts feed. I hope someone could help me:
public class SignupActivity extends BaseActivity {
private static final String TAG = "SignupActivity";
private Context mContext = SignupActivity.this;
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FireBaseMethods fireBaseMethods;
private String email, handleName, password;
private EditText mHandleName, mEmail, mPassword;
private Button mButtonRegister;
private TextView loadingPleaseWait;
private ProgressBar mProgressBar;
//firebase Database
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
boolean isExisted;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
fireBaseMethods = new FireBaseMethods(mContext);
Log.d(TAG, "onCreate: started");
initWidgets();
setupFirebaseAuth();
init();
}
#Override
protected void performOnCreate(Bundle state) {
}
private void init() {
mButtonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleName = mHandleName.getText().toString();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(mEmail.getText().toString());
stringBuilder.append("");
email = stringBuilder.toString();
password = mPassword.getText().toString();
if (validate()) {
mProgressBar.setVisibility(View.VISIBLE);
loadingPleaseWait.setVisibility(View.VISIBLE);
fireBaseMethods.registerNewEmail(handleName, email, password);
}
}
});
}
/*
Initialize the activity widgets
*/
private void initWidgets() {
Log.d(TAG, "initWidgets: Initialize Widgets");
mHandleName = findViewById(R.id.handle_name);
mEmail = findViewById(R.id.input_email_signup);
mPassword = findViewById(R.id.input_password_signup);
mButtonRegister = findViewById(R.id.btn_signup);
mProgressBar = findViewById(R.id.progressBar);
loadingPleaseWait = findViewById(R.id.loading_signup);
mProgressBar.setVisibility(View.GONE);
loadingPleaseWait.setVisibility(View.GONE);
}
public boolean validate() {
boolean valid = true;
if (handleName.isEmpty() || handleName.length() < 3) {
mHandleName.setError("Внесете најмалку 3 карактери");
valid = false;
} else {
mHandleName.setError(null);
}
if (email.isEmpty()) {
mEmail.setError("Внесете валидна електронска пошта");
valid = false;
} else {
mEmail.setError(null);
}
if (password.isEmpty() || password.length() < 4) {
mPassword.setError("помеѓу 4 и 10 карактери");
valid = false;
} else {
mPassword.setError(null);
}
return valid;
}
/*
------------------------------------- Firebase ---------------------------------------------------
*/
/**
* Set up firebase auth object
*/
private void setupFirebaseAuth() {
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//1st check: make sure handle name is not ready in use
if (fireBaseMethods.checkIfHandleNameAlreadyExists(handleName, dataSnapshot)) {
mHandleName.setError("Тој ник веќе постои");
isExisted = true;
}
//add new user to the database
fireBaseMethods.addNewUser(handleName, email);
Toast.makeText(mContext, "Регистрирањето беше успешно.Ви пративме верификација на email", Toast.LENGTH_SHORT).show();
mAuth.signOut();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
finish();
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
I do NOT advise the ability to sign up with ONLY a username. You lose the ability to recover an account.
However, you may take the username given to you, and append #fakeemail.com to the end of it and continue to use the email/password method.
I've got input city form, where it has 2 element, EditText for city name and Spinner a that has been populate Province Data from Firebase database. I want to make nodes structure in Firebase like this:
database{
provinces{
provinceId_1{
provinceId_1 : value
provinceName_1 : value
}
provinceId_2{
provinceId_2 : value
provinceName_2 : value
}
}
cities{
provinceId_1{
cityId_1{
cityId_1 : value
cityName_1 : value
}
cityId_2{
cityId_2 : value
cityName_2 : value
}
}
provinceId_2{
cityId_3{
cityId_3 : value
cityName_3 : value
}
}
}
}
But i do not know how to acquire provinces id and store it to cities table in firebase database, here's my code :
public class AddCityActivity extends AppCompatActivity {
private EditText inputCity;
private Button btnAddCity, btnClearText;
private MaterialSpinner spinnerProvinces;
private DatabaseReference databaseCities, databaseProvinces;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_city);
inputCity = (EditText) findViewById(R.id.add_city_edit_text);
btnAddCity = (Button) findViewById(R.id.action_add_city_button);
btnClearText = (Button) findViewById(R.id.action_clear_text_button);
spinnerProvinces = (MaterialSpinner) findViewById(R.id.provinceSpinner);
databaseProvinces = FirebaseDatabase.getInstance().getReference().child("provinces");
databaseProvinces.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<String> provinces = new ArrayList<String>();
for (DataSnapshot provinceSnapshot : dataSnapshot.getChildren()) {
String provinceName = provinceSnapshot.child("provinceName").getValue(String.class);
provinces.add(provinceName);
}
MaterialSpinner provincesSpinner = (MaterialSpinner) findViewById(R.id.provinceSpinner);
ArrayAdapter<String> provincesAdapter = new ArrayAdapter<String>(AddCityActivity.this, android.R.layout.simple_spinner_item, provinces); provincesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
provincesSpinner.setAdapter(provincesAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
btnClearText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputCity.setText("");
}
});
btnAddCity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addCity();
}
});
}
private void addCity() {
String name = inputCity.getText().toString().trim();
databaseCities = FirebaseDatabase.getInstance().getReference("cities");
if (!TextUtils.isEmpty(name)) {
String id = databaseCities.push().getKey();
City city = new City(id, name);
databaseCities.child(id).setValue(city);
Toast.makeText(this, "City Added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Enter City Name", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
startActivity(new Intent(AddCityActivity.this, LandingActivity.class));
finish();
}
}