Android studio not catching value from editText box - java

I would like to compare the Id that the user has inputted with the Id from the database as a login process. However, when I run the code after filling all the ID and password, the application returns that inputted ID and inputted pw are empty. What's the problem?

It happens because
final String inputId = editId.getText().toString();
final String inputPw = editPw.getText().toString();
These strings are initialized at the beginning in the onCreate() method.
When you click the button the buttonLogIn.setOnClickListener is executed with the same values initialized (empty values).
You have to get the new values from the EditText views.
buttonLogIn.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
//...
String user = editId.getText().toString();
String psw = editPw.getText().toString();
//..
if (!TextUtils.isEmpty(user)&& !TextUtils.isEmpty(psw)){ ... }
}
});
As mentioned by #Andy in the comments, you have to change also the check on firebase because the method is asynchronous.
if (TextUtils.isEmpty(user)&& TextUtils.isEmpty(psw)){
Toast.makeText(LoginScreen.this, "Complete all fields", Toast.LENGTH_SHORT).show();
} else {
//Firebase check
....
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//....
//Check the values here
if (userId.equals(inputId)) && userPw.equals(inputPw)){...}
}
}

You need to get the value from the edit text after the text has been updated:
if (!TextUtils.isEmpty(editId.getText().toString())&& !TextUtils.isEmpty(editPw.getText().toString()))...

Related

Firebase Database Reference Error: No such instance field: 'mDatabaseReference'

I'm using Firebase Realtime Database to store data for a project. I'm using Android Studio and Java to create a mobile app. In this particular activity, a new user is filling out a form to sign up for the service. Once they input their info and hit the submit button, the on click handles that info and inserts it into the Database.
Here is the relevant code for that class:
public class CreateUserActivity extends AppCompatActivity {
private DatabaseReference mDatabaseReference;
private List<String> mInterestList;
private EditText mUsername;
private EditText mPassword;
private EditText mEmail;
private EditText mLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mInterestList = new ArrayList<>();
mUsername = findViewById(R.id.text_username);
mPassword = findViewById(R.id.text_password);
mEmail = findViewById(R.id.text_email);
mLocation = findViewById(R.id.text_location);
}
public void onCheckboxClicked(View view) {
CheckBox checkbox = (CheckBox) view;
boolean isChecked = checkbox.isChecked();
String interest = checkbox.getText().toString();
if(isChecked) {
mInterestList.add(interest);
}else {
mInterestList.remove(interest);
}
}
public void onSaveUser(View view) {
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
String email = mEmail.getText().toString();
String location = mLocation.getText().toString();
if(TextUtils.isEmpty(username) ||
TextUtils.isEmpty(password) ||
TextUtils.isEmpty(email) ||
TextUtils.isEmpty(location) ||
mInterestList.size() == 0) {
displayToast("Please enter values for all fields");
}else {
List<String> interests = mInterestList;
User user = new User(username, password, email, location, interests, null);
mDatabaseReference.child("users").child(username).setValue(user, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(#Nullable DatabaseError databaseError, #NonNull DatabaseReference databaseReference) {
if(databaseError != null) {
Log.e(GetTogetherApp.LOG_TAG, databaseError.getMessage());
}else{
displayToast("User created!");
}
}
});
}
}
As I've run through breakpoints the error seems to fire on this line:
mDatabaseReference.child("users").child(username).setValue()
Specifically once I try and enter into the setValue() method. The other two child() calls work to find the path as intended. I have the database reference set as a member variable, so I'm not sure why it seems to lose it at that point.
Here's a look at my database structure
Firebase Database Structure Pic
Error in Android Studio:
The error message in your screenshot is in the variable inspector in the Android Studio debugger. It means that where the error occurs, there is no variable mDatabaseReference so the debugger can't show its value. This is not the actual cause of the crash, merely the debugger telling you that it can't show you something you asked for.
You can find the actual cause of the problem by inspecting the InvocationTargetException e.

if statement inside a onClickListener trying to get value of androidtextwidget

I am trying to convert a value that has been passed through from another fragment. The convert method is inside an onClickListener which when clicked will make the conversion of the value passed through the fragment.
The values are currently being placed into TextViews on my second fragment. However when I try to make an if statement it won't enter the loop
Text Name is what my textView has been set to.
The code is here
button10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (textName.equals("Miles") && textName2.equals("Kilometers")) {
String str1 = editText1.getText().toString();
double unittoConvert = Double.parseDouble(str1);
double convertedUnit = unittoConvert * 1.6;
String result = Double.toString(convertedUnit);
textName3.setText(result);
}
}
});
This is the code for the methods that are setting the unit selected in scroller and passing it through to the text view which is then displaying the selected unit. When i try to extract these values it wont work
PageViewModel.getName().observe(requireActivity(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textName.setText(s);
}
});
PageViewModel2.getName2().observe(requireActivity(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textName2.setText(s);
}
});
Use getText to extract text from TextView and then compare
textName.getText().equals("Miles") && textName2.getText().equals("Kilometers")

How to retrieve a Boolean value from Firebase to a TextView?

I'm making a shopping app and User has to subscribe to the 'Fast-delivery' option if he needs to order it faster. When the User puts a tick to the 'Fast-delivery' Checkbox, the boolean value is being uploaded to the Firebase realtime database -->
database
And I want to see if the User has subscribed to the 'Fast-delivery' option from the Admin Panel. I retrieve all the order information to a RecyclerView in the Admin Panel. I want to set a TextView as "Fast Delivery : On/Off" when the Admin views the order details from the Admin Panel.
This is what I have tried:
#Override
protected void onStart()
{
super.onStart();
ordersRef = FirebaseDatabase.getInstance().getReference().child("Orders");
FirebaseRecyclerOptions<AdminOrders> options =
new FirebaseRecyclerOptions.Builder<AdminOrders>()
.setQuery(ordersRef, AdminOrders.class)
.build();
FirebaseRecyclerAdapter<AdminOrders, AdminOrdersViewHolder> adapter =
new FirebaseRecyclerAdapter<AdminOrders, AdminOrdersViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final AdminOrdersViewHolder holder, final int position, final #NonNull AdminOrders model)
{
holder.userName.setText("Name: "+ model.getName());
holder.userPhoneNumber.setText("Phone Number: : "+ model.getPhone());
holder.userTotalPrice.setText("Total Amount: $"+ model.getTotalAmount());
holder.userDateTime.setText("Order Time: "+ model.getDate() + model.getTime());
holder.userShippingAddress.setText("Shipping Address: "+ model.getAddress() + "," + model.getCity());
holder.showOrdersBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String uID = getRef(position).getKey();
Intent intent = new Intent(AdminNewOrdersActivity.this, AdminUserProductsActivity.class);
intent.putExtra("uid", uID);
startActivity(intent);
}
});
ordersRef.child(userID).child("fast_delivery").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
TextView switch1 = (TextView) findViewById(R.id.switch1);
switch1.setText(String.valueOf(this));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
And I'm getting this error
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
You have a NullPointerException indicating that userID is not initialized, hence this error:
Can't pass null for argument 'pathString' in child()
To solve this, please add the following line of code:
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
Right in front of:
ordersRef.child(userID).child("fast_delivery").addValueEventListener(/* ... */);
i guess if im right.. you have created separate tree for orders where you are getting orders
create model class give name as same as childname are where you're getting boolean value of fast_delivery use that boolean value to convert it to string and hence compare that value if String.valueof(boolean)is="true" then print to textview or vise versa with off

How do I smoothly store user input data with EditText and RadioButtons (with a color set as well)?

I want to store the data from both the RadioButtons as well as the EditText values in the User attribute registeredData, but I don't know how to access my function in a way that allows me to grab all the data, as well as displaying a color change from the RadioButtons. Also how do I check if the input data is already in use (like email)?
I have tried splitting them into two different functions, but I can't get the data back from them into my User attribute registeredData. This is my first try at coding an app so any help is appreciated.
public class Registration extends AppCompatActivity {
private EditText displayname, email, password, confirmpassword;
private Button bsubmit;
private RadioGroup rgroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
displayname = findViewById(R.id.displayname);
email = findViewById(R.id.useremail);
password = findViewById(R.id.password);
confirmpassword = findViewById(R.id.confirmpassword);
bsubmit = findViewById(R.id.bsubmit);
rgroup = findViewById(R.id.rgroupteams);
bsubmit.setOnClickListener(onRegister);
}
private View.OnClickListener onRegister = new View.OnClickListener() {
#Override
public void onClick(View v) {
final User registeredData;
registeredData = new User();
switch (v.getId()) {
case R.id.bsubmit:
String useremail = email.getText().toString();
String userdisplayname = displayname.getText().toString();
String userpassword = password.getText().toString();
registeredData.email = useremail;
registeredData.displayname = userdisplayname;
registeredData.password = userpassword;
case R.id.rgroupteams:
RadioGroup group = findViewById(R.id.rgroupteams);
group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int idOfSelected) {
switch (idOfSelected) {
case R.id.rbtnmantis:
bsubmit.setBackgroundColor(Color.parseColor("#FF0000"));
bsubmit.setTextColor(Color.parseColor("#000000"));
registeredData.team = "Mantis";
break;
case R.id.rbtlightbringers:
bsubmit.setBackgroundColor(Color.parseColor("#F4DC00"));
bsubmit.setTextColor(Color.parseColor("#000000"));
registeredData.team = "LightBringers";
break;
case R.id.rbtncryptographers:
bsubmit.setBackgroundColor(Color.parseColor("#1C00AA"));
bsubmit.setTextColor(Color.parseColor("#FFFFFF"));
registeredData.team = "Cryptographers";
break;
default:
registeredData.team = "";
}
}
});
}
}
};
}
Right now the color change only turns on after I've have clicked the submit button because I don't know how to better set my setOnClickListener(), I haven't made use of any variables in the registeredData outside of this either, are they set up to be able to be accessed for some data (like displayname) to be displayed?
You need to move onCheckedChangeListener outside of onClickListener. Also, move registeredData outside onClickListener. Make sure that registeredData is "globally" accessible. Then on button click and checked listener you can set data from input fields and from checkboxes to the object.
Second, with TextUtils.isEmpty(email.getText().toString()) you can get boolean if email is empty or not. This you can use for other input fields, just send text to the isEmpty method

Comparing EditText with EditText values

Does anyone know what's wrong with my code, I'm trying to compare the input in my edit text field to ensure their equal value before it creates an account.
//compare the fields contents
if(editTextPassword.equals(editTextReEnterPassword)) {
//they are equal
//Creating a new user
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
finish();
startActivity(new Intent(getApplicationContext(), Home.class));
} else{
Toast.makeText(Register.this, "Could not register... please try again", Toast.LENGTH_SHORT).show();
}
}
});
}else {//they are not equal
Toast.makeText(Register.this, "Passwords do not match... please try again", Toast.LENGTH_SHORT).show();
}
You have to get the text value of the edit text.
So, really, you can not do editText.equals()
You would do something like this..
String editTextPasswordString = editTextPassword.getText().toString().trim();
String editTextReEnterPasswordString = editTextReEnterPassword.getText().toString().trim();
if(editTextPasswordString.equals(editTextReEnterPasswordString)) {
//code
}
First you need to get the value from EditText using the method getText().toString(), like this:
String newPassword= editTextReEnterPassword.getText().toString();
For more information about the method, please check the follow link:
Get Value of EditText
After that, you need to compare the previous string editTextPassword with the new one created, which is the result of the method getText(), editTextReEnterPassword.
So your final code, should be like this:
String newPassword = editTextReEnterPassword.getText().toString();
String atualPassword = editTextPassword.getText().toString();
if(atualPassword.equals(newPassword))
{
...
}
else
{
...
}
Try:
if(editTextPassword.getText().toString().equals(editTextReEnterPassword.getText().toString()))
EditText is not a String

Categories

Resources