Get text from multiples radiobuttons - java

I want to get the text from multiples checked radiobuttons, and retrieve it in one edittext... but dont know how is the best way to do it. What is better? saving results in string or a list?
Anyway the result should appear in one single editext with the space beetwen each text. For example... Dog, Cat, Mouse.
if (radioButton.isChecked()){
String obs2 = radioButton.getText().toString();
texto.setText(obs2);
}
if (radioButton3.isChecked()){
String obs2 = radioButton3.getText().toString();
texto.setText(obs2);
}
if (radioButton4.isChecked()){
String obs2 = radioButton4.getText().toString();
texto.setText(obs2);
}
if (radioButton5.isChecked()){
String obs2 = radioButton5.getText().toString();
texto.setText(obs2);
}
if (radioButton6.isChecked()){
String obs2 = radioButton6.getText().toString();
texto.setText(obs2);
}
if (radioButton7.isChecked()){
String obs2 = radioButton7.getText().toString();
texto.setText(obs2);
}
if (radioButton8.isChecked()){
String obs2 = radioButton8.getText().toString();
texto.setText(obs2);
}
editText1 = here should get the text of each radio button checked
new try:
if (radioButton.isChecked()){
obs2 = checkNullAndAppend(obs2, (String) radioButton.getText());
} else if (radioButton3.isChecked()){
obs2 = checkNullAndAppend(obs2, (String) radioButton3.getText());
} else if (radioButton4.isChecked()){
obs2 = checkNullAndAppend(obs2, (String) radioButton4.getText());
} else {
texto.setText(obs2);
}

If you want event-driven code then using a list may be easier to manage depending on how many buttons you have and how you do it. But in the case of your exact example, a string is more than enough. As suggested in comments you can simply append the text texto.setText(texto.getText() + "," + obs2);.
If you want to avoid issues with null values or reduce duplicate code, then there are many different ways you can do this, but one is to create a simple method:
public static String checkNullAndAppend(String existing, String toAppend){
//Check null
if (existing == null || existing.equals(""))
return toAppend;
//Otherwise add a comma and space
else
return existing + ", " + toAppend;
}
Then you can simply call the method inside your if statements:
if (radioButton.isChecked()){
texto = checkNullAndAppend(texto, radioButton3.getText());
}
if (radioButton3.isChecked()){
texto = checkNullAndAppend(texto, radioButton3.getText());
}
...
editText1 = texto;
...

Related

How to get StrikeThrough on a String ? Not a TextView, EditText or a View. But like String a = "my text" and then pass it to SQLite as a String

I have this method which works fine for an EditText or a view.
public SpannableString strikeThrough(String txt){
SpannableString spannableString = new SpannableString(txt);
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
spannableString.setSpan(strikethroughSpan,0, txt.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
EditText etChecklistItem = checklistView.findViewById(R.id.et_checklist_item);
etChecklistItem.setText(strikeThrough(etChecklistItem.getText().toString()));
But my problem is after that, the text doesn't have StrikeThrough.
StringBuilder stringBuilderItem = new StringBuilder();
for( String list : itemslist) {
stringBuilderItem.append(list);
stringBuilderItem.append("\n");
}
String text = stringBuilderItem.toString();
strikeThrough(text);
dbHelper.insertChecklist(text);
When I get the data in RecyclerView, it would not be in Strikethrough.
Instead of storing a strike-through string inside the array, Create a class having two members a String and a boolean, and make the boolean true for the string you want to strike through.
class Message {
private String str;
private boolean strike;
public Message (String str, boolean strike) {
this.str = str;
this.strike = strike;
}
// getters and setters
}
and make string strike through when you're showing it on the screen
ArrayList<Message> arr = new ArrayList<>();
for (Message msg: arr) {
if (arr.getStrike()) {
// make string strikethrough
} else {
// keep as it is
}
}
To strike through a string in TextView
Method 1
textView.setText("I want like that")
textView.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
Method 2: If you want to strike through only a part of the text then use
String str = "I want like that";
SpannableStringBuilder builder = new SpannableStringBuilder(str);
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
builder.setSpan(
strikethroughSpan,
0, // Start
4, // End (exclusive)
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE // Text changes will not reflect in the strike changing
);
textView.setText(spanBuilder);
Method 3: If you want to strike through text in strings.xml
<string name="yourName"><strike>I want like that</strike></string>
references: [1]
Just Checkout this Code
First you need to initialise you edit text or text view
textView = findViewById(R.id.textView);
textView.setText("Hello World");
textView.setPaintFlags(textView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
I hope this will help you, if any problem just comment down

Issue with variable in a if/else loop in Java

import java.util.HashMap;
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
String location = "memes more memes Virginia";
String test = createStateMap(location);
System.out.println(test);
}
public static String createStateMap(String loc) {
loc = loc.toUpperCase();
String secondLast; // Retrieves potential second to last value
String lastWord; // Retrieves last value
String state = "failed";
String trimmed = loc.trim(); // Take off spaces at the end of String
String o = trimmed.substring(0, trimmed.lastIndexOf(" ")); // Remove last Word in String EX. "SOUTH CAROLINA" = "SOUTH"
String otrim = o.trim(); // Take off spaces at the end of String
if (trimmed.contains("/")){
secondLast = otrim.substring(otrim.lastIndexOf("/")+1);
lastWord = trimmed.substring(trimmed.lastIndexOf("/")+1);
} else {
secondLast = otrim.substring(otrim.lastIndexOf(" ")+1);
lastWord = trimmed.substring(trimmed.lastIndexOf(" ")+1);
}
HashMap<String,String> names = new HashMap<String,String>();
names.put("ALABAMA", "AL");
names.put("ALASKA", "AK");
names.put("ARIZONA", "AZ");
names.put("ARKANSAS", "AR");
names.put("CALIFORNIA", "CA");
names.put("COLORADO", "CO");
names.put("CONNECTICUT", "CT");
names.put("DELAWARE", "DE");
names.put("FLORIDA", "FL");
names.put("GEORGIA", "GA");
names.put("HAWAII", "HI");
names.put("IDAHO", "ID");
names.put("ILLINOIS", "IL");
names.put("INDIANA", "IN");
names.put("IOWA", "IA");
names.put("KANSAS", "KS");
names.put("KENTUCKY", "KY");
names.put("LOUISIANA", "LA");
names.put("MAINE", "ME");
names.put("MARYLAND", "MD");
names.put("MASSACHUSETTS", "MA");
names.put("MICHIGAN", "MI");
names.put("MINNESOTA", "MN");
names.put("MISSISSIPPI", "MS");
names.put("MISSOURI", "MO");
names.put("MONTANA", "MT");
names.put("NEBRASKA", "NE");
names.put("NEVADA", "NV");
names.put("NEWHAMPSHIRE", "NH");
names.put("JERSEY", "NJ");
names.put("MEXICO", "NM");
names.put("YORK", "NY");
names.put("CAROLINA", "NC");
names.put("DAKOTA", "ND");
names.put("OHIO", "OH");
names.put("OKLAHOMA", "OK");
names.put("OREGON", "OR");
names.put("PENNSYLVANIA", "PA");
names.put("RHODEISLAND ", "RI");
names.put("CAROLINA", "SC");
names.put("DAKOTA", "SD");
names.put("TENNESSEE", "TN");
names.put("TEXAS", "TX");
names.put("UTAH", "UT");
names.put("VERMONT", "VT");
names.put("VIRGINIA", "VA");
names.put("WASHINGTON", "WA");
names.put("VIRGINIA", "WV");
names.put("WISCONSIN", "WI");
names.put("WYOMING", "WY");
System.out.println(secondLast);
if (names.containsValue(lastWord)){
state = lastWord;
}
if (names.containsKey(lastWord)){
if (names.get(lastWord).equals("CAROLINA")){ // Differentiate NC and SC
if (secondLast.equals("North")){
state = "NC";
} else { state = "SC"; }
} if (names.get(lastWord).equals("DAKOTA")) { // Differentiate ND and SD
if (secondLast.equals("North")){
state = "ND";
} else { state = "SD"; }
} if (names.get(lastWord).equals("VIRGINIA")) { // Differentiate WV and VA
if (secondLast.equals("West")){
state = "WV";
} else { state = "VA"; }
} else { state = names.get(lastWord); }
}
return state;} }
I am currently having issues with my code that assigns a state's abbreviations to a variable depending on the String passed into the parameter of the createStateMap method. When the lastWord String is either Virginia, Dakota, or Carolina they will always be assigned WV, ND, or NC- even if the secondLast is not North or West.
Any help would be much appreciated, I have been stuck on this one for a while.
names.get(lastWord) already returns "SC" for key "CAROLINA", so your
names.get(lastWord).equals("CAROLINA")
condition will always return false.
It also makes no sense to put the same key twice in the Map, since the second value will overwrite the first value having the same key.
Why not put the full name of the state as key?
names.put("SOUTH CAROLINA", "SC");
names.put("NORTH CAROLINA", "NC");
In that case
state = names.get(fullStateName);
will always work and you can eliminate all of those conditions, as long as fullStateName contains the full name of the state (either a single word or two words).
If you don't know whether you should search for the last word or the last two words in the Map, you can search for the last two words, and if not found, search for the last word :
state = names.get(secondLast + " " + lastWord);
if (state == null) {
state = names.get(lastWord);
}
So, just as an fyi,
names.put("VIRGINIA", "VA");
names.put("WASHINGTON", "WA");
names.put("VIRGINIA", "WV");
You're working with a HashMap here, so you can only have 1 value per key. This means the only value you'll get when you extract VIRGINIA is WV (the last one to be entered). Just put in the full state name, as Eran suggested. I mean, you're already putting in NEWHAMPSHIRE, which is technically two words, so I don't see why you don't want to do the same thing for the Carolinas, Dakotas, and Virginias.

java recursion: object is replaced rather than adding a new one

I am trying to add an object inside an object using recursion. My object contains an arrayList and I am trying to add my objects to this arrayList. But instead of adding a new object, my objects are being replaced.
My code which is doing this: This is where the logic of adding an object is being done. But it is being replaced instead.
private ArrayList<SubChapters> recursiveSubChapters(ReportingTree tree, LinkedHashMap<String, HashMap<String, String>> linkedHashMap, Boolean isSubTree){
SubChapters subChapters = new Subchapters();
ArrayList<SubChapters> alchildUnits = new ArrayList<SubChapters>();
final String chapterId = linkedHashMap.get(tree.getUnitID()).get("unit_num");
final String chapterName= linkedHashMap.get(tree.getUnitID()).get("unit_name");
if (!isSubTree) {
subChapters.set(chapterId);
subChapters.setTreeName(chapterName);
}
final ArrayList<ReportingTree> branches = tree.getBranches();
if (branches != null) {
subChapters.hasSubUnits(true);
for (ReportingTree subTree: branches) {
subChapters.setSubChapters(recursiveSubChapters(subTree, linkedHashMap, false));
//This is where the logic of adding an object is being done. But it is being replaced instead.
}
alchildUnits.add(subChapters);
}
return alchildUnits;
}
My guess is that I am messing somewhere in the loop here but I am not able to figure out where I am messing up. Thanks in advance for any suggestions or help.
My subChapters class:
public String subChapterID;
public String subChapterName;
public boolean isSubTree= false;
public ArrayList<SubChapters> subChapters;
and getters and setters.
I have coded the same solution to return a string and see the order on a jsp. It works just fine. I am not able to apply the same to my issue here.
private String recursive(ReportingTree tree, LinkedHashMap<String, HashMap<String, String>> listUnitInfo, boolean isTop) {
final String unitID = tree.getUnitID();
final HashMap<String, String> unit = listUnitInfo.get(unitID);
String output = "";
if (!isTop) {
output += "<li>" + unit.get("unit_num") + "/" + unit.get("unit_name") + "";
}
final ArrayList<ReportingTree> branches = tree.getBranches();
if (branches != null) {
if (isTop) {
output += "<li>" + unit.get("unit_num") + "/" + unit.get("unit_name") + "";
}
output += "<ul>\n";
for (ReportingTree subTree : branches) {
output += recursive(subTree, listUnitInfo, false);
}
output += "</ul>";
} else {
if (isTop) {
output += "<li>No units match your criteria.";
}
}
output += "</li>\n";
return output;
}
What you're doing is subChapters.setSubChapters, what I think you're trying to do is
subChapters.addSubChapters.
The reason why it works with the strings is because you're using += to add
the new string to the old string. Doing setSubChapters would be the same as using = with the strings.
addSubChapters would be a method that should add something to an ArrayList variable inside your subChapters class.

Need help in creating a java(fx) program which replaces a string by user with another set of strings

I have created this app, to use for sort of like coding and decoding. I have created the first text area in which the user enters text. The program gets the text. So far, so good.
Now i need to replace each alphabet by another set of alphabets or numbers or both. I tried using:
#FXML
String text;
#FXML
TextArea userText;
#FXML
Label codedTextLabel;
#FXML
private void getTextAction(ActionEvent textEvent) {
String codedText;
text = userText.getText();
//The first if
if (text.contains("a") {
codedText = codedTextLabel.getText() + "50"; //50 means a, 60 means b and so on
codedTextLabel.setText(codedText);
} else {
System.out.println("Searching for more text...");
}
//The second if
if (text.contains("b") {
codedText = codedTextLabel.getText() + "50"; //50 means a, 60 means b and so on
codedTextLabel.setText(codedText);
} else {
System.out.println("Searching for more text...");
... so on ...
I have created multiple ifs for the same text area, so that each if gets executed, even if the other is executed. But it generates errors and doesn't work. Any idea how to create such an application to do this very thing?
I would do it like that:
private static final Map<Character, String> mapping = new HashMap <>();
static {
map.put('a', "50");
map.put('b', "60");
//etc.
}
then in your method:
String text = userText.getText();
StringBuilder sb = new StringBuilder();
for (char c : text.toCharArray()) {
sb.append(mapping.get(c)); //should add null check here
}
String encodedText = sb.toString();

Android - get content of certain array-field to a String

I am trying to get the content of a single array item.
In my code, I want the value of String suitId to have the content of suitIdArray[getSuitId];, but it doesn't get the content.
Could you please help me to see what is wrong. Here is my code...
Object item1 = spinner1.getSelectedItem();
int getDragId = spinner1.getSelectedItemPosition();
String suitId;
if(!item1.equals("Choose size")) {
suitId = suitIdArray[getSuitId];
}
else {
pSuit = null;
}
Is is not working because you have a variable getdragid but you're using getsuitid in the array? ie, should it be the following...
Object item1 = spinner1.getSelectedItem();
int getdragtid = spinner1.getSelectedItemPosition();
if(!item1.equals("Choose size"))
{
suitid = suitidarray[getdragtid]; // I changed this line
}
else if(item1.equals("Choose size"))
{
psuit = null;
}
Otherwise, I'm not really sure what you're trying to do?

Categories