Im making a cgpa calculator in android studio but app crash on following line always.gpa=Double.parseDouble(marks_et.getText().toString());
complete code is here.
public class CgpaActivity extends AppCompatActivity {
GridLayout DynamicEditTextHolder;
EditText edtNoCreate,marks_et,cr_et,cgpa_ET;
Button btnCreate,CalculateGPA;
TextView course;
double cgpa = 0,gpa,sumgpa = 0;
int i,length;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cgpa);
DynamicEditTextHolder = findViewById(R.id.DynamicEditTextHolder);
edtNoCreate = (EditText) findViewById(R.id.edtNoCreate);
cgpa_ET=findViewById(R.id.cgpa_ET);
btnCreate = (Button) findViewById(R.id.btnCreate);
CalculateGPA=findViewById(R.id.CalculateGPA);
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(edtNoCreate.getText().toString().length()>0) {
try {
DynamicEditTextHolder.removeAllViews();
} catch (Throwable e) {
e.printStackTrace();
}
length = Integer.parseInt(edtNoCreate.getText().toString());
for ( i=1;i<=length;i++){
course=new TextView(CgpaActivity.this);
course.setId(i);
course.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
course.setX(10);
// course.setX(ALIGN_BOUNDS);
// course.setRowOrderPreserved(false);
course.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
course.setText("Course"+(i));
DynamicEditTextHolder.addView(course,new GridLayout.LayoutParams());
marks_et = new EditText(CgpaActivity.this);
marks_et.setId(i);
marks_et.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
marks_et.setHint("marks ");
marks_et.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
DynamicEditTextHolder.addView(marks_et,new GridLayout.LayoutParams());
gpa=Double.parseDouble(marks_et.getText().toString());
sumgpa += gpa;
}
}
}
});
CalculateGPA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
{
cgpa = sumgpa / length;
cgpa_ET.setText(String.valueOf(cgpa));
}
}
});
}
}
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!
I am facing issue while subtracting my product, I am using three buttons to get the value of the selected one and then multiply these value for add more product or subtract . But when i click on subtract button it will minus the whole amount. So please help me in this. Below mention is my code. If you want some more info then please ask me.
public class ShowDetailActivity extends AppCompatActivity {
private TextView addToCardBtn;
private TextView titleTxt, feeTxt, descriptionTxt, numberOrderTxt;
private ImageView plusBtn, minusBtn, picFood, priceBtn, mediumPriceBtn, largePriceBtn;
private ProductsDomain object;
private int numberOrder = 1;
private ManagementCart managementCart;
private LinearLayout cheese_ll;
private LinearLayout scale_ll;
private int itemPrice;
private CheckBox cheeseBoxyes;
private int price;
private int checkvalue;
private int uncheckValue;
private boolean cheeseBoolean = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_detail);
managementCart = new ManagementCart(this);
initView();
getBundle();
//Button Code
price=object.getPrice();
priceBtn.setOnClickListener(this::onClick);
mediumPriceBtn.setOnClickListener(this::onClick);
largePriceBtn.setOnClickListener(this::onClick);
//check box code for extra cheese
}
private void onClick(View view) {
int id=view.getId();
switch (id){
case R.id.smallPriceBtn:
price=object.getPrice();
itemPrice=object.getPrice();
feeTxt.setText(Integer.toString(price*numberOrder));
break;
case R.id.mediumPriceBtn:
price = object.getMediumPrice();
feeTxt.setText(Integer.toString(price*numberOrder));
itemPrice=object.getMediumPrice();
break;
case R.id.largePriceBtn:
price = object.getLargePrice();
feeTxt.setText(Integer.toString(price*numberOrder));
itemPrice=object.getLargePrice();
break;
}
}
private void getBundle() {
object = (ProductsDomain) getIntent().getSerializableExtra("object");
if (object.getWithCheese() == 1)//get cheese
{
cheese_ll.setVisibility(View.VISIBLE);
scale_ll.setVisibility(View.GONE);
} else {
cheese_ll.setVisibility(View.GONE);
scale_ll.setVisibility(View.VISIBLE);
}
Glide.with(this).load("http://192.168.100.215/pizzaVill/Images/" + object.getImage()).into(picFood);
titleTxt.setText(object.getName());
descriptionTxt.setText(object.getDescription());
numberOrderTxt.setText(Integer.toString(numberOrder));
feeTxt.setText(Integer.toString(object.getPrice()));
plusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
numberOrder = numberOrder + 1;
numberOrderTxt.setText(Integer.toString(numberOrder));
feeTxt.setText(Integer.toString(numberOrder * price));
//Code if there is no size required
}
});
minusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (numberOrder > 1) {
numberOrder = numberOrder - 1;
}
numberOrderTxt.setText(Integer.toString(numberOrder));
feeTxt.setText(Integer.toString(price - itemPrice));
}
});
addToCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
object.setNumberInCard(numberOrder);
object.setFinalPrice(price);
managementCart.insertFood(object);
}
});
}
private void initView() {
addToCardBtn = findViewById(R.id.addToCardBtn);
titleTxt = findViewById(R.id.titleTxt);
feeTxt = findViewById(R.id.priceTxt);
descriptionTxt = findViewById(R.id.descriptionTxt);
numberOrderTxt = findViewById(R.id.numberOrderTxt);
plusBtn = findViewById(R.id.plusBtn);
minusBtn = findViewById(R.id.minusBtn);
picFood = findViewById(R.id.foodPic);
priceBtn = findViewById(R.id.smallPriceBtn);
mediumPriceBtn = findViewById(R.id.mediumPriceBtn);
largePriceBtn = findViewById(R.id.largePriceBtn);
cheese_ll = findViewById(R.id.cheese_ll);
scale_ll = findViewById(R.id.scale_ll);
cheeseBoxyes = findViewById(R.id.cheeseBoxyes);
}
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)));
}
}
});