I have one of these for each day of the week:
mondayRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mondayRadioButton.isChecked()){
deleteAppointmentsLayout.removeAllViews();
daySelected = 1;
for(Iterator<Appointment> i = appointments.iterator(); i.hasNext();){
Appointment item = i.next();
if(item.getDay() == 1){
checkBox = new CheckBox(DeleteAppointmentActivity.this);
System.out.println("fucken did work");
id = item.getId();
time = item.getTime();
duration = item.getDuration();
description = item.getDescription();
boxText = time + ", " + duration + ", " + description;
checkBox.setText(boxText);
checkBox.setTextSize(12);
checkBox.setId((int) id);
deleteAppointmentsLayout.addView(checkBox);
}
else {
System.out.println("fucken didnt work");
}
}
}
}
});
When an onclick for a button is activated I want to retrieve the information for each of the selected checkboxes for the currently selected day (checkboxes are generated programmatically). How can I check which ones are selected when the onclick for the Delete button is activated?
Create a member variable Array like
public class MyClass extends Activity
{
ArrayList<CheckBox> cbArray = new ArrayList<CheckBox>();
then when you create a checkbox add it to the ArrayList. Now when you click the delete Button use a for loop to iterate over the ArrayList and call isChecked() on each one.
Then delete or add that to a checked Array to do whatever you need with it
for (int i=0; i<cbArray.size(); i++)
{
if (cbArray.get(i).isChecked())
{
// do whatever here
Related
I am a beginner level programmer and I am again here to take everybody's help and solve my problem. Actually I don't have an error this time but I need to do something which I am not able to,
The thing is that I want to use a for loop 3 times and everytime I have a condition to check if my Quantity1 = 0 or not, again if my Quantity2 is = 0 or not and same for the third time. I can also repeat the code 3 times but I need to do this is because, I am uploading my data to a realtime database. And I am uploading my SelectedDate1 if Quantity1 != 0 and same for the three times, but to read them I have to know that how many Quantities and SelectedDates are uploaded and for that I have created a variable OrderQuantity. But the problem is if the user has selected the 1st date and the 3rd date and not the 2nd one as its quantity is 0, so when it is uploaded it shows OrderQuantity=2and the selectedDate1 comes under 1 but the 3rd date comes under 2nd node with name 3, but it should come with the name of variable+i, I hope you understand my question. And if not, please comment and I'll provide you an english video for what I want. Hoping your help as soon as possible.-
I think there is no use of main_activity.xml as it will make my question very big.
But here goes my MainActivity.java (without imports as it was very big)
public class MainActivity extends AppCompatActivity implements DatePickerFragment.applyDate, AdapterView.OnItemSelectedListener {
String CurrentDateString;
TextView mainDate;
Integer OrderQuantity = 3;
String itemOneDate;
String itemTwoDate;
String itemThreeDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button SelectDate1 = findViewById(R.id.SelectDateButton1);
Button SelectDate2 = findViewById(R.id.SelectDateButton2);
Button SelectDate3 = findViewById(R.id.SelectDateButton3);
SelectDate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(1, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate1;
}
});
SelectDate2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(2, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate2;
}
});
SelectDate3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(3, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate3;
}
});
ArrayAdapter<CharSequence> FoodAdapter = ArrayAdapter.createFromResource(this, R.array.FoodList, android.R.layout.simple_spinner_item);
FoodAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner SelectItem1 = findViewById(R.id.SelectItem1);
SelectItem1.setAdapter(FoodAdapter);
SelectItem1.setOnItemSelectedListener(this);
Spinner SelectItem2 = findViewById(R.id.SelectItem2);
SelectItem2.setAdapter(FoodAdapter);
SelectItem2.setOnItemSelectedListener(this);
Spinner SelectItem3 = findViewById(R.id.SelectItem3);
SelectItem3.setAdapter(FoodAdapter);
SelectItem3.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> QuantityAdapter = ArrayAdapter.createFromResource(this, R.array.Quantity, android.R.layout.simple_spinner_item);
QuantityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner Quantity1 = findViewById(R.id.SelectQuantity1);
Quantity1.setAdapter(QuantityAdapter);
Quantity1.setOnItemSelectedListener(this);
Spinner Quantity2 = findViewById(R.id.SelectQuantity2);
Quantity2.setAdapter(QuantityAdapter);
Quantity2.setOnItemSelectedListener(this);
Spinner Quantity3 = findViewById(R.id.SelectQuantity3);
Quantity3.setAdapter(QuantityAdapter);
Quantity3.setOnItemSelectedListener(this);
Button DoneButton = findViewById(R.id.DoneButton);
EditText PersonName = findViewById(R.id.PersonName);
EditText PersonPhone = findViewById(R.id.PersonPhone);
EditText PersonAddress = findViewById(R.id.PersonAddress);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference Name = database.getReference(PersonPhone.getText().toString() + "/Name");
Name.setValue(PersonName.getText().toString());
DatabaseReference Phone = database.getReference(PersonPhone.getText().toString() + "/Phone");
Phone.setValue(PersonPhone.getText().toString());
DatabaseReference Address = database.getReference(PersonPhone.getText().toString() + "/Address");
Address.setValue(PersonAddress.getText().toString());
//I need help here in these three if-else statements
if (Quantity1.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders" + "/1" + "/Date");
dateOne.setValue(itemOneDate);
}
if (Quantity2.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders" + "/2" + "/Date");
dateOne.setValue(itemTwoDate);
}
if (Quantity3.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders" + "/3" + "/Date");
dateOne.setValue(itemOneDate);
}
DatabaseReference OrderQuantities = database.getReference(PersonPhone.getText().toString() + "/OrderQuantity");
OrderQuantities.setValue(OrderQuantity);
}
});
}
public void setDate(int selectedYear, int selectedMonth, int selectedDay, int buttonNumber) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, selectedYear);
c.set(Calendar.MONTH, selectedMonth);
c.set(Calendar.DAY_OF_MONTH, selectedDay);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String CurrentDateString = format.format(c.getTime());
mainDate.setText(CurrentDateString);
if (buttonNumber == 1) {
itemOneDate = CurrentDateString;
} else if (buttonNumber == 2) {
itemTwoDate = CurrentDateString;
} else if (buttonNumber == 3) {
itemThreeDate = CurrentDateString;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Here is the image of the data saved on realtime database when 1st and 3rd date are selected.-
Also see that what I have selected on the virtual device.
And here is the link from where I learnt to make a datePickerFragment for selecting date.
Edit: go object-oriented
Edit: since my first two suggestions didn’t work for you, I am suggesting using some abstraction. Declare a class to hold a spinner and its related data, and iterate a list of such objects. Your list can hold a variable number of objects so there will be a variable number of spinners. Caveat: I don’t know Android UI programming, so may be missing a detail or two there. And I still have not compiled my code myself.
public class MySpinner {
private FirebaseDatabase database;
private Spinner quantity;
private String number;
private String itemDate;
public MySpinner(FirebaseDatabase database,
Spinner quantity, String number, String itemDate) {
this.database = database;
this.quantity = quantity;
this.number = number;
this.itemDate = itemDate;
}
/* #return true if there was a positive quantity to process, false otherwise */
public boolean processQuantity() {
if (quantity.getSelectedItem().toString().equals("0")) {
return false;
}
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString()
+ "/Orders" + number + "/Date");
dateOne.setValue(itemDate);
return true;
}
}
I have also object-orientedly fitted the class with a method to do the work for each spinner. Now with a list of objects of your class you may process each in turn in a loop like this:
for (MySpinner mySpinner : yourListOfMySpinners) {
if (! mySpinner.processQuantity()) { // quantity was 0
OrderQuantity -= 1;
}
}
I am leaving to yourself to fill objects into your list. There will probably also be some adjusting and tailoring that you will want to do.
Original answer follows.
Use an array or list
It’s not uncommon for beginners in programming to ask that question. It’s not quite the right question to ask. What you need is to iterate over your quantities in a loop. The solution to that is to put them into an array or list and iterate over that array or list. Code is not tested.
Spinner[] quantities = { Quantity1, Quantity2, Quantity3 };
for (int i = 0; i < quantities.length; i++) {
if (quantities[i].getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders/" + (i + 1) + "/Date");
dateOne.setValue(itemTwoDate);
}
}
While it would be possible to select a variable the way you describe, it’s neither the best, the easiest nor the nicest solution.
Or use a method
An alternative is to declare a method that does the job for each quantity and call it three times without using any loop. In your case the method may need to take quite many arguments, though, which is not ideal.
processSpinner(database, Quantity1, "/1", itemOneDate);
processSpinner(database, Quantity2, "/2", itemTwoDate);
processSpinner(database, Quantity3, "/3", itemThreeDate);
Your method may be declared like:
private void processSpinner(FirebaseDatabase database,
Spinner quantity, String number, String itemDate) {
if (quantity.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString()
+ "/Orders" + number + "/Date");
dateOne.setValue(itemDate);
}
}
Hello guys in bottom I code something which work perfectly but I am using array list in that, but I want Dynamic radio button if user select any button so for user it should display name and for me i get selected id my json response is like divid,divisionname I have to show divisionname to user in Radio button and if user select any radio based on that i want divid any thing if we pass both id and name in one radio button, on submit button i want Id
ArrayList<String> divId = null;
ArrayList<String> divName = null;
RadioGroup divRadioGrouop;
String divsionId=null;
if (divisionCheck) {
RadioButton rdbDiv;
divId = new ArrayList<>();
divName = new ArrayList<>();
divisionLogin.setVisibility(View.VISIBLE);
divRadioGrouop.removeAllViews();
for (int j = 0; j < jsonArrayDiv.length(); j++) {
JSONObject jsonDiv = jsonArrayDiv.getJSONObject(j);
divId.add(jsonDiv.getString("divid"));
divName.add(jsonDiv.getString("divisionname"));
rdbDiv = new RadioButton(this);
rdbDiv.setId(View.generateViewId());
rdbDiv.setText(jsonDiv.getString("divisionname"));
divRadioGrouop.addView(rdbDiv);
}
divOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int divid = divRadioGrouop.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(divid);
String divSionNameFind = (String) radioButton.getText();
int idPostionIndex = divName.indexOf(divSionNameFind);
divsionId = divId.get(idPostionIndex);
divName.clear();
divId.clear();
logINDataForDiv();
}
});
divCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something
}
});
}
You need to use tag in that case, first add divid in all your radio button like:
radioButton.setTag(divid);
on Submit, you can get back divid by this:
String divid=radioButton.getTag().toString();
Make sure you do setTag before getTag, otherwise getTag will return null and your app will crash.
This question already has answers here:
Android Spinner: Get the selected item change event
(17 answers)
Closed 5 years ago.
I create a table dynamically, and inside the table I create a spinner dynamically. When a user selects a string using the spinner, I want to know what was selected.
the GUI:
the dynamic created spinner:
TextView t7v = new TextView(this);
/**********ADD SPINNER*******/
ArrayList<String> spinnerArray = new ArrayList<String>();
if(tempBranch[i].equals("karmiel")) {
spinnerArray.add(" " + tempBranch[i] + " ");
spinnerArray.add("batyam");
spinnerArray.add("natbag");
}else if(tempBranch[i].equals("batyam")){
spinnerArray.add(" " + tempBranch[i] + " ");
spinnerArray.add("karmiel");
spinnerArray.add("natbag");
}else{
spinnerArray.add(" " + tempBranch[i] + " ");
spinnerArray.add("batyam");
spinnerArray.add("karmiel");
}
spinner = new Spinner(this);
spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
spinner.setAdapter(spinnerArrayAdapter);
tbrow.addView(spinner);
/*********END ADD SPINNER*****/
final Button rowButton2 = new Button(this);// create a new button
//Button OK
rowButton2.setText("OK");
rowButton2.setId(i);//set the number of count
// b.addView(rowButton);
tbrow.addView(rowButton2);
// save a reference to the button for later
myButton[i] = rowButton2;
myButton[i].setOnClickListener(btnClick2(rowButton2));//click the button
the Button when I want receive the value:
private View.OnClickListener btnClick2(final Button button) {//clock button that create dynamic
return new View.OnClickListener(){
public void onClick(View v){
//create array
idEmpl = id[v.getId()];
tmpBranch = spinner.getSelectedItem().toString();//NOT WORK TEMPORARY
String type = "changeTempBranch";
/* ManagerListInBackground managerListInBackground = new ManagerListInBackground(v.getContext());
managerListInBackground.execute(type,idEmpl,tmpBranch);//send the data to valid*/
}
};
}
Try this answer: https://stackoverflow.com/a/1714426/9217218
Then inside the onItemSelected method, add the you can get the string value like this:
String selectedItemTitle = mySpinner.getSelectedItem().toString();
So with help of IdleApps Inc and his link:enter link description here
I solved my problem, that is answer:
enter code here/* Value Spinner */
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
/* Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();*/
tmpBranch = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
tmpBranch = spinner.getSelectedItem().toString();
}
});
/* End of Value Spinner */
that code inside in the build dynamic table, so be careful, that not will work in another place (for me minimum)
thank you to everyone!
i have tried all the things but i cant get proper result,i also try
adapter.clearAll()
adapter.notifyDataSetChanged()
but i cant get result when i delete row from list view its deleted from its position but when i change value of another row than the delete process working perfectly but changed value not set.getting value from database perfectly.
Here is my code please help me and tell where i m doing wrong.
Thank you in advance
Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Identifier_fev = null;
String Default_Option = null;
String Quantity1 = null;
jffDatabase.open();
Cursor identifie = jffDatabase.getALL();
if (identifie.moveToPosition(position)) {
Identifier_fev = identifie.getString(identifie.getColumnIndexOrThrow("identifier"));
Default_Option = identifie.getString(identifie.getColumnIndexOrThrow("default_option"));
}
jffDatabase.delete(Identifier_fev, Default_Option);
identifier.remove(position);
title.remove(position);
defaultPrice.remove(position);
default_option.remove(position);
price.remove(position);
quantity.remove(position);
Cursor c1 = jffDatabase.getALL();
if (c1.moveToFirst()) {
do {
Quantity1 = c1.getString(c1.getColumnIndexOrThrow("quantity"));
update_quantity.add(Quantity1);
} while (c1.moveToNext());
}
for (int i = 0; i < update_quantity.size(); i++) {
Toast.makeText(ctx, "" + update_quantity, Toast.LENGTH_LONG).show();
Quantitylbl.setText(update_quantity.get(i).toString());
Toast.makeText(ctx, "set " + Quantitylbl.getText().toString(), Toast.LENGTH_LONG).show();
}
Quantity();
notifyDataSetChanged()
AddtoCartActivity.Cartcount.setText(String.valueOf(sum));
}
});
Good practice is use Interface
Create new Interface
public interface MyCustomObjectListener {
public void RefreshList();
//add parameter for delete if required ex-
//public void RefreshList(String Item_id);
}
then implement Activity by this Interface
YourActivityName extends Activity implements MyCustomObjectListener
And Implement Method
#Override
public void RefreshList() {
// Do your delete task and clear current List and get updated list task here
}
and from Base adapter onClick you can call method RefreshList like this
((YourActivityName)mContext).RefreshList();
you can delete and refresh list from #Override RefreshList
While debugging my app, I noticed that my RecyclerView display is inconsistent with the data provided, i.e.
If I set an alarm (TextView in RecyclerView has date set) then scroll my RecyclerView, the date shows up in the wrong positions e.g If I set the date on the 4th item, then the 3rd item also has the date set as well for some reason
I also noticed that at times, e.g. Only the 3rd and 5th -last items in the data set plays an animation while the 4th does not. I checked the logs, and it appears that onBindViewHolder() is not called for the 4th item, only 3rd and 5th. Am I doing something wrong here?
I have looked at the documentation, but am not sure how to patch accordingly. Can you help me?
My onBindViewHolder:
#Override
public void onBindViewHolder(final RecyclerVH recyclerVH, final int position) {
currentNote = data.get(position);
final String currentTitle = currentNote.getTitle();
final String currentContent = currentNote.getContent();
final int currentPosition = currentNote.getPosition();
String currentAlarmDate = currentNote.getAlarm();
Log.d("RecyclerView", "onBindVH called: " + currentTitle);
Log.d("RecyclerView", "Position at: " + currentPosition + " and Adapter Position at: " + recyclerVH.getAdapterPosition());
// final Info currentObject = data.get(position);
// Current Info object retrieved for current RecyclerView item - USED FOR DELETE
recyclerVH.listTitle.setText(currentTitle);
recyclerVH.listContent.setText(currentContent);
Log.d("RecyclerAdapter", "currentAlarmDate is: '" + currentAlarmDate + "'");
if (currentAlarmDate != null && !currentAlarmDate.equals(" ")) {
Log.d("RecyclerAdapter", "Current Alarm set for: " + currentAlarmDate);
recyclerVH.alarm.setText(currentAlarmDate);
}
recyclerVH.pencil.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("User Interface", "updateNoteInfo called!");
// Opens Dialog to update Note and Alarm
// TODO Open Activity instead
//final View updateButton;
// NEEDS TO BE DECLARED AT TOP, SO IT IS SEEN EVERYWHERE
updateDialog = new MaterialDialog.Builder(context)
.title(R.string.rewrite_note)
.customView(R.layout.note_update_screen, false)
.positiveText(R.string.update)
.negativeText(R.string.nevermind)
.forceStacking(false)
.cancelable(false)
.canceledOnTouchOutside(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
updatedTitle = updateTitle.getText().toString();
updatedContent = updateContent.getText().toString();
updateNote(updatedTitle, updatedContent, recyclerVH.getAdapterPosition());
}
})
.build();
//noinspection ConstantConditions
updateTitle = (EditText) updateDialog.getCustomView().findViewById(R.id.updateNoteTitle);
updateContent = (EditText) updateDialog.getCustomView().findViewById(R.id.updateNoteContent);
// Set the text for the title using current info
updateTitle.setText(currentTitle);
updateTitle.setSingleLine(false);
updateTitle.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
updateContent.setText(currentContent);
updateContent.setSingleLine(false);
updateContent.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
updateButton = updateDialog.getActionButton(DialogAction.POSITIVE);
// TODO Use do-while loop for onTextChanged?
// TODO Use Thread?
updateDialog.show();
// updateButton.setEnabled(false);
}
});
runEnterAnimation(recyclerVH.itemView, position);
}
since RecyclerView reuses or recycles the views, you must always add an else condition to make sure that it works properly. So, add an else block along with your if block.
Remove the setOnClickListener() from onBindViewHolder and set the setOnClickListener() inside your ViewHolder RecyclerVH. To get the position of the clicked item or row call the method getAdapterPosition(). Example:
public class ReservationViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
// each data item is just a string in this case
CardView cardView;
public ReservationViewHolder(View v) {
super(v);
cardView = (CardView) v.findViewById(R.id.cv);
cardView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
// do what you want...
}
}