checkbox text not getting displayed on textview - android

I am new to android technology, i wanted the checkbox's text to be displayed using textview.
I think the problem is in TextUtils.join function
For e.g
If my checklist is a, b, c, d.
I want to display the textview like
//Text view string
you have selected a, b, c, d.
Code Snippet :
public class Menu3 extends AppCompatActivity {
CheckBox checkBox;
CheckBox checkBox2;
CheckBox checkBox3;
CheckBox checkBox4;
TextView tView;
ArrayList<String> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu3);
checkBox = (CheckBox)findViewById(R.id.checkBox);
checkBox2 = (CheckBox)findViewById(R.id.checkBox2);
checkBox3 = (CheckBox)findViewById(R.id.checkBox3);
checkBox4 = (CheckBox)findViewById(R.id.checkBox4);
tView = (TextView)findViewById(R.id.textView3);
checkBox.setOnClickListener(ocl);
checkBox2.setOnClickListener(ocl);
checkBox3.setOnClickListener(ocl);
checkBox4.setOnClickListener(ocl);
String all = TextUtils.join(",", arrayList);
tView.setText(all);
}
View.OnClickListener ocl = new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean checked = ((CheckBox) v).isChecked();
if(checked) {
String text = null;
switch (v.getId()) {
case R.id.checkBox:
text = checkBox.getText().toString();
Toast.makeText(Menu3.this, text + " checked.", Toast.LENGTH_SHORT).show();
arrayList.add(text);
break;
case R.id.checkBox2:
text = checkBox2.getText().toString();
Toast.makeText(Menu3.this, text + " checked.", Toast.LENGTH_SHORT).show();
arrayList.add(text);
break;
case R.id.checkBox3:
text = checkBox3.getText().toString();
Toast.makeText(Menu3.this, text + " checked.", Toast.LENGTH_SHORT).show();
arrayList.add(text);
break;
case R.id.checkBox4:
text = checkBox4.getText().toString();
Toast.makeText(Menu3.this, text + " checked.", Toast.LENGTH_SHORT).show();
arrayList.add(text);
break;
}
}
}
};
}

The problem is that you are calling setText right away in onCreate, and it isn't called again when the checkboxes are changed. Personally, I'd set up a method that gets called when a checkbox is changed to handle all of this
Something like this
private void updateTextView(String text) {
Toast.makeText(Menu3.this, text + " checked.", Toast.LENGTH_SHORT).show();
arrayList.add(text);
String all = TextUtils.join(",", arrayList);
tView.setText(all);
}
Then call it from all of your OnClickListener for the checkboxes
case R.id.checkBox:
updateTextView(checkBox.getText().toString());
...

You are setting the text first, after then, you are not setting anything. You must set text every time you add/remove string to your arraylist.

Related

Checked the Checkboxes that is already checked

I have one EditText (edModelColor). when user click on edModelColor(EditText) then the custom dialog will be called.Custom dialog consist of RecylerView and searchview and one custom row for each item. Custom row contains ImageView(icon), TextView (colorNames) and checkbox for selection. When user click on any checkbox I passed the colorName and its position in adapter into method checkAndRemove. this method will add or remove the color name according to its adapter position and the colorNames will added into edModelColor(EditText). its working fine but the problem is that once the user click on edModelColor(EditText) again, I want to checked those checkboxes which are already checked inside CustomDialogbox.I have seen some articles online but I could not understand what they meant.
bodyColorDialog:
private void bodyColorDialog() {
TextView txtClose;
TextView tvCancel;
Button btnOk;
bodyColorDialog.setContentView(R.layout.ed_body_color_dialog);
bodyColorDialog.setCancelable(false);
txtClose = bodyColorDialog.findViewById(R.id.txtModelClose);
tvCancel = bodyColorDialog.findViewById(R.id.tvCancel);
btnOk = bodyColorDialog.findViewById(R.id.btnOk);
edBodyColorSearchView = bodyColorDialog.findViewById(R.id.edBodyColorSearchViewColor);
edBodyColorRecylerView = bodyColorDialog.findViewById(R.id.edBodyColorRecylerView);
edBodyColorRecylerView.setLayoutManager(new LinearLayoutManager(getContext()));
bodyColorArrayList.clear();
setUpBodyColorArrayList();
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectionCMap = new HashMap<>();
selectionCMap = edBodyColorAdapter.selectionColorsMap;
for(String value : selectionCMap.values()){
/* tv.setText(tv.getText() + "\n" + value);*/
edBodyColor.append(value + ",");
}
bodyColorDialog.dismiss();
}
});
txtClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bodyColorDialog.dismiss();
}
});
tvCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bodyColorDialog.dismiss();
}
});
bodyColorDialog.show();
}
private void setUpBodyColorArrayList() {
bodyColorArrayList.clear();
String bodyColorName[] = getResources().getStringArray(R.array.body_color_array);
int bodyColorIcons[] = {R.drawable.red, R.drawable.black, R.drawable.violet, R.drawable.white,
R.drawable.orange, R.drawable.blue, R.drawable.green, R.drawable.yello};
for(int i =0; i < bodyColorIcons.length; i++)
{
bodyColorArrayList.add(new edModelBodyColor(bodyColorName[i], bodyColorIcons[i]));
}
edBodyColorAdapter = new edBodyColorAdapter(getContext(), bodyColorArrayList);
edBodyColorRecylerView.setAdapter(edBodyColorAdapter);
edBodyColorSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String queryString) {
edBodyColorAdapter.getFilter().filter(queryString);
return false;
}
#Override
public boolean onQueryTextChange(String queryString) {
edBodyColorAdapter.getFilter().filter(queryString);
return false;
}
});
}
edBodyColorAdapter.java
holder.checkBoxColor.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
int position = holder.getAdapterPosition();
clickedColorNamePosition = edBodyColorArrayList.indexOf(filteredArrayList.get(position));
String name = edBodyColorArrayList.get(clickedColorNamePosition).getBodyColorName();
Toast.makeText(context, "name = " + name, Toast.LENGTH_SHORT).show();
//this mthod will check if selected checkbox value is already present or not.
// It present then remove ( means user unchecked box) and if value is not there means user has selected checkbox
checkAndRemove(position,name);
}
});
checkAndRemove:
private void checkAndRemove(int position, String name) {
if(selectionColorsMap.containsKey(position)){
selectionColorsMap.remove(position);
Toast.makeText(context, "removed", Toast.LENGTH_SHORT).show();
}else {
selectionColorsMap.put(position, name);
Toast.makeText(context, "added", Toast.LENGTH_SHORT).show();
}
}
preview:
Conculusion: I want to check these checkboxes values when user click again on edBodyColor dialog..
I as can see, you are initializing the ArrayList of colors every time you are showing the dialog, that's why, you start always at initial state.
Instead, you should initialized the ArrayList inside onCreate() and reuse it every time to maintain the previous state.

How to validate which checkbox is checked?

I am new to android ,Here I have 7 check boxes in my application and I have customized it as in the image .Each checkbox is represents a day of the week .
What I want to do is ,If a user clicked on a checkbox the text of the clicked checkbox should appear on the above TextView (by default if there is any checkbox is not clicked Textview text should be as "Never").
Here the Textview text should be in a ordered way ,I mean If I select all the check boxes randomly but the TextView text should be in a ordered way like Sun,Mon,.....Sat.
I know how to validate a checkbox is checked or not ,but When it comes to the above situation I don't know how it should be .
Can anyone help me to get this .
private TreeMap<Integer, String> mAlarmDays = new TreeMap<>();
public void onClick(View v) {
switch (v.getId()) {
case R.id.mSun:
if (mRepeat.getText().toString().contains("Sun")) {
mAlarmDays.remove(0);
Toast.makeText(getApplicationContext(),"Sun is clicked",Toast.LENGTH_LONG).show();
} else
mAlarmDays.put(0, "Sun");
break;
case R.id.mMon:
if (mRepeat.getText().toString().contains("Mon")) {
mAlarmDays.remove(1);
} else
mAlarmDays.put(1, "Mon");
break;
case R.id.mTue:
if (mRepeat.getText().toString().contains("Tue")) {
mAlarmDays.remove(2);
} else
mAlarmDays.put(2, "Tue");
break;
case R.id.mWed:
if (mRepeat.getText().toString().contains("Wed")) {
mAlarmDays.remove(3);
} else
mAlarmDays.put(3, "Wed");
break;
case R.id.mThu:
if (mRepeat.getText().toString().contains("Thu")) {
mAlarmDays.remove(4);
} else
mAlarmDays.put(4, "Thu");
break;
case R.id.mFri:
if (mRepeat.getText().toString().contains("Fri")) {
mAlarmDays.remove(5);
} else
mAlarmDays.put(5, "Fri");
break;
case R.id.mSat:
if (mRepeat.getText().toString().contains("Sat")) {
mAlarmDays.remove(6);
} else
mAlarmDays.put(6, "Sat");
break;
}
StringBuilder repeatDays = new StringBuilder();
if (mAlarmDays.size() == 0) {
repeatDays = new StringBuilder("Never");
} else {
for (String day:mAlarmDays.values()) {
repeatDays.append(day).append(" ");
}
}
mRepeat.setText(repeatDays.toString());
}
I suggest to create one checkbox listener for all checkboxes which will iterate over them and build string for textview
Something like this:
CheckBox sunday = ...;
CheckBox monday = ...;
//......
CheckBox saturday = ...;
TextView label = ...;
CompoundButton.OnCheckedChangeListener changeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
List<String> days = new ArrayList<>();
if (sunday.isChecked()) {
days.add("Sun");
}
if (monday.isChecked()) {
days.add("Mon");
}
//....
if (saturday.isChecked()) {
days.add("Sat");
}
if (days.size() != 0) {
label.setText(TextUtils.join(", ", days));
} else {
label.setText("Never");
}
}
};
sunday.setOnCheckedChangeListener(changeListener);
monday.setOnCheckedChangeListener(changeListener);
//......
saturday.setOnCheckedChangeListener(changeListener);
It really depends how you have the text set... but you can do something like.
if (checkBox.isChecked()) {
System.out.println("checkBox clicked");
}
try this for every checkbox.
CheckBox checkBox = (CheckBox)v;
if(checkBox.isChecked()){
Log.i("Checkbox", "Checkbox selected.");
}else{
Log.i("Checkbox", "Checkbox Not selected.");
}

Issues passing Edit text into an If statement

I have a quiz app that should contains the following:
1- radio groups/buttons
2- checkbox
3- editText
all should calculate a score. I manage to get the radio groups, checkbox to work and calculate the score. however having problems with the editText
I am trying to compare the value of what's in name2 variable but I am unable to do so. I've implemented the .equals syntax but it's not working accordingly.
Any suggestions/solutions are grateful.
public class Quiz extends AppCompatActivity {
int score = 0;
String name;
String name2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
}
public void onRadioButtonCliked(View view) {
Boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.yes_radio_buttonG1B3:
if (checked)
score++;
break;
case R.id.yes_radio_buttonG2B2:
if (checked)
score++;
break;
case R.id.yes_radio_buttonG3B2:
score++;
if (checked)
break;
case R.id.yes_radio_buttonG4B1:
if (checked)
score++;
break;
case R.id.yes_radio_buttonG5B2:
if (checked)
score++;
break;
case R.id.yes_radio_buttonG6B3:
if (checked)
score++;
break;
}
}
public void onCheckBoxCliked(View view) {
Boolean checked = ((CheckBox) view).isChecked();
CheckBox cB1 = (CheckBox) findViewById(R.id.checkBox1);
CheckBox cB2 = (CheckBox) findViewById((R.id.checkBox2));
CheckBox cB3 = (CheckBox) findViewById(R.id.checkBox3);
if (cB1.isChecked() && cB2.isChecked() && !cB3.isChecked()) {
score++;
}
}
public void EditText(View view) {
EditText text = (EditText) findViewById(R.id.editText1);
name2 = text.getText().toString();
if (name2.equals("8")) {
score++;
}
}
public void submitOrder(View view) {
EditText username = (EditText) findViewById(R.id.editText);
name = username.getText().toString();
Toast.makeText(this, "Thank you " + name, Toast.LENGTH_SHORT).show();
Toast.makeText(this, "You have got 8/" + score, Toast.LENGTH_SHORT).show();
}
}
Since it's a string variable, you must use "" to indicate it's a string.
Whole number are only applicable for int variable type.
if(name2.equals("8")){
score++;
}
Try replacing the 8 with "8" as you are supposed to be comparing a String, not an integer.
As already mentioned in a comment and in the two other answers, you can't compare a String to a number.
Instead of checking a String, convert that string to an integer(assuming it is a valid int) and compare the ints instead.
First, convert:
int value;
try{
value = Integer.parseInt(name2);//throws an exception if it isn't a valid integer or if name == null
}catch(Exception e){
return;//not valid, don't continue
}
Then compare:
if(value == 8){
score++;
}

Custom listview using button OnClickListener

i have created a custom listview with an ImageView, two TextViews and a Button
now i am facing issue when i try to set onClicklistner to that button
i want different method to be done for every button
here is my code for customlistview class
i have used temporary onclicklistner for that button which shows the toast "Bought"
what i want to do is that after clicking the button i have to return the price of the food.
class CustomListView extends ArrayAdapter {
public CustomListView(Context context, String[] resource) {
super(context,R.layout.custom_view , resource);
}
Toast toast= null;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater MyInflater = LayoutInflater.from(getContext());
View CustomView = MyInflater.inflate(R.layout.custom_view, parent, false);
String SingleItem= (String) getItem(position);
final TextView text =(TextView)CustomView.findViewById(R.id.Itemname);
final ImageView Image= (ImageView)CustomView.findViewById(R.id.icon);
final TextView Pricetag= (TextView)CustomView.findViewById(R.id.PriceTextView);
text.setText(SingleItem);
switch (SingleItem)
{
case "Chicken":
Image.setImageResource(R.drawable.desert1);
Pricetag.setText("Rs 300");
break;
case "soap":
Image.setImageResource(R.drawable.desert2);
Pricetag.setText("Rs 300");
break;
case "Fish":
Image.setImageResource(R.drawable.fish);
Pricetag.setText("Rs 100");
break;
default:
Image.setImageResource(R.drawable.myimage);
Pricetag.setText("Rs 0.00");
break;
}
final Button Buybutton= (Button)CustomView.findViewById(R.id.BuyButton);
toast = Toast.makeText(getContext(), "", Toast.LENGTH_LONG);
Buybutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toast.setText("Bought");
toast.show();
}
});
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toast.setText(text.getText().toString());
toast.show();
}
});
return CustomView;
}
}
For the record, there should be a better way to do this, using food-id or other approach to prevent this, but based on your request, here we go:
1- in getView() when you get a reference on the button i.e:
final Button Buybutton= (Button)CustomView.findViewById(R.id.BuyButton);
do a one more step:
Buybutton.setTag(10);
10 here could be any other number, and you need to find a way to determine which number to use for each button, also it could be a string , ex value of SingleItem
Buybutton.setTag(SingleItem);
2- at onClick() you need to find out what the value assign to the view (button) and based on this value call the proper method:
#Override
public void onClick(View v) {
if (v.getTag().toString().equals("xxxxx")){
doSomething();
}else if (v.getTag().toString().equals("yyyy")){
doAnotherThing();
}else if (v.getTag().toString().equals("zzzzz")){
doSomething12();
}
//and so on...
}
this approach used String as value in setTag() and getTag()
if you use integers, just replace the condition as belwo:
if (Integer.parseInt(v.getTag().toString()) == 10)
EDIT:
If i understand well, then you need to:
Buybutton.setTag(SingleItem);
and onClick():
#Override
public void onClick(View v) {
showPriceTag(v.getTag().toString());
}
add method showPriceTag():
public void showPriceTag(String type){
switch (type)
{
case "Chicken":
//set the price tag data ...
break;
case "soap":
//set the price tag data ...
break;
case "Fish":
//set the price tag data ...
break;
default:
//set the default price tag data ...
break;
}
}

OnClickListener in a while loop on custom objects

I'm setting up a CardView layout (with the libary) but I've got a problem.
I can setup a onClickListener (which works) in this way:
mCardView = (CardUI) getView().findViewById(R.id.cardsview);
mCardView.setSwipeable(true);
MyCard b = new MyCard("Hi", "Hi", 15);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(v.toString());
Toast.makeText(getActivity(),"werkt",Toast.LENGTH_LONG).show();
}
});
mCardView.addCard(b);
But when I try to do it in a loop I can't seem to get the ID of the cards.
My cards do have a unique ID (just a int as ID).
I'm adding them like this:
int id = 0;
while(!c.isAfterLast()){
String description = "";
System.out.println("Opmerking: " + c.getString(3));
if(!c.getString(3).equals("")){
description = "Opmerkingen: " + c.getString(3);
}
if(recreate){
MyCard a = new MyCard(c.getString(2)+" "+c.getString(1), description, id);
cards.add(a);
mCardView.addCard(a);
a.setOnClickListener(new OnClickListener());
}
c.moveToNext();
id++;
}
And the onClickListener is this:
private class OnClickListener implements View.OnClickListener {
#Override
public void onClick(View view) {
switch (view.getId()){
case 1:
Toast.makeText(getActivity(), "werkt", Toast.LENGTH_LONG).show();
break;
default: Toast.makeText(getActivity(), "werkt niet", Toast.LENGTH_LONG).show(); break;
}
}
}
But everytime when I click one which has a onClickListener of the while loop I get 'werkt niet' which is the default item of the switch.
The card ID is a int in the MyCard object.
If anyone could help me it would be greatly appreciated.
Edit: The MyCard object is a object which needs this libary: http://nadavfima.com/cardsui-view-library/
That is because your view.getId() is never equals 1. Try adding
System.out.println("view.getId() -->> "+view.getId());
inside the default case..
You will get your problem then and there...

Categories

Resources