How to prevent android studio from skipping activities? - android

I have a quiz app that will save the score on firebase. It works properly. But whenever I try to retake the quiz, it will just show the first activity, and then skip all the activity after it and proceed to the final activity where it shows the output. I checked everything, the IDs are all unique. I can't find where I went wrong.
This is the first part of my quiz. When I retake the quiz, the scores will reset to 0. It works properly. But when I click next, it will just proceed to the final activity where the output is shown.
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_part1);
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
phqChoice1 = (RadioButton) findViewById(R.id.phqChoice1);
phqChoice2 = (RadioButton) findViewById(R.id.phqChoice2);
phqChoice3 = (RadioButton) findViewById(R.id.phqChoice3);
phqChoice4 = (RadioButton) findViewById(R.id.phqChoice4);
btnNext = (Button) findViewById(R.id.btnNext);
getAnswer();
final DatabaseReference myRef = firebaseDatabase.getReference(firebaseAuth.getUid()).child("test");
if (myRef != null) {
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
HashMap<String, Object> result = new HashMap<>();
result.put("anx", 0);
result.put("dep", 0);
myRef.updateChildren(result);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserHistory userHistory = new UserHistory();
userHistory.setAnx(anx);
userHistory.setDep(dep);
myRef.setValue(userHistory);
Intent myIntent = new Intent(Part1.this, Part2.class);
startActivity(myIntent);
finish();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println("Entering data failed. " + databaseError.getMessage());
}
});
}
});
}}
private void getAnswer() {
radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);
radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.phqChoice2) {
dep++;
} else if (checkedId == R.id.phqChoice3) {
dep = dep + 2;
} else if (checkedId == R.id.phqChoice4) {
dep = dep + 3;
}
}
});}
This is the part2 activity where android skips these activities and will just proceed to the final activity if I retake the quiz.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_part2);
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
btnNext = (Button)findViewById(R.id.btnPart2);
DatabaseReference myRef = firebaseDatabase.getReference(firebaseAuth.getUid()).child("test");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserHistory userHistory = dataSnapshot.getValue(UserHistory.class);
anxHistory = userHistory.getAnx();
depHistory = userHistory.getDep();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Part2.this, databaseError.getCode(), Toast.LENGTH_SHORT).show();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer();
anxValue = anxHistory + anx;
final DatabaseReference myRef = firebaseDatabase.getReference(firebaseAuth.getUid()).child("test");
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
HashMap<String, Object> result = new HashMap<>();
result.put("anx", anxValue);
myRef.updateChildren(result);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
Intent part3A = new Intent(Part2.this, Part3.class);
startActivity(part3A);
}
});
}
private void getAnswer() {
radioGroup2 = (RadioGroup) findViewById(R.id.radioGroup2);
int selectedItem = radioGroup2.getCheckedRadioButtonId();
if (selectedItem == R.id.part2Choice2) {
anx++ ;
} else if (selectedItem == R.id.part2Choice3) {
anx = anx + 2 ;
}
else if (selectedItem == R.id.part2Choice4) {
anx = anx + 3;
}else {
anx = 0;
}
}
}
I expect the output to proceed as normally whenever I retake the quiz again. All activities should proceed as usual and no activity should be skipped. What actually happens is the first activity is working properly but all the other activities that are related to the quiz ends up being skipped. Please help. I am clueless and I don't know what else should I check.
In addition, if I click the radio button A (value is 0), the activity will just continue as usual. If I click other buttons which has a value that is greater than 0, (Value is 1-3), and then the activity will just skip to the final activity wherein the output is displayed.
To simplify: Click Radio button A (0) > Next activity, Click Radio Button A(0), > Next Activity (Proceeds as normal.). OR Click Radio button B (1) > Skips other activity, proceeds to the final activity.

try to put the Intent outside the btnNext,onClickListener method
Intent part3A = new Intent(Part2.this, Part3.class);
btnNext.setOnClcikListener(){
//here call your intent from Part2
startActivity(part3A);
}

I put the intent activity inside the ValueEventListener so whenever I try to enter new data, it will skip to the Final activity. The fix:
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserHistory userHistory = new UserHistory();
userHistory.setAnx(anx);
userHistory.setDep(dep);
myRef.setValue(userHistory);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println("Entering data failed. " + databaseError.getMessage());
}
});
Intent myIntent = new Intent(Part1.this, Part2.class);
startActivity(myIntent);
finish();

Related

Firebase Value Event listener being skipped

When debugging, the program doesn't get into user ref value event listener why would this happen?
I get rid = null but the firebase instantiation is correct from what I can tell.
[text so stack overflow lets me post since there's too much code and no further explanation for the issue]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_message_chat);
getSupportActionBar().hide();
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
useref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snap : snapshot.getChildren()) {
rid = snap.child("receiverid").getValue(String.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
rv = findViewById(R.id.rvcahtitems);
b = findViewById(R.id.chatsendb);
field = findViewById(R.id.chatfield);
user = FirebaseAuth.getInstance().getCurrentUser();
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = field.getText().toString();
if ((!msg.equals("")))
{
SendM(user.getUid(), rid, msg);
}
else
{
Toast.makeText(ChatScreen.this, "Can't send an empty message", Toast.LENGTH_SHORT);
}
field.setText("");
}
});
rv.setLayoutManager(new LinearLayoutManager(this));
readmsgs(userID, rid);
}

How to retrieve other child value when a specific child value is known

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
}
});

Extracting the text from a textview

Hi guys I need help on a rather trivial problem that I can't solve, then I'm writing an app for android with android studio, what the app should do is read the contents of the TextView, text-only format without numbers or anything , and based on the content of the TextView should change image or text, I can not I tried to write this code but it does not work, could you please tell me where I am wrong and write me some code, thanks.
public class CashBackPage extends AppCompatActivity {
public FirebaseAuth mAuth;
public AdView adViewTop, adViewBot;
TextView mLogout;
TextView mTxtPhone;
TextView mPhone;
TextView mReadCash;
TextView mVersionApp;
TextView mCodeRappCash;
TextView mGeneralTextCash, mSendRequestText;
ImageButton mSendRequest, mCancel;
LinearLayout mbannerTop, mbannerBot;
FirebaseDatabase mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cash_back_page);
mLogout = (TextView) findViewById(R.id.logoutbutn);
mTxtPhone = (TextView) findViewById(R.id.TextPhone);
mPhone = (TextView) findViewById(R.id.NumberPhTxt);
mReadCash = (TextView) findViewById(R.id.ReadCashBack);
mVersionApp = (TextView) findViewById(R.id.VersionApp);
mSendRequest = (ImageButton) findViewById(R.id.SendRequestBtn);
mCancel = (ImageButton) findViewById(R.id.CancelBtn);
mCodeRappCash = (TextView) findViewById(R.id.CodeDiscountCash);
mGeneralTextCash = (TextView) findViewById(R.id.textgeneralacash);
mSendRequestText = (TextView) findViewById(R.id.textsendrequest);
mSendRequestText.setVisibility(View.GONE);
mGeneralTextCash.setVisibility(View.GONE);
mAuth = FirebaseAuth.getInstance();
initFirebase();
//Set Orientation Portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getnumberprefs();
if (!isEmpty (String.valueOf(mCodeRappCash))){
String textgen = mCodeRappCash.getText().toString().trim();
if (textgen.equals("Request code sent...")){
mSendRequestText.setVisibility(View.VISIBLE);
mGeneralTextCash.setVisibility(View.GONE);
}else{
mSendRequestText.setVisibility(View.GONE);
mGeneralTextCash.setVisibility(View.VISIBLE);
}
}
}
#Override
protected void onStart() {
super.onStart();
// Read to the database CashBack
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("CashBack").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String cashback = dataSnapshot.getValue(String.class);
mReadCash.setText(cashback);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// Read to the database Version App
myRef.child("Utenti").child(mPhone.getText().toString()).child("Version App").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String versionapp = dataSnapshot.getValue(String.class);
mVersionApp.setText(versionapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// Read to the database Code Cash Back
myRef.child("Utenti").child(mPhone.getText().toString()).child("RappCash Code").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coderappcash = dataSnapshot.getValue(String.class);
mCodeRappCash.setText(coderappcash);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void logoutclick(View view) {
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(30);
mAuth.signOut();
updateUI();
}
private void initFirebase() {
mDatabase = FirebaseDatabase.getInstance();
}
private void updateUI() {
FirebaseUser currentuser = mAuth.getCurrentUser();
if(currentuser == null){
Intent intTologin = new Intent(this, MainActivity.class);
finish();
startActivity(intTologin);
}
}
private void getnumberprefs() {
SharedPreferences numb = getSharedPreferences(Register.NUMB, MODE_PRIVATE);
String numberphn = numb.getString(Register.KEY_NUMB,null);
mPhone.setText(numberphn);
}
public void sendrequest(View view) {
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(30);
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("RappCash Code").setValue("Request code sent...");
}
public void cancelrequest(View view) {
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(30);
new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("RappCash Code").setValue("Request code canceled...");
}
public void onFinish() {
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("RappCash Code").setValue("#RappCashCode");
}
}.start();
}
private boolean isEmpty (String mCoins) {
return mCoins.contentEquals("#RappCashCode");
}
}
so only if the text is the same as "Request code sent ..." it changes image or text contained in another textview, I entered this code in both OnStart and OnCreate but in both cases it doesn't work.
I state that the TextView reads the content of a line of a real time database firebase and that it returns in the app what is written on the database
Edit:
Okay, relating to your code the problem is simple. TextView is checked for text, before is set.
You are firstly calling check on onCreate():
if (!isEmpty (String.valueOf(mCodeRappCash))){
String textgen = mCodeRappCash.getText().toString().trim();
if (textgen.equals("Request code sent...")){
mSendRequestText.setVisibility(View.VISIBLE);
mGeneralTextCash.setVisibility(View.GONE);
}else{
mSendRequestText.setVisibility(View.GONE);
mGeneralTextCash.setVisibility(View.VISIBLE);
}
}
And then you are calling on onStart():
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coderappcash = dataSnapshot.getValue(String.class);
mCodeRappCash.setText(coderappcash);
}
You have to get reference to database earlier, and set your TextView before check. So for example:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cash_back_page);
mLogout = (TextView) findViewById(R.id.logoutbutn);
mTxtPhone = (TextView) findViewById(R.id.TextPhone);
mPhone = (TextView) findViewById(R.id.NumberPhTxt);
mReadCash = (TextView) findViewById(R.id.ReadCashBack);
mVersionApp = (TextView) findViewById(R.id.VersionApp);
mSendRequest = (ImageButton) findViewById(R.id.SendRequestBtn);
mCancel = (ImageButton) findViewById(R.id.CancelBtn);
mCodeRappCash = (TextView) findViewById(R.id.CodeDiscountCash);
mGeneralTextCash = (TextView) findViewById(R.id.textgeneralacash);
mSendRequestText = (TextView) findViewById(R.id.textsendrequest);
mSendRequestText.setVisibility(View.GONE);
mGeneralTextCash.setVisibility(View.GONE);
mAuth = FirebaseAuth.getInstance();
initFirebase();
//Set Orientation Portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getnumberprefs();
//You have to set mCodeRappCash value before this check!!!
// Read to the database Code Cash Back
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("RappCash Code").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coderappcash = dataSnapshot.getValue(String.class);
mCodeRappCash.setText(coderappcash);
}
if (!isEmpty (String.valueOf(mCodeRappCash))){
String textgen = mCodeRappCash.getText().toString().trim();
if (textgen.equals("Request code sent...")){
mSendRequestText.setVisibility(View.VISIBLE);
mGeneralTextCash.setVisibility(View.GONE);
}else{
mSendRequestText.setVisibility(View.GONE);
mGeneralTextCash.setVisibility(View.VISIBLE);
}
}
}
}
I solved and found this banal problem, thanks to the same to all those who answered, under the portion of code solved.
#Override
protected void onStart() {
super.onStart();
// Read to the database CashBack
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("CashBack").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String cashback = dataSnapshot.getValue(String.class);
mReadCash.setText(cashback);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// Read to the database Version App
myRef.child("Utenti").child(mPhone.getText().toString()).child("Version App").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String versionapp = dataSnapshot.getValue(String.class);
mVersionApp.setText(versionapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// Read to the database Code Cash Back
myRef.child("Utenti").child(mPhone.getText().toString()).child("RappCash Code").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coderappcash = dataSnapshot.getValue(String.class);
mCodeRappCash.setText(coderappcash);
assert coderappcash != null;
if (!isEmpty (coderappcash)){
if (coderappcash.equals("Request code sent...")){
mSendRequestText.setVisibility(View.VISIBLE);
mGeneralTextCash.setVisibility(View.GONE);
}else{
mSendRequestText.setVisibility(View.GONE);
mGeneralTextCash.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
the information was contained in (coderappcash)

Trying to replace a data from specific child (Firebase Database)

I want to replace kids/[id]/kidLimit/[new data]
So what I do is I make a spinner with kidName data, then with the selected item from that spinner I want to replace the data of kidLimit (with the same parent as the selected item from the spinner).
The first thing I do is to find the unique key of the selected item, then go to the kidLimit with that unique key to then use the setValue() method.
public class setLimit extends AppCompatActivity {
private DatabaseReference db;
private EditText etLimit;
private Button btnSetLimit;
private Spinner kidSpinner;
private String kidKey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_limit);
etLimit = findViewById(R.id.et_limit);
btnSetLimit = findViewById(R.id.btn_confirm);
kidSpinner = findViewById(R.id.spinner_kid);
//PUTTING STRING LIST FROM FIREBASE TO SPINNER DROPDOWN STARTS HERE
db = FirebaseDatabase.getInstance().getReference().child("kids");
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final List<String> kid = new ArrayList<>();
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()) {
String kidName = dataSnapshot1.child("kidName").getValue(String.class);
kid.add(kidName);
}
ArrayAdapter<String> kidNameAdapter = new ArrayAdapter<>(setLimit.this, android.R.layout.simple_spinner_item, kid);
kidNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
kidSpinner.setAdapter(kidNameAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//ENDS HERE
//ONCLICKLISTENER
btnSetLimit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findId();
String newLimit = etLimit.getText().toString().trim();
db.child(kidKey).child("kidLimit").setValue(newLimit);
}
});
}
//FINDING KEY FROM THE SELECTED SPINNER ITEM
public void findId(){
String kidName = kidSpinner.getSelectedItem().toString();
db = FirebaseDatabase.getInstance().getReference().child("kids");
db.orderByChild("kidName").equalTo(kidName).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
kidKey = dataSnapshot1.getKey();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
So basically what I did was using the snapshot inside the onclick method to find the key. But when I check them on the log, it showed that the kidkey variable is null the first time I press the button, but after that it's not null anymore.
What can I to do so when I press the button, I can go to a specific child to replace it's data without getting any null pointer exception?
Here's the database that I use
When you do this
btnSetLimit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findId();
String newLimit = etLimit.getText().toString().trim();
db.child(kidKey).child("kidLimit").setValue(newLimit);
}
});
findId(); is executed but you don't know when it will finish, so after that method is executed and waiting for data, this line
db.child(kidKey).child("kidLimit").setValue(newLimit);
will have kidKey with a null value because it has not been pulled yet from the database, so instead, you should move your code to the onDataChange() or make a new callback when all the asynchronous process finishes
btnSetLimit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findId();
}
});
public void findId(){
String kidName = kidSpinner.getSelectedItem().toString();
String newLimit = etLimit.getText().toString().trim();
db = FirebaseDatabase.getInstance().getReference().child("kids");
db.orderByChild("kidName").equalTo(kidName).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
kidKey = dataSnapshot1.getKey();
}
db.child(kidKey).child("kidLimit").setValue(newLimit);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

How to retrieve data of specific users from firebase into a listview

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) {
}
});

Categories

Resources