Store checkbox value to Firebase Database - java

I'm making an app and I need to register user. I also have two checkboxes where the user selects gender (male or female). I know that checkbox understand boolean values true or false, but I'm wondering how to do that with firebase.
This is exactly what I need to do:
image
Here what I've done:
private void SignUp(final String firstName, final String lastName, final String email, final String password, final String checkMale, final String checkFemale) {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
assert user != null;
String userId =user.getUid();
reference = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("id", userId);
hashMap.put("firstName", firstName);
hashMap.put("lastName", lastName);
hashMap.put("email", email.toLowerCase());
if(male.isChecked() && female.isChecked()) {
hashMap.put("male", checkMale);
hashMap.put("female", checkFemale);
}
reference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
pd.dismiss();
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Toast.makeText(RegisterActivity.this, "User Registered successfully", Toast.LENGTH_SHORT).show();
}
}
});
} else {
pd.dismiss();
Toast.makeText(RegisterActivity.this, "You can't register with this email or password", Toast.LENGTH_SHORT).show();
}
}
});
}
Any help is appreciated.

You can use Radio Buttons instead of checkbox.
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/malleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/femaleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
And in code you can check which is selected.
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.maleButton:
if (checked)
hashMap.put("male", true);
break;
case R.id.femaleButton:
if (checked)
hashMap.put("male", false);
break;
}
}
Also you do not need to store 2 variables in firebase male and female if users can choose only one. In other case(if users can choose both) store 2 variables and remove radiogroup so users can choose both.

I think in gender both can't checked at once and you kept && condition, so I would't work here:
if(male.isChecked() && female.isChecked()) {
hashMap.put("male", checkMale);
hashMap.put("female", checkFemale);
}
First of all do not need to save both value male & female. Just keep once key "gender" and specify one string or number e.g. 1 or "m" for male & 2 or "f" for female and save it along with all value.
Here you can use RadioButton inside RadioGroup 'gender' instead of only RadioButtons.
For your reference:
if(male.isChecked())
hashMap.put("gender", "m");
else
hashMap.put("gender", "f");

Use Radio Buttons in place of the checkbox.
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rdgGender"
android:orientation="vertical">
<RadioButton android:id="#+id/rbMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/rbFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
get RadioGroup id
RadioGroup rdgGender = findViewbyId(R.id.rdgGender);
on submit button click
public void onSubmitClick() {
boolean checkedId = rdgGender.getCheckedRadioButtonId();
switch(checkedId) {
case R.id.rbMale:
hashMap.put("gender", "Male");
break;
case R.id.rbFemale:
hashMap.put("gender", "Female");
break;
}
}

Related

A variable holds an unexpected value

I'm building a module for checking an answer in my Android java app and it doesn't work. While debugging it shows that the variable holds a value that is completely unexpected for it to hold. Could please someone explain what the problem might be? Here is the module:
private void QuizOperations() {
Toast.makeText(QuizActivity.this,"quizOperation", Toast.LENGTH_SHORT).show();
answered = true; // when the question is already answered Set bool to true
RadioButton rbSelected = findViewById(rbGroup.getCheckedRadioButtonId());
int indexofchild =rbGroup.indexOfChild(rbSelected) +1;
int answerNr = indexofchild +1;
checkSolution(answerNr,rbSelected);// method checks if the answer that is selected by the user corresponds to the answer in the database
}
The intended way was rbselected getting the index of the RadioButton pressed by the user, and than answerNr gets the index of this button as int. Than it passes in to the checksolution() function which checks if the AnswerNr corresponds to the right answer in the database. However, while debugging answerNr holds the value of 5 whichever button I press.
Debug screenshot
Let me know if any additional code needed. Thanks a lot
Here is a very minimalistic example on how to detect the view is being pressed, set/get id from tag.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:background="#333333">
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/radioButton1"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/radioButton2"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/radioButton3"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
private String[] answers = {
"January",
"February",
"March",
};
private RadioButton rb1, rb2, rb3;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rb1 = findViewById(R.id.radioButton1);
rb2 = findViewById(R.id.radioButton2);
rb3 = findViewById(R.id.radioButton3);
rb1.setTag("0");
rb2.setTag("1");
rb3.setTag("2");
rb1.setOnClickListener(this);
rb2.setOnClickListener(this);
rb3.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
final int index = Integer.parseInt((String)view.getTag());
switch(view.getId()) {
case R.id.radioButton1:
rb2.setChecked(false);
rb3.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton2:
rb1.setChecked(false);
rb3.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton3:
rb1.setChecked(false);
rb2.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
}
}
}

Android Material Button Toggle Group

I'm creating a form in android which asks for gender. To get this input I use Material Button Toggle Group which contains two buttons. I don't know how to know which button is clicked in my activity.java. How to get to know about the selected button in my activity so that i can save the details in different database.
myxml.xml
<com.google.android.material.button.MaterialButtonToggleGroup
android:id="#+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:singleSelection="true">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:layout_marginStart="5dp"
style="?attr/materialButtonOutlinedStyle"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:layout_marginStart="10dp"
style="?attr/materialButtonOutlinedStyle"/>
</com.google.android.material.button.MaterialButtonToggleGroup>
Myactivity.java
MaterialButtonToggleGroup toggleButton = findViewById(R.id.toggleButton);
toggleButton.addOnButtonCheckedListener();
// I CAN'T FIND ANY PROPER SOLUTION
You can use the getCheckedButtonId() method.
Something like:
MaterialButtonToggleGroup materialButtonToggleGroup =
findViewById(R.id.toggleButton);
int buttonId = materialButtonToggleGroup.getCheckedButtonId();
MaterialButton button = materialButtonToggleGroup.findViewById(buttonId);
Only if you need a listener you can use the addOnButtonCheckedListener:
materialButtonToggleGroup.addOnButtonCheckedListener(new MaterialButtonToggleGroup.OnButtonCheckedListener() {
#Override
public void onButtonChecked(MaterialButtonToggleGroup group, int checkedId, boolean isChecked) {
if (isChecked) {
if (checkedId == R.id.button1) {
//..
}
}
}
});
You have to check the checkedId value but also the isChecked value. The same listener is called when you check a button but also when you unckeck a button.
It means that if you click the button1 the listener is called with isChecked=true and checkedId=1. Then if you click the button2 the listener is called twice. Once with isChecked=false and checkedId=1, once with isChecked=true and checkedId=2.
You can do it like this :
toggleButton.addOnButtonCheckedListener(new MaterialButtonToggleGroup.OnButtonCheckedListener() {
#Override
public void onButtonChecked(MaterialButtonToggleGroup group, int checkedId, boolean isChecked) {
if(group.getCheckedButtonId()==R.id.button1)
{
//Place code related to button1 here
Toast.makeText(MainActivity2.this, "Button1 Clicked", Toast.LENGTH_SHORT).show();
}else if(group.getCheckedButtonId()==R.id.button2) {
//Place code related to button 2 here
Toast.makeText(MainActivity2.this, "Button2 Clicked", Toast.LENGTH_SHORT).show();
}
}
});

Error getting in validation

I am working on android application in my application there are registration page in that page i am using #slackid, when user fill the registration form and enter slack id without # its show validation message like # is necessary. Than he move to the next. Kindly please tell me how i use this # validation message. Here is the code
activity_registration.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".RegisterActivity">
<EditText
android:id="#+id/name_reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Your Name"/>
<EditText
android:id="#+id/email_reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Your email id"
android:inputType="textEmailAddress"/>
<EditText
android:id="#+id/slackid_reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint=" #slackId"/>
<EditText
android:id="#+id/password_reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"/>
<EditText
android:id="#+id/confirm_password_reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Retype Password"/>
<EditText
android:id="#+id/info_reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Information/Phone no/Optional"/>
<Button
android:id="#+id/register_reg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:text="Register"/>
</LinearLayout>
RegistrationActivity.java
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
private EditText name,emailId,slackId,password,conPasword,info;
private Button registerB;
// Alert dialog
AlertDialog.Builder alertBuilder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
name = findViewById(R.id.name_reg);
emailId = findViewById(R.id.email_reg);
slackId = findViewById(R.id.slackid_reg);
password = findViewById(R.id.password_reg);
conPasword = findViewById(R.id.confirm_password_reg);
info = findViewById(R.id.info_reg);
registerB = findViewById(R.id.register_reg);
//set register to onClick event
registerB.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.register_reg:
// Check all requir field empty or not
//Apply the validation in each field including slack Id
if(name.getText().toString().length()==0) {
name.setError("Name cannot be blank");
}
if(emailId.getText().toString().equals("")) {
emailId.setError("Email cannot be blank");
}
if(String.valueOf(slackId.getText().toString().charAt(0)).equals("#")) {
slackId.setError("Slack id cannot be blank");
}
if (password.getText().toString().equals("")) {
password.setError("password cannot be blank");
}
if(conPasword.getText().toString().equals("")) {
conPasword.setError("confirm password cannot be blank");
// if any of the required field empty "Show Dialog to fill the required field
alertBuilder = new AlertDialog.Builder(RegisterActivity.this);
alertBuilder.setTitle("Something Wrong");
alertBuilder.setMessage("Please Fill all required field");
alertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = alertBuilder.create();
alertDialog.show();
}else if(!(password.getText().toString().equals(conPasword.getText().toString()))){
//check pasword and confirm pasword mismatch
alertBuilder = new AlertDialog.Builder(RegisterActivity.this);
alertBuilder.setTitle("Something Wrong");
alertBuilder.setMessage("Pasword Mismatch");
alertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
password.setText("");
conPasword.setText("");
}
});
AlertDialog alertDialog = alertBuilder.create();
alertDialog.show();
}else{
// Background task to insert user information into database
BackgroundLoginTask backgroundLoginTask = new BackgroundLoginTask(RegisterActivity.this);
backgroundLoginTask.execute("register",name.getText().toString(),
emailId.getText().toString(),
slackId.getText().toString(),
password.getText().toString(),
info.getText().toString());
}
break;
}
}
}
Try :
edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if(!edittext.getText().toString().contains("#")) {
edittext.setError("# not detected");
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
If you want something that the id should start with # then can use this pattern : ^#.*
You can blank validation by using TextUtils.isEmpty(slackId.getText().toString())
This will check if text is null or empty
In your code you did validation like
if(String.valueOf(slackId.getText().toString().charAt(0)).equals("#")) {
slackId.setError("Slack id cannot be blank");
}
this will not validate weather is contains # or not.
do this:
if(!slackId.getText().toString().contains("#")){
//show your error message here
}
Hope it will help you!!
You can make a validation like
if(!slackId.getText().toString().contains("#")){}
You can use this as its better than using textChange listener for your case to check the text edit after losing focus , which will give you the needed validation without submitting .
EditText ed= (EditText) findViewById(R.id.edittxt);
ed.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus && !ed.getText().toString().contains("#")) {
ed.setError("# not detected")
}
}
});

Android - Radiobutton click event to go to new activity

I would like to do something like a small selection form.
I would like to do a click event where if I select one of the first radiogroup and another one of the second it takes me to a new activity.
I got two radiogroups with two radiobuttons inside each.
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/physic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="physic"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/math"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="math"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/theories"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="theories"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/problems_solving"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="problem solving"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
I declared my buttons and tried to use onRadioButtonClicked like below:
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.math:
if (checked)
switch(view.getId()) {
case R.id.problems_solving:
if (checked)
showFirstWord("math problem resolution");
break;
case R.id.theories:
if (checked)
showSecondWord("math theories");
break;
}
break;
case R.id.physic:
if (checked)
switch(view.getId()) {
case R.id.problems_solving:
if (checked)
showThirdWord("physic problem solving");
break;
case R.id.theories:
if (checked)
showFourthWord("physic theories");
break;
}
break;
}
}
I want the strings in the functions to appear in a text view in the other activities like below:
private void showFirstWord (String text) {
Intent first_word = new Intent(this, FirstActivity.class);
first_word.putExtra("key", text);
startActivity(first_word);
}
private void showSecondWord (String text) {
Intent second_word = new Intent(this, SecondActivity.class);
second_word.putExtra("key", text);
startActivity(second_word);
}
private void showThirdWord (String text) {
Intent third_word = new Intent(this, ThirdActivity.class);
third_word.putExtra("key", text);
startActivity(third_word);
}
private void showFourthWord (String text) {
Intent fourth_word = new Intent(this, FourthActivity.class);
fourth_word.putExtra("key", text);
startActivity(fourth_word);
}
I tried to follow this page from Android developers but I'm still not sure what to do with it: https://stuff.mit.edu/afs/sipb/project/android/docs/guide/topics/ui/controls/radiobutton.html
My method doesn't seem to be correct ass I can't get the strings to appear in the other activities. Is my reasonning ok for now or should I study another method?
Thanks :)
You can simplified your code onRadioButtonClicked just create first a String variable called subjectSelected.
then:
private String subjectSelected = "";
public void onRadioButtonClicked(View view) {
RadioButton radioButton = (RadioButton) view;
switch(view.getId()) {
case R.id.math:
subjectSelected = radioButton.getText().toString();
break;
case R.id.physic:
subjectSelected = radioButton.getText().toString();
break;
case R.id.problems_solving:
if (subjectSelected.equals("math")) {
showFirstWord ("math problem resolution");
} else if (subjectSelected.equals("physic")) {
showThirdWord("physic problem solving");
}
break;
case R.id.theories:
if (subjectSelected.equals("math")) {
showSecondWord("math theories");
} else if (subjectSelected.equals("physic")) {
showFourthWord("physic theories");
}
break;
}
}
and to display the text you pass to another activity. Use a Bundle to get the value of your key.
e.g.:
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
Bundle bundle = getIntent().getExtras();
String key = bundle.getString("key");
TextView textView = (TextView) findViewById(R.id.textView1); // Replace the textView1 with the id you set to your textview.
textView.setText(key);
}
}
You can copy the codes of your FirstActivity and paste to your SecondActivity, ThirdActivity and FourthActivity to get the key.
String str; // store the text corresponding to the RadioButton which is clicked
switch(view.getId()) {
case R.id.radioButton1:
if (checked)
str = "button1Text";
break;
case R.id.radioButton2:
if (checked)
str = "button2Text";
break;
case R.id.radioButton3:
if (checked)
str = "button3Text";
break;
}
Intent intent = new Intent(this, WinderDTActivity.class);
intent.putExtra("radioChosen", str); // pass "str" to the next Activity

Java EditText not validating correctly

Can someone help with this? My EditText is not empty but the toast still shows up. My app require users to select Date and Time, then select 1 item on the listview to proceed. A dialog will pop out after that. However for some reason, even though my edittext isn't empty, it still won't allow me to continue. I can't seem to figure out what's wrong, I mean the code is just that simple, nothing complicate.
final String date = textDate1.getText().toString().trim();
final String time = textTime1.getText().toString().trim();
listViewHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final Team team = teams.get(i);
if(TextUtils.isEmpty(date)){
Toast.makeText(RecreateActivity.this,"Please choose a date.",Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(time)){
Toast.makeText(RecreateActivity.this,"Please choose a time.",Toast.LENGTH_LONG).show();
return;
}
//the rest of the code
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(RecreateActivity.this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.confirm_layout, null);
dialogBuilder.setView(dialogView);
final Button buttonYes2 = (Button) dialogView.findViewById(R.id.buttonYes2);
final Button buttonNo2 = (Button) dialogView.findViewById(R.id.buttonNo2);
//final Team team = teams.get();
final AlertDialog b = dialogBuilder.create();
b.show();
buttonYes2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
databaseMembers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final ArrayList<String> CheckList = new ArrayList<String>();
for (DataSnapshot check : dataSnapshot.child("teams").getChildren()) {
CheckList.add(check.getKey());
}
if (CheckList.contains(team.getTeamName())) {
Toast.makeText(RecreateActivity.this, "Team already exist.", Toast.LENGTH_LONG).show();
return;
}
databaseMembers.child("History").child(team.getTeamName()).child("date").setValue(date);
databaseMembers.child("History").child(team.getTeamName()).child("time").setValue(time);
for (DataSnapshot history : dataSnapshot.child("History").child(encodedEmailAddress).getChildren()) {
String key = history.getKey();
if (key.equals(team.getTeamName())) {
teams.clear();
Team team = history.getValue(Team.class);
teams.add(team);
databaseTeams.child(team.getTeamName()).setValue(team);
}
if (key.equals("teamMember")) {
for (DataSnapshot members : dataSnapshot.child("History").child(encodedEmailAddress).child("teamMember").getChildren()) {
String key2 = members.getKey();
String value = members.getValue(String.class);
Map<String, Object> map = new HashMap<>();
map.put(key2, value);
databaseMembers.child("members").child(team.getTeamName()).child("teamMember").updateChildren(map);
b.dismiss();
}
}
}
Toast.makeText(RecreateActivity.this, "Team created.", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(RecreateActivity.this,
MainActivity.class);
startActivity(myIntent);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
XML:
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Previous Team"
android:textAppearance="#style/TextAppearance.AppCompat.Title"
android:textAlignment="center"/>
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select new Date/Time and tap on the Team."
android:textAlignment="center"/>
<ListView
android:id="#+id/listViewHistory"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</ListView>
<TextView
android:id="#+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Members:"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
<TextView
android:id="#+id/textViewList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="#style/TextAppearance.AppCompat.Medium" />
<EditText
android:id="#+id/textDate1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Select Date..."
android:layout_alignParentStart="true" />
<EditText
android:id="#+id/textTime1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Select Time..."
android:layout_below="#+id/textDate"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/buttonAddHistory"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create Team"
android:textAlignment="center"
android:textAllCaps="false"
tools:textSize="20sp" />
You are getting string from EditText only once - before setting OnItemClickListener. You need to get string inside the listener.
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final Team team = teams.get(i);
final String date = textDate1.getText().toString().trim();
final String time = textTime1.getText().toString().trim();
if(TextUtils.isEmpty(date)){
Toast.makeText(RecreateActivity.this,"Please choose a date.",Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(time)){
Toast.makeText(RecreateActivity.this,"Please choose a time.",Toast.LENGTH_LONG).show();
return;
}
}
Your field is initialized only once. I don't know the context, this may be actually what you want, but then it doesn't make any sense to validate it every time, those fields have the same value every time the listener code is run. Try to add the code to get date and time in the listener itself.
Your code is setting [date] and [time] outside of the onClickListener. When the user clicks the button, your code isn't resetting the variables. I'd evaluate the EditText directly from your onClickListener code:
listViewHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final Team team = teams.get(i);
if(TextUtils.isEmpty(textDate1.getText().toString().trim())){
Toast.makeText(RecreateActivity.this,"Please choose a date.",Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(textTime1.getText().toString().trim())){
Toast.makeText(RecreateActivity.this,"Please choose a time.",Toast.LENGTH_LONG).show();
return;
}
Try getting date value of edittext inside the click listener.
listViewHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final Team team = teams.get(i);
final String date = textDate1.getText().toString().trim();
final String time = textTime1.getText().toString().trim();
if(date.isEmpty()){
Toast.makeText(RecreateActivity.this,"Please choose a date.",Toast.LENGTH_LONG).show();
return;
}
if(time.isEmpty()){
Toast.makeText(RecreateActivity.this,"Please choose a time.",Toast.LENGTH_LONG).show();
return;
}

Categories

Resources