android - json key value pairs to sqlite [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I am completely stuck on this and need help.
I need to get the value if another value is equal to something.
Lets say my array is:
"people":[
{"name": "David", "age": "30"},
{"name": "Bob", "age": "20"},
{"name": "Bill", "age": "30"}
]
I need to return the age if the name is lets say Bob. I have attempted to do it this way but to no avail.
String People = jsonPart.getString("people");
JSONArray arr = new JSONArray(People);
for (int h = 0; h < arr.length(); h++) {
JSONObject jsonPart = arr.getJSONObject(h);
String name = jsonPart.getString("name");
if (name == "Bob") {
String age = jsonPart.getString("age");
break;
}
}

Your problem is that you cannot do String comparisons in Java using the == operator. You must use String#equals so replace this line:
if (name == "Bob") {
with
if(name.equals("Bob")) {
See this link for more info:
https://www.baeldung.com/java-compare-strings
and
https://docs.oracle.com/javase/tutorial/java/data/comparestrings.html

You can also do it like this:
If("Bob".equals(name))
to avoid NullPointerException if the name is null.

Related

Java If Else Text Based on Other Text [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I am trying to have a text-box populate with X if another text-box has a certain value, else Y. However, it's populating with X or Y seemingly randomly. d4 is my button, d4result is where it populates the result, d4txt1 is where I want to see a 1 or 0, depending.
d4.setOnClickListener {
if (d4result.text.toString() == "1") {
d4txt1.text = "1"
} else {
d4txt1.text = "0"
}
val rand = Random().nextInt(4) + 1
d4result.text = rand.toString()
}
So if d4result is populated with 1, I want d4txt1 to populate with 1, otherwise it should be zero. But when I try it, I get 1 or 0 and I can't notice a pattern as to when/why.
Use equals instead of ==. == operator will return true only if two object reference it is comparing represent exactly same object otherwise "==" will return false.
d4.setOnClickListener {
if (d4result.text.toString().equalsIgnoreCase("1")) {
d4txt1.text = "1"
} else {
d4txt1.text = "0"
}
val rand = Random().nextInt(4) + 1
d4result.text = rand.toString()
}
Java is tricky about that. The == operator compares the two object pointers, not their values. It's fine for integers and floats but almost never useful for strings.
Instead use the .equals() method or the .equalsIgnoreCase() method:
if (d4result.text.toString().equalsIgnoreCase("1")) { ...

Splitting string by multiple delimiters [duplicate]

This question already has answers here:
how to get data between quotes in java?
(6 answers)
Closed 6 years ago.
I have a string of names. I am looking to split it based on names between double quotes. I used the following code to split the names.
String []splitterString=str.split("\"");
for (String s : splitterString) {
System.out.println(s);
}
I get the output as:
[
Hossain, Ziaul
,
Sathiaseelan, Arjuna
,
Secchi, Raffaello
,
Fairhurst, Gorry
]
I need to store just the names from these. I am not sure how to do that.
This is the string:
["Hossain, Ziaul","Sathiaseelan, Arjuna","Secchi, Raffaello","Fairhurst, Gorry"]
Thanks for the help!!!
I think following solution may help you out :-
String str = "[\"Hossain, Ziaul\",\"Sathiaseelan, Arjuna\",\"Secchi, Raffaello\",\"Fairhurst, Gorry\"]";
String [] str1 = str.split("\\[\"|\",\"|\"\\]");
for (int iCount = 0; iCount < str1.length; iCount++)
{
System.out.println(str1[iCount]);
}

'If' Statement Failing Check Involving String Array [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to create a program in Java which allows the user to pick from a list of coffees contained in a String array and continues on, but it fails the check and prints out the else statement.
Here is the relevant code:
Scanner scan = new Scanner(System.in);
String[] flavors = {"Black", "French Vanilla", "Hazelnut", "Mango", "Cherokee", "anarcho-syndicalism", "Otis" };
...
System.out.println("Today we have " + Arrays.toString(flavors));
System.out.println("Please enter the name of the coffee you would like exactly as shown above: ");
String coffee = scan.next();
...
for (int i = 0; i < flavors.length; i++) {
if (coffee == flavors[i]) {
String selection = flavors[i];
Though not shown here, I believe everything's properly formatted later on in the program. Any ideas?
In general, when comparing objects for equality in java, use .equals(). Use == for comparing primitives. In java, Strings are objects.
change:
if (coffee == flavors[i]) {
to:
if (coffee.equals(flavors[i])) {
When comparing objects with ==, they will only be equal if they are in fact the same instance.

How to split a string to get related data JAVA

I have string from which I am getting data in array but I am not getting way to get so that I get related data in array like my string is,
[{"Class Room": ["Windows", "Windows1"], "Staffroom": ["Windows", "Windows1"]}], "
here i have two dropdowns ,
"Class Room" having two values in dropdown Windows and Windows1
another drodown,
"Staffroom" having two values in dropdown Windows and Windows1
How would i get dropdown related value in array i can use split operation but cant getting logic
Above given string is in list, my code is ,
String[] data = list.toString().split(",");
But it split in array then I would not have related data
I want it to split in way so that I would get relative dropdown data in array,
"Class Room": ["Windows", "Windows1"], value in aray index 0
"Staffroom": ["Windows", "Windows1"]}] value in array index 1
String is not fix it is generating on run time number of dropdown and values of dropdown vary time to time but pattern of string same as mentioned above
This depends on the UI framework that you are working. If you are using Swings then you have to use ActionListener to display related data. For example
private String s1[] = { "None", "J2EE", "DataBase", "Scripting Language",
"Computer Networks" };
private String s2[][] = { { "None" }, { "Core Java", "Advanced Java" },
{ "Oracle", "SQL", "SyBase" }, { "Java scripts", "c#", "CGI" },
{ "MCSE", "CCNA", "CCNP", "CCIE" } };
...
skill = new JComboBox(s1);
specificSkill = new JComboBox(s2[0]);
...
skill.addActionListener(new ComboAction());
...
specificSkill.setSelectedIndex(0);
You can use this code which can solve your problem as it is tested and verified.
String temp = "[{"Class Room": ["Windows", "Windows1"], "Staffroom": ["Windows", "Windows1"]}],";
String parts[] = temp.split(",");
ArrayList<String> listItems = new ArrayList<String>();
for (int i = 0; i < parts.length; i =i+2) {
listItems.add(parts[i]+","+parts[i+1]);
}
Or you can use regex to break the string at a particular occurence of a character.
I hope it helps.

if statement issue with mysql getstring [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have an issue with the if/else function in my Java code (Android / Eclipse).
When I'm in debug mode, checkGender is equal to "M", but goes directly to "else" instruction and considers that 'checkGender' is not equal to "M". I don't understand why? For information, searcher.getString("Gender") takes information from MySQL.
String checkGender = "";
checkGender = searcher.getString("Gender");
if(checkGender == "M")
{
bGenderM.setChecked(true);
}
else
{
bGenderF.setChecked(true);
}
Debug info :
checkGender = "M" (id=8300460...)
value[0] = M
If I replace "searcher.getString("Gender");" by a simple "M", it works.
Thanks for your help.
Tom
Actually best would be to do it "Yoda-style"
if("M".equals(checkGender)) {
//code for male
} else {
//code for female
}
That way you avoid potential NullPointerException for the case that checkGender == null
Use equals() method instead of == for String comparison.
if(checkGender.equals("M")) {
bGenderM.setChecked(true);
} else {
bGenderF.setChecked(true);
}
OR, use equalsIgnoreCase() method and it better...
if(checkGender.equalsIgnoreCase("M")) {
bGenderM.setChecked(true);
} else {
bGenderF.setChecked(true);
}

Categories