I'm doing a function that will delete a record in a real time Firebase. A person can only delete their own record by knowing the unique ID generated by the .getKey(). However when i want implement the RecordID to delete, I couldn't called the RecordID. Does anyone know what i'm doing wrong here ? Thanks.
Error
My error demo, the variable doesnt recognize in my delete function
My get class
package com.example.sossystem;
public class SosRecords {
String RecordID;
String FullName;
String PhoneNumber;
String EmailAddress;
public SosRecords(){
}
public SosRecords(String recordID, String fullName, String phoneNumber, String emailAddress) {
RecordID = recordID;
FullName = fullName;
PhoneNumber = phoneNumber;
EmailAddress = emailAddress;
}
public String getRecordID() {
return RecordID;
}
public String getFullName() {
return FullName;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public String getEmailAddress() {
return EmailAddress;
}
}
Error
The error is showed on the Stop button
btnStopSOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onStop();
stopLocationUpdates();
deleteRecords(RecordID);
result.setText("Dashboard");
btnStartSOS.setEnabled(true);
btnStopSOS.setEnabled(false);
}
});
}
private void deleteRecords(String fullName) {
DatabaseReference delRecord = FirebaseDatabase.getInstance().getReference("Records").child(RecordID);
delRecord.removeValue();
Toast.makeText(MainActivity.this, "The SOS Request is Stopped!", Toast.LENGTH_SHORT).show();
}
My Code
btnStartSOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onStart();
//GET ALL INFORMATION FROM FIRESTORE AND SEND TO REALTIME DATABASE
if(FirebaseAuth.getInstance().getCurrentUser()!= null){
DocumentReference df = FirebaseFirestore.getInstance().collection("Users").document(FirebaseAuth.getInstance().getCurrentUser().getUid());
df.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.getString("FullName")!= null){
String id = reff.push().getKey();
Log.d(TAG, "asdasd"+id);
SosRecords sosRecords = new SosRecords(id,documentSnapshot.getString("FullName"), (documentSnapshot.getString("PhoneNumber")), (documentSnapshot.getString("UserEmail") ));
reff.child(id).setValue(sosRecords);
btnStopSOS.setEnabled(true);
Toast.makeText(MainActivity.this, "You're are now activating SOS request !", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),Login.class));
finish();
}
});
}
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
checkSettingsAndStartLocationUpdates();
}else{
askLocationPermission();
}
}
});
btnStopSOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onStop();
stopLocationUpdates();
deleteRecords(RecordID);
result.setText("Dashboard");
btnStartSOS.setEnabled(true);
btnStopSOS.setEnabled(false);
}
});
}
private void deleteRecords(String fullName) {
DatabaseReference delRecord = FirebaseDatabase.getInstance().getReference("Records").child(RecordID);
delRecord.removeValue();
Toast.makeText(MainActivity.this, "The SOS Request is Stopped!", Toast.LENGTH_SHORT).show();
}
SosRecords sosrecords = new SosRecords();
btnStopSOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onStop();
stopLocationUpdates();
deleteRecords(sosrecords.getRecordID);
result.setText("Dashboard");
btnStartSOS.setEnabled(true);
btnStopSOS.setEnabled(false);
}
});
}
I successfully solved it by set the value of the Id to my RecordID
sosrecords.setRecordID(id);
Related
I am not too good at android applications so most of the code are from the Youtube videos I watched while trying to learn how to code android application. I made some adjustment to what I want.
Here I am stuck trying to create a library management system. Every thing seems to be
working, except for the fact that I can't create a new user or sign in.
Code is running fine, but still do not understand the errors. From my Sign Activity there seems to be a misplacement of code, which I don't understand.
public class SignUpActivity extends AppCompatActivity implements View.OnClickListener{
private TextInputLayout editName;
private TextInputLayout editEnrollNo;
private TextInputLayout editCardNo;
private TextInputLayout editPass1;
private TextInputLayout editID;
private TextInputLayout editPass;
private Button buttonRegister;
private TextView toSignIn;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
private CheckBox check1;
private FirebaseFirestore db;
private Spinner userType;
private String type;
private int type1;
private int temp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
editID = (TextInputLayout) findViewById(R.id.editID);
editPass = (TextInputLayout) findViewById(R.id.editPass);
editPass1=(TextInputLayout)findViewById(R.id.editPass1);
editName=(TextInputLayout)findViewById(R.id.editName);
editEnrollNo=(TextInputLayout)findViewById(R.id.editEnrollNo);
editCardNo=(TextInputLayout)findViewById(R.id.editCardNo);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
toSignIn = (TextView) findViewById(R.id.toSignIn);
progressDialog=new ProgressDialog(this);
progressDialog.setCancelable(false);
check1=(CheckBox)findViewById(R.id.check1);
userType=(Spinner)findViewById(R.id.userType);
List<String> list = new ArrayList<>();
list.add("Select Account Type");
list.add("User");
list.add("Admin");
ArrayAdapter adapter =new ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
userType.setAdapter(adapter);
userType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getItemAtPosition(position).toString().equals("Select Account Type"))
{
type=parent.getItemAtPosition(position).toString();
editPass1.setEnabled(false);
editPass.setEnabled(false);
editName.setEnabled(false);
editID.setEnabled(false);
editEnrollNo.setEnabled(false);
editCardNo.setEnabled(false);
editCardNo.setErrorEnabled(false);
editEnrollNo.setErrorEnabled(false);
editID.setErrorEnabled(false);
editName.setErrorEnabled(false);
editPass.setErrorEnabled(false);
editPass1.setErrorEnabled(false);
}
else if(parent.getItemAtPosition(position).toString().equals("User"))
{
type=parent.getItemAtPosition(position).toString();
editPass1.setEnabled(true);
editPass.setEnabled(true);
editName.setEnabled(true);
editID.setEnabled(true);
editEnrollNo.setEnabled(true);
editCardNo.setEnabled(true);
editCardNo.setErrorEnabled(false);
editEnrollNo.setErrorEnabled(false);
editID.setErrorEnabled(false);
editName.setErrorEnabled(false);
editPass.setErrorEnabled(false);
editPass1.setErrorEnabled(false);
}
else
{
type=parent.getItemAtPosition(position).toString();
editPass1.setEnabled(true);
editPass.setEnabled(true);
editName.setEnabled(true);
editID.setEnabled(true);
editEnrollNo.setEnabled(false);
editCardNo.setEnabled(false);
editCardNo.setErrorEnabled(false);
editEnrollNo.setErrorEnabled(false);
editID.setErrorEnabled(false);
editName.setErrorEnabled(false);
editPass.setErrorEnabled(false);
editPass1.setErrorEnabled(false);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
FirebaseApp.initializeApp(this);
firebaseAuth=FirebaseAuth.getInstance();
db=FirebaseFirestore.getInstance();
buttonRegister.setOnClickListener(this);
toSignIn.setOnClickListener(this);
check1.setOnClickListener(this);
}
private boolean verifyName()
{
String name=editName.getEditText().getText().toString().trim();
if(name.isEmpty())
{ editName.setErrorEnabled(true);
editName.setError("Name Required");
return true;
}
else
{
editName.setErrorEnabled(false);
return false;
}
}
private boolean verifyCardNo()
{
String cardNo=editCardNo.getEditText().getText().toString().trim();
if(cardNo.isEmpty())
{ editCardNo.setErrorEnabled(true);
editCardNo.setError("Card No. Required");
return true;
}
else
{
editCardNo.setErrorEnabled(false);
return false;
}
}
private boolean verifyEnrollNo()
{
String enrollNo=editEnrollNo.getEditText().getText().toString().trim();
if(enrollNo.isEmpty())
{ editEnrollNo.setErrorEnabled(true);
editEnrollNo.setError("Enrollment No. Required");
return true;
}
else
{
editEnrollNo.setErrorEnabled(false);
return false;
}
}
private boolean verifyEmailId()
{
String emailId=editID.getEditText().getText().toString().trim();
if(emailId.isEmpty())
{ editID.setErrorEnabled(true);
editID.setError(" Email ID Required");
return true;
}
else if(!emailId.endsWith("#iiitnr.edu.in"))
{
editID.setErrorEnabled(true);
editID.setError(" Enter Valid Email ID");
return true;
}
else
{
editID.setErrorEnabled(false);
return false;
}
}
private boolean verifyPass()
{
String pass=editPass.getEditText().getText().toString().trim();
if(pass.isEmpty())
{ editPass.setErrorEnabled(true);
editPass.setError(" Password Required");
return true;
}
else
{
editPass.setErrorEnabled(false);
return false;
}
}
private boolean verifyPass1()
{
String pass1=editPass1.getEditText().getText().toString().trim();
String pass=editPass.getEditText().getText().toString().trim();
if(pass1.isEmpty())
{ editPass1.setErrorEnabled(true);
editPass1.setError("Confirm Password Required");
return true;
}
else if(pass.equals(pass1))
{
editPass1.setErrorEnabled(false);
return false;
}
else
{
editPass1.setErrorEnabled(true);
editPass1.setError("Passwords do not match");
return true;
}
}
private boolean verifyType()
{
if (type.equals("Select Account Type"))
{
Toast.makeText(this, "Please select account type !", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
private boolean verifyCard1()
{
db.collection("User").whereEqualTo("card",Integer.parseInt(editCardNo.getEditText().getText().toString().trim())).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful())
{
temp=task.getResult().size();
}
}
});
if(temp==0)
return false;
else
return true;
}
private void registerUser()
{
if(verifyType())
return;
if(type.equals("User"))
{
boolean res= (verifyName()|verifyCardNo()|verifyEmailId()|verifyEnrollNo()|verifyPass()|verifyPass1());
if(res==true)
return;
}
if(type.equals("Admin"))
{
boolean res= (verifyName()|verifyEmailId()|verifyPass()|verifyPass1());
if(res==true)
return;
}
String id=editID.getEditText().getText().toString().trim();
String pass=editPass.getEditText().getText().toString().trim();
if(type.equals("User")){
type1=0;
}
else
type1=1;
progressDialog.setMessage("Registering User ... ");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(id,pass).addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
String id=editID.getEditText().getText().toString().trim();
String name=editName.getEditText().getText().toString().trim();
if(type1==0)
{
int enroll=Integer.parseInt(editEnrollNo.getEditText().getText().toString().trim());
int card=Integer.parseInt(editCardNo.getEditText().getText().toString().trim());
db.collection("User").document(id).set(new User(name,id,enroll,card,type1)).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.cancel();
Toast.makeText(SignUpActivity.this,"Registered Successfully !",Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
startActivity(new Intent(getApplicationContext(),SignInActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SignUpActivity.this, "Please Try Again !", Toast.LENGTH_SHORT).show();
}
});
}
else {
db.collection("User").document(id).set(new Admin(type1,name,id)).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.cancel();
Toast.makeText(SignUpActivity.this,"Registered Successfully !",Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
startActivity(new Intent(getApplicationContext(),SignInActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SignUpActivity.this, "Please Try Again !", Toast.LENGTH_SHORT).show();
}
});
}
}
else
{ progressDialog.cancel();
if(task.getException() instanceof FirebaseAuthUserCollisionException)
{
Toast.makeText(SignUpActivity.this,"Already Registered ! ",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(SignUpActivity.this, "Registration Failed ! Try Again ", Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
public void onClick(View v) {
if(v==check1)
{
if(check1.isChecked())
buttonRegister.setEnabled(true);
else
buttonRegister.setEnabled(false);
}
else if(v==buttonRegister)
registerUser();
else if(v==toSignIn) {
startActivity(new Intent(getApplicationContext(),SignInActivity.class));
finish();
}
}
}
Please can any one help?
When you return from a function, the code written after is never executed. In your method registerUser() every if condition that is true, returns. That means the actual code to register user is never reached.
This are the rules on my Firebase Realtime Database:
{
"rules": {
".read": true,
".write": true
}
}
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
private EditText mUserName, mEmail, mPassword;
private Button registerBtn;
private TextView toLogin;
private ProgressBar progressBar;
private ImageView mImage;
// Firebase stuff
private FirebaseAuth mAuth;
private DatabaseReference databaseReference;
private FirebaseDatabase mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
setupUI();
mAuth = FirebaseAuth.getInstance();
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String userName = mUserName.getText().toString();
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
if(TextUtils.isEmpty(userName)) {
Toast.makeText(getApplicationContext(),"Username is required", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(),"Email is required", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(),"Password is required", Toast.LENGTH_SHORT).show();
}
if(userName.length() < 4) {
Toast.makeText(RegisterActivity.this, "Username too short", Toast.LENGTH_SHORT).show();
}
if (android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
Toast.makeText(getApplicationContext(),"Valid email address", Toast.LENGTH_SHORT).show();
}
if(password.length() < 8) {
Toast.makeText(getApplicationContext(),"Password must contain at least 8 characters", Toast.LENGTH_SHORT).show();
}
userRegister(email, password);
startActivity(new Intent(getApplicationContext(), MenuActivity.class));
finish();
}
});
toLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
});
}
private void userRegister(String email, String password) {
final ProgressDialog progressDialog = new ProgressDialog(RegisterActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Creating account...");
progressDialog.show();
//register user in firebase
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
User user = new User(email, password);
FirebaseDatabase.getInstance().getReference("users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "User successful created",
Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
else {
Toast.makeText(RegisterActivity.this, "Failed to register",
Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(RegisterActivity.this, "Error! " +
task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
private void setupUI() {
mImage = findViewById(R.id.image);
mUserName = findViewById(R.id.userName_register);
mEmail = findViewById(R.id.email_register);
mPassword = findViewById(R.id.password_register);
registerBtn = findViewById(R.id.register_button);
toLogin = findViewById(R.id.toLogin);
progressBar = findViewById(R.id.progress_bar_register);
}
}
User.java
public class User {
public String userName, email, password;
public User() { }
public User(String email, String password) {
this.email = email;
this.password = password;
}
public User(String userName, String email, String password) {
this.userName = userName;
this.email = email;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
I have tried many things found on web but none have worked and nothing changes, it still remain void. I'm very desperate guys. Am I forgetting to add something? Unfortunately I'm new in Android and Firebase. Thanks in advance.
Did you setup the application by downloading the google-services.json from Firebase console and putting it in the Android Studio project?
Also, did you add your app's signature to the allowed apps in Firebase console?
Refer to this.
The problem I am facing is that I cannot display the detail of the ListView on which I clicked, any suggestion to display the detail of the Firebase data, I'm done for itemOnClick and change to another activity, but the problem is that it shows only the text of ListView and not the detail, thank you
LISTVIEW JAVA CLASS
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
final String value = dataSnapshot.getValue(Sample.class).toString();
arrayList.add(0,value);
listcase.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), Report.class);
//String sample = String.valueOf(arrayList.get(i));//arrayAdapter.getItem(i);
intent.putExtra("sample", String.valueOf(arrayList.get(i)));
startActivity(intent);
overridePendingTransition(R.anim.slide_right_entering, R.anim.slide_right_exiting);
finish();
}
});
}
});
CONSTRUCTOR
public Sample() {
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public String getSymthom() {
return symthom;
}
public void setSymthom(String symthom) {
this.symthom = symthom;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getDateDiag() {
return DateDiag;
}
public void setDateDiag(String dateDiag) {
DateDiag = dateDiag;
}
public String toString (){
return "Sample Name : " + Name + "\n"+ "Status : ";
}
DETAIL JAVA CLASS
Intent intent = getIntent();
if (intent.hasExtra("sample"))
{
textView.setText(intent.getStringExtra("sample"));
}
I have no idea how to display detail of my Firebase object to another activity, thank you for helping me
Your ArrayList contains an only String, not a detail object.
final String value = dataSnapshot.getValue(Sample.class).toString();
So when you get by index it returns item value. If you share the value of value JSON structure it would be good to understand better.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot){
Log.d("data", "onDataChange: "+ dataSnapshot);
Sample Sample = snapshot.getValue(Sample.class);
sampleList.add(Sample);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I have added all the strings, private booleans in the Signup.java and properly added all the firebase dependencies. Plus, Added the codes in Login.java to retrieve all the firebase data after successful signup. However, there is no error showing in the codes but still, the sign-in screen functionalites aren't working. When I click on "Signin" button the apps showing me "This app has stopped"
Here's the code that I have written on login.java
public class Login extends AppCompatActivity {
Button callSignUp, reg_btn;
TextInputLayout username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
callSignUp = findViewById(R.id.signupscreen);
callSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Login.this, SignUp.class);
startActivity(intent);
}
});
//All elements Hooks
username = findViewById(R.id.reg_username);
password = findViewById(R.id.reg_password);
reg_btn = findViewById(R.id.reg_btn);
}
private Boolean validateUsername() {
String val = username.getEditText().getText().toString();
if (val.isEmpty()) {
username.setError("Please enter your username");
return false;
} else {
username.setError(null);
username.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = password.getEditText().getText().toString();
if (val.isEmpty()) {
password.setError("Please enter your password");
return false;
} else {
password.setError(null);
password.setErrorEnabled(false);
return true;
}
}
public void loginUser(View view) {
//validate user login
if (!validateUsername() | !validatePassword()) {
return;
} else {
isUser();
}
}
private void isUser() {
final String userEnteredUsername = username.getEditText().getText().toString().trim();
final String userEnteredPassword = password.getEditText().getText().toString().trim();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users");
Query checkUser = reference.orderByChild("username").equalTo(userEnteredUsername);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
username.setError(null);
username.setErrorEnabled(false);
String passwordFromDB = dataSnapshot.child(userEnteredUsername).child("password").getValue(String.class);
if (passwordFromDB.equals(userEnteredPassword)) {
String nameFromDB = dataSnapshot.child(userEnteredUsername).child("name").getValue(String.class);
String emailFromDB = dataSnapshot.child(userEnteredUsername).child("email").getValue(String.class);
String usernameFromDB = dataSnapshot.child(userEnteredUsername).child("username").getValue(String.class);
String phoneNoFromDB = dataSnapshot.child(userEnteredUsername).child("phoneNo").getValue(String.class);
Intent intent = new Intent(getApplicationContext(), UserProfile.class);
intent.putExtra("name", nameFromDB);
intent.putExtra("username", usernameFromDB);
intent.putExtra("phoneNo", phoneNoFromDB);
intent.putExtra("password", passwordFromDB);
startActivity(intent);
} else {
password.setError("Wrong Password");
}
} else {
username.setError("Opps! No Such User Exist!");
username.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
//Call SignUp Screen
public void callSignUpScreen(View view) {
//To call next activity
Intent intent = new Intent(Login.this, SignUp.class);
}
}
Can anyone please tell me why the issue is happening?
Thanks
This is the code, i have problem when i want to get user key (getPhone) i can't, cause get null value i'm newbie in programming.
LayoutInflater inflater = LayoutInflater.from(this);
View layout_pwd = inflater.inflate(R.layout.ganti_password_layout,null);
final MaterialEditText edtPassword = (MaterialEditText)layout_pwd.findViewById(R.id.gantiPassword);
final MaterialEditText edtNewPassword = (MaterialEditText)layout_pwd.findViewById(R.id.gantiPasswordBaru);
final MaterialEditText edtRepeatPassword = (MaterialEditText)layout_pwd.findViewById(R.id.gantiPasswordBaruUlang);
alertDialog.setView(layout_pwd);
//Button
alertDialog.setPositiveButton("GANTI", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Ganti Password Disini
final android.app.AlertDialog waitingDialog = new SpotsDialog(Home.this);
waitingDialog.show();
//cek password lama
if(edtPassword.getText().toString().equals(Common.currentUser.getPassword()))
{
//Cek Password Baru dan Ulang Password
if(edtNewPassword.getText().toString().equals(edtRepeatPassword.getText().toString()))
{
Map<String,Object> passwordUpdate = new HashMap<>();
passwordUpdate.put("password",edtNewPassword.getText().toString());
//Update
DatabaseReference user = FirebaseDatabase.getInstance().getReference("User");
user.child(Common.currentUser.getPhone())
.updateChildren(passwordUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
waitingDialog.dismiss();
Toast.makeText(Home.this, "Password Telah Diganti", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Home.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
else
{
waitingDialog.dismiss();
Toast.makeText(Home.this, "Pengulangan Password Tidak Sesuai", Toast.LENGTH_SHORT).show();
}
}
else
{
waitingDialog.dismiss();
Toast.makeText(Home.this, "Password Lama Salah", Toast.LENGTH_SHORT).show();
}
}
});
and this is the error
Process: com.example.novaldi.sabilulunganlaykes, PID: 15878
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at com.google.firebase.database.DatabaseReference.child(Unknown Source:6)
at com.example.novaldi.sabilulunganlaykes.Home$4.onClick(Home.java:259)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
and this my structure database
database structure
and this is my user class
public User(){
}
public User(String nama, String password, String kodeKeamanan) {
Nama = nama;
Password = password;
IsStaff = "false";
this.KodeKeamanan = kodeKeamanan;
}
public String getKodeKeamanan() {
return KodeKeamanan;
}
public void setKodeKeamanan(String kodeKeamanan) {
KodeKeamanan = kodeKeamanan;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getIsStaff() {
return IsStaff;
}
public void setIsStaff(String isStaff) {
IsStaff = isStaff;
}
public String getNama() {
return Nama;
}
public void setNama(String nama) {
Nama = nama;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
This problem exists because the method Common.currentUser.getPhone() returns null.
To fix it just add simple null test before the child() method invokation.
Like this:
String phone = Common.currentUser.getPhone();
if (phone != null)
user.child(phone)
.updateChildren(passwordUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
waitingDialog.dismiss();
Toast.makeText(Home.this, "Password Telah Diganti", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Home.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
else {
// do something else here
}
Or edit the getPhone() method that it will never return null