I have a problem in my activity when I change a value in the database. I tried creating a new Activity with a toolbar, the toolbar's title is changed with a database value via ValueEventListener. The problem is that when I change the value in my DB, the activity reopens itself.
private static String eventKey;
private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testing);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() == null) {
finishAffinity();
startActivity(new Intent(this, HomeScreenActivity.class));
}
eventKey = getIntent().getExtras().getString("eventKey");
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Eventos").child(eventKey);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String titleValue = dataSnapshot.child("title").getValue().toString();
getSupportActionBar().setTitle(titleValue);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
This is the full code of the TestingActivity class.
Here you can see the previous activity (is too large). And here you can see the log when I change something in my DB.
Thanks!
By looking your code provided in the link, it seems you are launching the TestingActivity or EventSingleActivity.
This is the code from the link:
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabase.child(id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String eventTime = dataSnapshot.child("timeStamp").getValue().toString();
if(Integer.parseInt(nowTime) > Integer.parseInt(eventTime)){
Intent intent = new Intent(PrincipalActivity.this, TestingActivity.class);
intent.putExtra("eventKey", id);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(PrincipalActivity.this, EventSingleActivity.class);
intent.putExtra("eventKey", id);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
That's why every changes from the firebase db it will launch the activities I mentioned above.
To fix this you need to do the following:
mDatabase.child(id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String eventTime = dataSnapshot.child("timeStamp").getValue().toString();
if(Integer.parseInt(nowTime) > Integer.parseInt(eventTime)){
Intent intent = new Intent(PrincipalActivity.this, TestingActivity.class);
intent.putExtra("eventKey", id);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(PrincipalActivity.this, EventSingleActivity.class);
intent.putExtra("eventKey", id);
startActivity(intent);
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Related
I wonder if there's any way where when I try to retrieve the specific email, I get the other child value which is the id. For example, I retrieve the louis#gmail.com, I get the id in the database for return. Whenever i tried to access the id, it says cannot resolve symbol id. Intent doesnt work if i put it inside the if()
public class loginActivity extends AppCompatActivity {
CheckBox checkbox;
EditText email;
EditText password;
FirebaseAuth mAuth;
String emailText;
String passwordText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
checkbox = findViewById(R.id.checkbox);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
}
public void confirm(View view) {
checkAccount();
}
private void checkAccount() {
emailText = email.getText().toString();
passwordText = password.getText().toString();
mAuth = FirebaseAuth.getInstance();
checkBox();
mAuth.signInWithEmailAndPassword(emailText, passwordText).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
if (!checkbox.isChecked()) {
Toast.makeText(loginActivity.this, "Account signin successful", Toast.LENGTH_SHORT).show();
goToMain(new DataRetriever() {
#Override
public void onIdFound(String id) {
Intent toMain = new Intent(loginActivity.this, MainActivity.class);
toMain.putExtra("welcomeId", id);
startActivity(toMain);
}
});
}
} else {
Toast.makeText(loginActivity.this, "Account signin failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void goToMain(DataRetriever retriever) {
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot1: snapshot.getChildren()){
String email = String.valueOf(snapshot1.child("email").getValue());
if (email.equals(emailText)){
String id = String.valueOf(snapshot1.child("id").getValue());
retriever.onIdFound(id);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public interface DataRetriever{
void onIdFound(String id);
}
public void checkBox() {
if (checkbox.isChecked()) {
SharedPreferences sharedPreferences = getSharedPreferences("remember", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("remember", "true");
editor.apply();
Intent toMain = new Intent(loginActivity.this, introActivity.class);
startActivity(toMain);
}
}
}
You mean that you want to get the other childs instead of the current you have, yes it is possible
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
String email= snapshot.child("email").getValue(String.class);//get email
//Check if email is the not same
if(!email.Equals(EditTextValue){
//other value id
String id= snapshot.child("id").getValue(String.class);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Add this interface
public interface DataRetriever{
void onIdFound(String id);
}
Replace your gotoMain with this
public void goToMain(DataRetriever retriever ) {
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference().child("users");
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot1: snapshot.getChildren()){
String email = String.valueOf(snapshot1.child("email").getValue());
if (email.equals(emailText)){
String id = String.valueOf(snapshot1.child("id").getValue());
retriever.onIdFound(id);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Call gotoMain like below:
goToMain(new DataRetriever() {
#Override
public void onIdFound(String id) {
//do whatever you want to do with id
}
});
I'd like to start another activity when a value is added in the database of Firebase.
No error is appearing but when I add a value in the database nothing happens.
Here's my sample code. I've been searching for the past days but it is my first app and I'm a bit confused.
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blackscreen);
databaseReference = FirebaseDatabase.getInstance().getReference();
}
#Override
protected void onStart() {
super.onStart();
usingFirebaseDatabase();
}
public void usingFirebaseDatabase() {
databaseReference.child("uploads")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
do {
if (dataSnapshot.exists()) {
Intent intent = new Intent(blackscreen.this,MainActivity.class);
startActivity(intent);
} else {
return;
}
} while (!dataSnapshot.exists());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(blackscreen.this, "NO images found \n" + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
This is my code of how currently/specific logged in users can add to the database, I need help in retrieving the information of these specific user in a listview or recyclerView. I don't want another user to get the data of a different user.
This is also the structure of my database, within the users water bill payment details, the first node generated is the Users ID and also the next node after the Users Id is the transaction id.
Database structure:
mAuth = FirebaseAuth.getInstance();
currentID = mAuth.getCurrentUser().getUid();
databaseWater= FirebaseDatabase.getInstance().getReference().child("users water bill payment details").child(currentID);
progressBar= new ProgressDialog(this);
moneynumberwat = (EditText) findViewById(R.id.moneynumberwat);
moneypinwat = (EditText) findViewById(R.id.moneypinwat);
meterwat = (EditText) findViewById( R.id.meterwat);
user_idwat = (EditText) findViewById(R.id.user_idwat);
amountwat = (EditText) findViewById(R.id.amountwat);
modePaywat = (Spinner) findViewById(R.id.modePaywat);
Paywater = (Button) findViewById(R.id.Paywater);
Paywater.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addPayWaterInfo();
}
});
setubk();
setupbk();
}
private void setubk() {
ImageButton btn2 = findViewById(R.id.bord);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
Intent intent = new Intent(PayOffWater.this, Interface.class);
startActivity(intent);
}
});
}
private void setupbk() {
ImageButton btn2 = findViewById(R.id.bak);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
Intent intent = new Intent(PayOffWater.this, Services.class);
startActivity(intent);
}
});
}
private void addPayWaterInfo() {
String moneynumw = moneynumberwat.getText().toString();
String pincodelitw = moneypinwat.getText().toString();
String meterw = meterwat.getText().toString();
String customerw = user_idwat.getText().toString();
String cashw = amountwat.getText().toString();
String mpayw = modePaywat.getSelectedItem().toString();
if( moneynumw.isEmpty()||moneynumw.length()>10 || moneynumw.length()<10 ||
pincodelitw.length()>4 || pincodelitw.length()<4 ||meterw.isEmpty()||cashw.isEmpty()|| mpayw.isEmpty()){
Toast.makeText(this,"provide correct information before payment can be successful",Toast.LENGTH_LONG).show();
} else{
String id = databaseWater.push().getKey();
com.example.iamstix_jnr.utility.PayOf.Pay pay = new Pay(moneynumw,pincodelitw,meterw,customerw,cashw,mpayw);
databaseWater.child(id).setValue(pay);
finish();
Intent intent = new Intent(PayOffWater.this,Success.class);
startActivity(intent);
}
}
You have to navigate to the last id.
databaseWater= FirebaseDatabase.getInstance().getReference().child("users water bill payment details").child(currentID).child("id of no 3.");
you have to add an ChildEventListener on your database reference and on each callback add or remove or update the adapter that you have on your recyclerview
databaseWater.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
//todo add to adapter
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
//todo update adapter
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
//todo remove from adapter
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
//todo update adapter
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I have created an app in android studio and I have a java file name Login.java. In which I had checked a particular mpin entered by user exists in firebase real time database or not.
Now I want that in else loop mpin doesn't exists then it should remain on Login activity.
How can this be done?
public class Login extends AppCompatActivity {
String enteredmPINString;
EditText enteredmPin;
DatabaseReference rootref;
String contactfromPhoneLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button mLoginSubmit;
mLoginSubmit = (Button) findViewById(R.id.loginSubmit);
Bundle b = getIntent().getExtras();
if(b!=null){
contactfromPhoneLogin = b.getString("contacttoLogin");
Log.d("abcd",contactfromPhoneLogin);
}
rootref= FirebaseDatabase.getInstance().getReference("Employees").child(contactfromPhoneLogin).child("empmpin");
Log.d("abcd","Database reference reached");
// enteredmPin = (EditText) findViewById(R.id.editTextmPIN);
// enteredmPINString = enteredmPin.getText().toString();
View.OnClickListener submitListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
enteredmPin = (EditText) findViewById(R.id.editTextmPIN);
enteredmPINString = enteredmPin.getText().toString();
Log.d("abcd",enteredmPINString);
final Intent loginIntent = new Intent(Login.this,NavigationDrawer.class);
loginIntent.putExtra ("mPINtoNavigation",enteredmPINString);
Log.d("abcd","Login.java sending"+enteredmPINString);
startActivity(loginIntent);
rootref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("abcd","onDatachange reached");
Log.d("abcd",enteredmPINString);
if(dataSnapshot.child(enteredmPINString).exists()){
Log.d("abcd","mpin exists");
Intent loginIntent = new Intent(Login.this,NavigationDrawer.class);
loginIntent.putExtra ("mPINtoNavigation",enteredmPINString);
Log.d("abcd","Login.java sending"+enteredmPINString);
startActivity(loginIntent);
}
else{
Toast.makeText(Login.this,"Invalid mPIN!",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mLoginSubmit.setOnClickListener(submitListener);
}
public void erp_site(View view){
Intent erpIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://web.nbccho.com/erp/"));
startActivity(erpIntent);
}
public void nbcc_site(View view){
Intent nbcc_siteIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.nbccindia.com/nbccindia/index.jsp"));
startActivity(nbcc_siteIntent);
}
}
remove the intent in onClick();
View.OnClickListener submitListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
enteredmPin = (EditText) findViewById(R.id.editTextmPIN);
enteredmPINString = enteredmPin.getText().toString();
Log.d("abcd",enteredmPINString);
Log.d("abcd","Login.java sending"+enteredmPINString);
I'm using the following code to fill a list with data from a child within firebase database. The list is filled successfully, but I've got an issue: FirebaseListAdapter is being called multiple times before stopping, what does not occur when I use it in other activities.
One weird thing is that when I click a specific listView item, data from another item is passed through my openChat intent, what makes wrong data be retrieved to the chat activity I open. It seems that the calling multiple times thing is messing all the data.
Can someone point out what might be wrong with my code and/or what I must do to optimize it?
//database references
chatsRef = FirebaseDatabase.getInstance().getReference().child("chats").child(mAuth.getCurrentUser().getUid()); //the children of this are other users IDs
usersRef = FirebaseDatabase.getInstance().getReference().child("users");
////////// code for populateView I use within FirebaseListAdapter ///////////
FirebaseListAdapter<ChatUsers> firebaseListAdapter = new FirebaseListAdapter<ChatUsers>(getActivity(), ChatUsers.class, R.layout.item_user_listing, chatsRef) {
protected void populateView(View view, ChatUsers chatUsers, int position) {
TextView nameChatItemList = (TextView) view.findViewById(R.id.nameChatItemList);
id_other_user = getRef(position).getKey();
usersRef.child(id_other_user).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//for (DataSnapshot ds : dataSnapshot.getChildren())
Toast.makeText(mActivity, dataSnapshot.getValue().toString(), Toast.LENGTH_SHORT).show();
name = dataSnapshot.child("name").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent openChat= new Intent(getActivity().getApplicationContext(), Chat.class);
openChat.putExtra("iduser_chat", id_outro_usuario);
openChat.putExtra("name_user_chat", name);
startActivity(openChat);
}
});
}
}
EDIT Changes implemented as suggested by Farmaan
FirebaseListAdapter<ChatUsers> firebaseListAdapter = new FirebaseListAdapter<ChatUsers>(getActivity(), ChatUsers.class, R.layout.item_user_listing, ChatsRef) {
#Override
protected void populateView(View view, ChatUsers chatUsers, int position) {
TextView nomeImageChatItemList = (TextView) view.findViewById(R.id.nomeChatItemList);
String id_other_user = getRef(position).getKey();
usersRef.child(id_other_user).addListenerForSingleValue(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usersRef.child(id_other_user).addListenerForSingleValue(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
Intent openChat = new Intent(getActivity().getApplicationContext(), Chat.class);
openChat.putExtra("iduser_chat", id_other_user);
openChat.putExtra("nameuser_chat", name);
startActivity(openChat);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
Since id_other_user and name are the class level field and you are updating it every time you populate the view.So the last view which is populated will decide the user id and the name.That's wrong with your code.
chatsRef = FirebaseDatabase.getInstance().getReference().child("chats").child(mAuth.getCurrentUser().getUid()); //the children of this are other users IDs
usersRef = FirebaseDatabase.getInstance().getReference().child("users");
////////// code for populateView I use within FirebaseListAdapter ///////////
protected void populateView (View view, ChatUsuarios chatUsuarios,int position){
TextView nameChatItemList = (TextView) view.findViewById(R.id.nameChatItemList);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String id_other_user = getRef(position).getKey();
usersRef.child(id_other_user).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//for (DataSnapshot ds : dataSnapshot.getChildren())
String name = dataSnapshot.child("name").getValue().toString();
Intent openChat = new Intent(getActivity().getApplicationContext(), Chat.class);
openChat.putExtra("iduser_chat", id_other_user);
openChat.putExtra("name_user_chat", name);
startActivity(openChat);
Toast.makeText(mActivity, dataSnapshot.getValue().toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}