One Linearlayout I have created and dynamically I am adding RadioGroup and textView in it. When next time I am calling the method, Textview is getting removed but old radio buttons are not getting removed.
Here is the code:
public void setShippingMethods() {
shippingChargesLayout.removeAllViews();
final RadioGroup radioGroup = new RadioGroup(getActivity());
radioGroup.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(getActivity());
textView.setText("Select Shipping Options:");
shippingChargesLayout.addView(textView);
for (int i = 0; i < shippingDetailsList.size(); i++) {
RadioButton radioButton = new RadioButton(getActivity());
radioButton.setText("" + shippingDetailsList.get(i).getMethodTitle() + "-" + (new SessionManager(getActivity()).getCurrency()) + df.format(shippingDetailsList.get(i).getAmount()));
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
radioGroup.addView(radioButton, params);
radioButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
shippingChargesLayout.addView(radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
shipmentCode = shippingDetailsList.get(i - 1).getCarrierCode();
Log.v("carrierCode", "" + shipmentCode);
}
});
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getActivity(),"Select shipping options.",Toast.LENGTH_LONG).show();
} else {
completeOrder();
}
}
});
}
Here is the image:
I have made some changes in your code.
public void setShippingMethods() {
shippingChargesLayout.removeAllViews();
final RadioGroup radioGroup = new RadioGroup(getActivity());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
radioGroup.setLayoutParams(params);
radioGroup.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(getActivity());
textView.setText("Select Shipping Options:");
shippingChargesLayout.addView(textView);
for (int i = 0; i < shippingDetailsList.size(); i++) {
RadioButton radioButton = new RadioButton(getActivity());
radioButton.setText("" + shippingDetailsList.get(i).getMethodTitle() + "-" + (new SessionManager(getActivity()).getCurrency()) + df.format(shippingDetailsList.get(i).getAmount()));
radioGroup.addView(radioButton);
}
shippingChargesLayout.addView(radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
shipmentCode = shippingDetailsList.get(i - 1).getCarrierCode();
Log.v("carrierCode", "" + shipmentCode);
}
});
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getActivity(),"Select shipping options.",Toast.LENGTH_LONG).show();
} else {
completeOrder();
}
}
});
}
Related
I have a radioGroup that is populated dynamically since I don't know how many elements are going to be within it (it is being populated by a database). The problem is when I use setOnCheckedChangeListener with it, it won't work at all. I tried creating a toast to see if it's even getting called, and the toast didn't even fire!
Here is a copy of the class that contains the radio group as well as the setOnCheckedChange method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_add_payment, container, false);
addPayment = v.findViewById(R.id.btn_add_payment);
totalPaymentTV = v.findViewById(R.id.tv_total_payment);
radioGroup0 = v.findViewById(R.id.rg_select_subject);
datePickerTV = v.findViewById(R.id.tv_date_picker);
radioGroup = v.findViewById(R.id.rg_add_payment);
numberPicker = v.findViewById(R.id.numberPicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(10);
hoursTeached = 0;
teacherFee = 0;
date = new String();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
Toast.makeText(getContext(),"hello ",Toast.LENGTH_SHORT).show();
schoolViewModel.getTeacherByID(i).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
#Override
public void onChanged(Teacher teacher) {
teacherFee = teacher.getFee();
totalPaymentTV.setText(teacherFee * hoursTeached + " DA");
}
});
}
});
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int hours) {
if (!(radioGroup.getCheckedRadioButtonId() == -1)) {
schoolViewModel.getTeacherByID(radioGroup.getCheckedRadioButtonId()).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
#Override
public void onChanged(Teacher teacher) {
teacherFee = teacher.getFee();
hoursTeached = hours;
totalPaymentTV.setText(teacherFee * hours + " DA");
}
});
}
}
});
datePickerTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pickADate();
}
});
schoolViewModel = new ViewModelProvider(this).get(SchoolViewModel.class);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
schoolViewModel.getSingleTeacherWithSubjects(i).observe(getViewLifecycleOwner(), new Observer<TeacherWithSubjects>() {
#Override
public void onChanged(TeacherWithSubjects teacherWithSubjects) {
if (teacherWithSubjects.subjects.size() > 1) {
openDialog(teacherWithSubjects.subjects, radioGroup0);
} else {
subject = teacherWithSubjects.subjects.get(0);
}
}
});
}
});
schoolViewModel.getAllTeachers().observe(getViewLifecycleOwner(), new Observer<List<Teacher>>() {
#Override
public void onChanged(List<Teacher> teachers) {
addRadioButtons(teachers, radioGroup);
}
});
addPayment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getContext(), "Choose a Teacher!!", Toast.LENGTH_SHORT).show();
return;
}
if (subject == null) {
Toast.makeText(getContext(), "Choose a Subject", Toast.LENGTH_SHORT).show();
return;
}
if (date.isEmpty()) {
Toast.makeText(getContext(), "Pick a Date", Toast.LENGTH_SHORT).show();
return;
}
if(hoursTeached == 0){
Toast.makeText(getContext(),"Choose how many hours have been teached!!",Toast.LENGTH_SHORT).show();
return;
}
SubjectTeacherCrossRef crossRef = new SubjectTeacherCrossRef(subject.getSubjectName(),radioGroup.getCheckedRadioButtonId());
int totalPayment = (hoursTeached*teacherFee);
schoolViewModel.addPayment(new Payment(crossRef,date,hoursTeached,totalPayment));
}
});
return v;
}
private void addRadioButtons(List<Teacher> teachers, RadioGroup radioGroup) {
for (Teacher i : teachers) {
//instantiate...
RadioButton radioButton = new RadioButton(getContext());
//set the values that you would otherwise hardcode in the xml...
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 25;
params.leftMargin = 20;
params.rightMargin = 20;
params.topMargin = 20;
radioButton.setLayoutParams(params);
//label the button...
radioButton.setBackground(new ColorDrawable(Color.TRANSPARENT));
radioButton.setMinWidth(250);
radioButton.setBackgroundResource(R.drawable.custom_checkbox);
radioButton.setElevation(16);
radioButton.setGravity(Gravity.CENTER);
radioButton.setText(i.getTeacherName());
radioButton.setPadding(50, 100, 50, 100);
radioButton.setButtonDrawable(R.drawable.custom_checkbox);
radioButton.setId(i.getTeacherId());
//add it to the group.
radioGroup.addView(radioButton);
}
}
void openDialog(List<Subject> subjects, RadioGroup radioGroup) {
dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.choose_teached_subject_dialog);
dialog.setCancelable(false);
radioGroup = dialog.findViewById(R.id.rg_select_subject);
Button confirmSubject = dialog.findViewById(R.id.btn_choose_subject);
Button cancelSubject = dialog.findViewById(R.id.btn_dont_choose_subject);
//populate the checkBox
for (int i = 0; i < subjects.size(); i++) {
RadioButton radioButton1 = new RadioButton(dialog.getContext());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 25;
params.leftMargin = 20;
params.rightMargin = 20;
params.topMargin = 20;
radioButton1.setLayoutParams(params);
radioButton1.setBackground(new ColorDrawable(Color.TRANSPARENT));
radioButton1.setMinWidth(250);
radioButton1.setBackgroundResource(R.drawable.custom_checkbox);
radioButton1.setElevation(16);
radioButton1.setGravity(Gravity.CENTER);
radioButton1.setId(i);
radioButton1.setText(subjects.get(i).getSubjectName());
radioButton1.setPadding(50, 100, 50, 100);
radioButton1.setButtonDrawable(R.drawable.custom_checkbox);
//add it to the group.
radioGroup.addView(radioButton1);
}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
dummySubject = subjects.get(i);
Toast.makeText(getContext(), dummySubject.getSubjectName(), Toast.LENGTH_SHORT).show();
}
});
confirmSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (dummySubject == null) {
Toast.makeText(getContext(), "Choose A Subject", Toast.LENGTH_SHORT).show();
} else {
subject = dummySubject;
dummySubject = null;
dialog.dismiss();
}
}
});
cancelSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dummySubject = null;
dialog.dismiss();
}
});
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.show();
}
void pickADate() {
DatePickerDialog datePickerDialog = new DatePickerDialog(
getContext(), this,
Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.show();
}
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
date = day + "/" + (month + 1) + "/" + year;
datePickerTV.setText(date);
}
}
i have a problem with radioGroup.setOnCheckedChangeListener and i dont know to fix it
I have a fragment that is used to gather data and create a new instance of payment class.
the problem that i am facing is when i try to reselect the teacher after choosing how many hours have been teached the total doesnt get updated, i know that the code responsible for updating the total is tied to the spinner but i tried to create an independent "setOnCheckedChangeListener" on the radio group but it still fails to update the total.
here is a screenshot of the UI so u can better understand what am talking about
here is the code for java class responsible for this part :
public class addPaymentFragment extends Fragment implements DatePickerDialog.OnDateSetListener {
private RadioGroup radioGroup;
private RadioButton radioButton;
private SchoolViewModel schoolViewModel;
private NumberPicker numberPicker;
private Button addPayment;
private Subject dummySubject, subject;
private Dialog dialog;
private RadioGroup radioGroup0;
private TextView datePickerTV, totalPaymentTV;
private String date;
private int hoursTeached, teacherFee;
private Payment payment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_add_payment, container, false);
addPayment = v.findViewById(R.id.btn_add_payment);
totalPaymentTV = v.findViewById(R.id.tv_total_payment);
radioGroup0 = v.findViewById(R.id.rg_select_subject);
datePickerTV = v.findViewById(R.id.tv_date_picker);
radioGroup = v.findViewById(R.id.rg_add_payment);
numberPicker = v.findViewById(R.id.numberPicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(10);
hoursTeached = 0;
teacherFee = 0;
date = new String();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
schoolViewModel.getTeacherByID(i).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
#Override
public void onChanged(Teacher teacher) {
teacherFee = teacher.getFee();
totalPaymentTV.setText(teacherFee * hoursTeached + " DA");
}
});
}
});
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int hours) {
if (!(radioGroup.getCheckedRadioButtonId() == -1)) {
schoolViewModel.getTeacherByID(radioGroup.getCheckedRadioButtonId()).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
#Override
public void onChanged(Teacher teacher) {
teacherFee = teacher.getFee();
hoursTeached = hours;
totalPaymentTV.setText(teacherFee * hours + " DA");
}
});
}
}
});
datePickerTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pickADate();
}
});
schoolViewModel = new ViewModelProvider(this).get(SchoolViewModel.class);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
schoolViewModel.getSingleTeacherWithSubjects(i).observe(getViewLifecycleOwner(), new Observer<TeacherWithSubjects>() {
#Override
public void onChanged(TeacherWithSubjects teacherWithSubjects) {
if (teacherWithSubjects.subjects.size() > 1) {
openDialog(teacherWithSubjects.subjects, radioGroup0);
} else {
subject = teacherWithSubjects.subjects.get(0);
}
}
});
}
});
schoolViewModel.getAllTeachers().observe(getViewLifecycleOwner(), new Observer<List<Teacher>>() {
#Override
public void onChanged(List<Teacher> teachers) {
addRadioButtons(teachers, radioGroup);
}
});
addPayment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getContext(), "Choose a Teacher!!", Toast.LENGTH_SHORT).show();
return;
}
if (subject == null) {
Toast.makeText(getContext(), "Choose a Subject", Toast.LENGTH_SHORT).show();
return;
}
if (date.isEmpty()) {
Toast.makeText(getContext(), "Pick a Date", Toast.LENGTH_SHORT).show();
return;
}
if(hoursTeached == 0){
Toast.makeText(getContext(),"Choose how many hours have been teached!!",Toast.LENGTH_SHORT).show();
return;
}
SubjectTeacherCrossRef crossRef = new SubjectTeacherCrossRef(subject.getSubjectName(),radioGroup.getCheckedRadioButtonId());
int totalPayment = hoursTeached*teacherFee;
payment = new Payment(crossRef,date,totalPayment);
}
});
return v;
}
private void addRadioButtons(List<Teacher> teachers, RadioGroup radioGroup) {
for (Teacher i : teachers) {
//instantiate...
RadioButton radioButton = new RadioButton(getContext());
//set the values that you would otherwise hardcode in the xml...
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 25;
params.leftMargin = 20;
params.rightMargin = 20;
params.topMargin = 20;
radioButton.setLayoutParams(params);
//label the button...
radioButton.setBackground(new ColorDrawable(Color.TRANSPARENT));
radioButton.setMinWidth(250);
radioButton.setBackgroundResource(R.drawable.custom_checkbox);
radioButton.setElevation(16);
radioButton.setGravity(Gravity.CENTER);
radioButton.setText(i.getTeacherName());
radioButton.setPadding(50, 100, 50, 100);
radioButton.setButtonDrawable(R.drawable.custom_checkbox);
radioButton.setId(i.getTeacherId());
//add it to the group.
radioGroup.addView(radioButton);
}
}
void openDialog(List<Subject> subjects, RadioGroup radioGroup) {
dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.choose_teached_subject_dialog);
dialog.setCancelable(false);
radioGroup = dialog.findViewById(R.id.rg_select_subject);
Button confirmSubject = dialog.findViewById(R.id.btn_choose_subject);
Button cancelSubject = dialog.findViewById(R.id.btn_dont_choose_subject);
//populate the checkBox
for (int i = 0; i < subjects.size(); i++) {
RadioButton radioButton1 = new RadioButton(dialog.getContext());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 25;
params.leftMargin = 20;
params.rightMargin = 20;
params.topMargin = 20;
radioButton1.setLayoutParams(params);
radioButton1.setBackground(new ColorDrawable(Color.TRANSPARENT));
radioButton1.setMinWidth(250);
radioButton1.setBackgroundResource(R.drawable.custom_checkbox);
radioButton1.setElevation(16);
radioButton1.setGravity(Gravity.CENTER);
radioButton1.setId(i);
radioButton1.setText(subjects.get(i).getSubjectName());
radioButton1.setPadding(50, 100, 50, 100);
radioButton1.setButtonDrawable(R.drawable.custom_checkbox);
//add it to the group.
radioGroup.addView(radioButton1);
}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
dummySubject = subjects.get(i);
Toast.makeText(getContext(), dummySubject.getSubjectName(), Toast.LENGTH_SHORT).show();
}
});
confirmSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (dummySubject == null) {
Toast.makeText(getContext(), "Choose A Subject", Toast.LENGTH_SHORT).show();
} else {
subject = dummySubject;
dummySubject = null;
dialog.dismiss();
}
}
});
cancelSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dummySubject = null;
dialog.dismiss();
}
});
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.show();
}
void pickADate() {
DatePickerDialog datePickerDialog = new DatePickerDialog(
getContext(), this,
Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.show();
}
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
date = day + "/" + (month + 1) + "/" + year;
datePickerTV.setText(date);
}
}
Sorry if my question is so clear and please let me know if i need to provide any more information and thanks!
public class MainActivity extends AppCompatActivity {
int foulCounterA = 0;
int scoreOnePointTeamA = 0;
int periodCount = 0;
private TextView tv1;
private TextView period;
private Button startbtn, cancelbtn;
private ToggleButton togbtn;
private boolean isPaused = false;
private boolean isCanceled = false;
private long remainingTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
period = (TextView) findViewById(R.id.period_number);
startbtn = (Button) findViewById(R.id.startBtn);
cancelbtn = (Button) findViewById(R.id.cancelBtn);
togbtn = (ToggleButton) findViewById(R.id.togBtn);
cancelbtn.setEnabled(false);
togbtn.setEnabled(false);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
foulCounterA = 0;
foulCounterB = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
if (periodCount < 3)
periodCount = periodCount + 1;
else periodCount = 4;
period.setText("Period " + periodCount);
startbtn.setEnabled(false);
cancelbtn.setEnabled(true);
togbtn.setEnabled(true);
isPaused = false;
isCanceled = false;
long millisInFuture = 20000; /////20sec
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
});
togbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (togbtn.isChecked()) {
isPaused = true;
} else {
isPaused = false;
long millisInFuture = remainingTime;
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
}
});
cancelbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isCanceled = true;
period.setText("Period");
tv1.setText("Timer");
startbtn.setEnabled(true);
togbtn.setEnabled(false);
cancelbtn.setEnabled(false);
foulCounterA = 0;
foulCounterB = 0;
periodCount = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
}
});
}
public void onePointForTeamA(View v) {
scoreTeamA = scoreTeamA + 1;
scoreOnePointTeamA = scoreOnePointTeamA + 1;
displayForTeamA(scoreTeamA);
displayForTeamAOnePoint(scoreOnePointTeamA);
}
public void foulCountForTeamA(View v) {
if (foulCounterA < 5)
foulCounterA = foulCounterA + 1;
else
foulCounterA = 5;
displayForTeamAFoul(foulCounterA);
}
public void displayForTeamAOnePoint(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_score_1_point);
scoreView.setText(String.valueOf(score));
}
public void displayForTeamAFoul(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_foul);
scoreView.setText(String.valueOf(score));
}
}
I wanted to make the java code as simple as I can so I've just added the lines for my question. What I'm trying to do is
android:onClick="onePointForTeamA"make this button only clickable when foulCounterA = 5 Failed to add if (foulCounterA = 5); inside public void foulCountForTeamA(View v) {
It gave me an error that way. Says required: boolean, found: int.
What should I do with the code? Any help will be appreeciated
Regarding your concrete question, the syntax of if (foulCounterA = 5); is wrong, because the equation check is have to made by == operator.
So the correct syntax would be if (foulCounterA == 5);
As #OH GOD SPIDERS wrote in the comment, you should check the basics of java operators.
Also I recommend You to search for the answer before asking a new question.
I have an activity named EfortActivity which contains 3 EditText, a Spinner, a RadioGroup and a Button - saveButton. My goal is to add data dynamically in a ListView (the listView is implemented in another activity called HistoryActivity).
The problem is that when I click on the saveButton my app crash.
Here is the code in EfortActivity:
public class EfortMonitorizareActivity extends AppCompatActivity {
RadioGroup radioGroupDaNu;
Spinner spinnerTip;
EditText editTextDurata;
EditText editTextInainte;
EditText editTextDupa;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_efort_monitorizare);
intent = getIntent();
initializareComponente();
}
private void initializareComponente() {
radioGroupDaNu = (RadioGroup) findViewById(R.id.rg_activitateDANU);
spinnerTip = (Spinner) findViewById(R.id.spin_tip_efort);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(),
R.array.TipEfort, R.layout.support_simple_spinner_dropdown_item);
spinnerTip.setAdapter(adapter);
editTextDurata = (EditText) findViewById(R.id.edt_durataAnt_efort);
editTextInainte = (EditText) findViewById(R.id.edt_greuteInainteAnt_efort);
editTextDupa = (EditText) findViewById(R.id.edt_greutateDupaAnt_efort);
Button btn_inregistrareDate = (Button) findViewById(R.id.btn_adaugaDate_efort);
btn_inregistrareDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validare()) {
Efort efort = createPlayerFromComponents();
if (efort != null) {
intent.putExtra(Constants.ADD_EFORT_KEY,efort);
setResult(RESULT_OK,intent);
finish();
}
}
}
});
}
private Efort createPlayerFromComponents() {
RadioButton checkDaNu = (RadioButton) findViewById(radioGroupDaNu.getCheckedRadioButtonId());
String radioDaNu = checkDaNu.getText().toString();
String tip = spinnerTip.getSelectedItem().toString();
Integer durata = Integer.parseInt(editTextDurata.getText().toString());
Integer inainte = Integer.parseInt(editTextInainte.getText().toString());
Integer dupa = Integer.parseInt(editTextDupa.getText().toString());
return new Efort(radioDaNu, tip, durata, inainte, dupa);
}
private boolean validare() {
RadioButton nu = (RadioButton) findViewById(R.id.button_nu_efort);
if (editTextDurata.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
return false;
}
if (editTextInainte.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
return false;
}
if (editTextDupa.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
return false;
} }
Here is the code for HistoryActivity:
public class IstoricActivity extends AppCompatActivity {
ListView lvEfort;
List<String> listaEfort = new ArrayList<>();
Button deconectare;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_istoric);
deconectare=(Button)findViewById(R.id.btn_deconectareIstoric);
deconectare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
//initializare componente
lvEfort = (ListView) findViewById(R.id.lw_listaEfort);
Efort efortDefault = new Efort("Da", "Tennis", 40, 55, 53);
listaEfort.add(efortDefault.toString());
//declarare + initializare adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, listaEfort);
lvEfort.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
And the class Efort:
public class Efort implements Parcelable {
private String radioDaNu;
private String tip;
private Integer durata;
private Integer inainte;
private Integer dupa;
public Efort(String radioDaNu, String tip, Integer durata, Integer inainte, Integer dupa) {
this.radioDaNu = radioDaNu;
this.tip = tip;
this.durata = durata;
this.inainte = inainte;
this.dupa = dupa;
}
public String getRadioDaNu() {
return radioDaNu;
}
public void setRadioDaNu(String radioDaNu) {
this.radioDaNu = radioDaNu;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
public Integer getDurata() {
return durata;
}
public void setDurata(Integer durata) {
this.durata = durata;
}
public Integer getInainte() {
return inainte;
}
public void setInainte(Integer inainte) {
this.inainte = inainte;
}
public Integer getDupa() {
return dupa;
}
public void setDupa(Integer dupa) {
this.dupa = dupa;
}
#Override
public String toString() {
return "Efort{" +
// ", datePicker=" + datePicker +
", Activitate efort :" + radioDaNu +
", tip : '" + tip + '\'' +
", tipm de : " + durata +
", inainte de antrenamnet aveam : " + inainte +
", dupa antrenamnet am : " + dupa +
'}';
}
public Efort(Parcel in) {
this.radioDaNu = in.readString();
this.tip = in.readString();
this.durata = in.readInt();
this.inainte = in.readInt();
this.dupa = in.readInt();
}
public static Parcelable.Creator<Efort> CREATOR = new Creator<Efort>() {
#Override
public Efort createFromParcel(Parcel parcel) {
return new Efort(parcel);
}
#Override
public Efort[] newArray(int i) {
return new Efort[i];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(radioDaNu);
parcel.writeString(tip);
parcel.writeInt(durata);
parcel.writeInt(inainte);
parcel.writeInt(dupa);
}
}
When you called,
finish()
it will stop your activity and finish it. Please remove that finish()
I have an autogenerated list of edittexts gotten from the user input. What i want to do is shuffle the edittexts when the shuffle button is clicked or get the texts and set them to different edittexts. What i tried doing is to get the texts of each edittext adding it to an arraylist and shuffling it and then recreating the layout with the shuffled list. But that in itself is giving me errors. When the shuffle button is clicked it gives me this error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
Thanks For the help
`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnForCreate = (Button) findViewById(R.id.btnCreateTxt);
editTextForInputToCreate = (EditText) findViewById(R.id.textForInputToCreate);
listLayout = (LinearLayout) findViewById(R.id.listLayout);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnShuffleTxt = (Button) findViewById(R.id.btnShuffleTxt);
editTextForInputToCreate.animate().translationX(-1000f);
btnForCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bringTextInputBackOnScreen();
}
});
btnDisplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (editTextForInputToCreate.getText().toString().length() >= 0) {
try {
listLayout.removeAllViews();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
length = Integer.parseInt(editTextForInputToCreate.getText().toString());
for (i = 0; i < length; i++) {
editTextCollection = new EditText[length];
editText = new EditText(MainActivity.this);
editText.setId(i + 1);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("Input" + " " + (i + 1));
listLayout.addView(editText);
editTextCollection[i] = editText;
}
}
});
btnShuffleTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listLayout.removeAllViews();
for (EditText gottenEditText:editTextCollection)
{
String gottenTexts = gottenEditText.getText().toString();
list.add(gottenTexts);
}
Collections.shuffle(list);
}
});
}
private void bringTextInputBackOnScreen()
{
editTextForInputToCreate.animate().translationXBy(1000f).setDuration(2000);
}
`
Please make some corrections in your EditTextCollection.
editTextCollection = new EditText[length];// initialization outside the loop
for (i = 0; i < length; i++) {
editText = new EditText(MainActivity.this);
editText.setId(i + 1);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("Input" + " " + (i + 1));
listLayout.addView(editText);
editTextCollection[i] = editText;
}
btnShuffleTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listLayout.removeAllViews();
for (EditText gottenEditText:editTextCollection)
{
String gottenTexts = gottenEditText.getText().toString();
list.add(gottenTexts);
}
Collections.shuffle(list);
for (EditText gottenEditText:editTextCollection)
{
gottenEditText.setText(list.get(editTextCollection.indexOf(gottenEditText)));
}
}
});