This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Comparing two identical strings with == returns false
I am having real hard time with solving this code. This might look silly but I am not able to figure out what is happening. I am parsing a JSONArray(No big deal!) I am traversing the array with a for loop. I want to break the loop when the user input and the value matches. Here is my code
String regi = null;
JSONObject studentObject = null;
try {
JSONArray returned = test.getInternetData();
int i;
for (i = 0; i < returned.length(); i++) {
studentObject = returned.getJSONObject(i);
regi = studentObject.getString("REGISTRATION_NO");
if (regi == reg) {
name = studentObject.getString("STUDENT_NAME");
break;
}
}
course = studentObject.getString("COURSE_CODE");
Log.d("Details", name + course + regi + i);//Out put: nullGraduate081018394:name - null
//course: Graduate (same for all), regi: last registration number,
//i: giving totalnumber of objects
As per my knowledge the loop should stop when it finds a match. The COURSE_CODE will be corresponding to the student. Am I missing something?
Please note: The function getInternetData() is returning the whole JSON Array. The loop is completely traversing every object.
Strings cannot be compared with == in Java. You have to use string1.equals(string2).
Use regi.equals(reg) or regi.contentEquals(reg) instead of == and you will be fine :-)
use regi.contentEquals(reg) or !regi.contentEquals(reg) for comparison
you should use regi.contentEquals(reg)
try using this
JSONArray returned = test.getInternetData();
int i;
for (i = 0; i < returned.length(); i++) {
// added the below line
studentObject = new JsonObject();
studentObject = returned.getJSONObject(i);
regi = studentObject.getString("REGISTRATION_NO");
if (regi.equals(reg)) {
name = studentObject.getString("STUDENT_NAME");
break;
}
}
instead of just
JSONArray returned = test.getInternetData();
int i;
for (i = 0; i < returned.length(); i++) {
studentObject = returned.getJSONObject(i);
regi = studentObject.getString("REGISTRATION_NO");
if (regi == reg) {
name = studentObject.getString("STUDENT_NAME");
break;
}
}
Related
I have a function that 'crafts' products using two String parameters.
This is working fine when I put in hard coded strings like 'Wheel' & 'Car'.
But it makes my application crash if I try to put in the exact same strings but then provided by an intent.
I already tried to give in variable into the intent instead of a hard coded string. That did not work either.
Here is some part of the code. EDIT: Error log now included
productLeft = getIntent().getStringExtra("PRODUCT LEFT");
productRight = getIntent().getStringExtra("PRODUCT RIGHT");
public void craft(String product1, String product2) {
String[][] Products = factory.getProductList();
int i = 0;
while (finalProduct == "") {
int j;
for(j = 0; j < 3; j++){
if (product1 == Products[i][0] || product2 == Products[i][0]) {
if (product1 == Products[i][1] || product2 == Products[i][1]){
finalProduct = Products[i][2];
}
}
i++;
}
}
}
Problem is with the array index obviously. The array has only four elements and you are fetching index 4, probably in for loop with i variable. But then again I also do not see the role of j in that loop, can't tell without other parts of code.
how am I going to move the value of a char array to the same char array? Here's a code:
Assuming ctr_r1=1 ,
for(int ctr_x = (ctr_r1 + 2) ; ctr_x < letters.length - 2 ; ctr_x++)
{
letters[ctr_x] = letters[ctr_x];
}
sb.append(letters);
char[] lettersr1 = sb.toString().toCharArray();
sb1.append(lettersr1);
append the "letters", then convert it to string, then convert it to char array then make it as "lettersr1" value.
what im trying to accomplish is given the word EUCHARIST, i need to take the word HARIST out and place it on another array and call it region 1 (Porter2 stemming algorithm).
The code "ctr_X = (ctr_r1 + 2)" starts with H until T. The problem is I cannot pass the value directly that's why i'm trying to update the existing char array then append it.
I tried doing this:
char[] lettersr1 = null;
for(int ctr_x = (ctr_r1 + 2) ; ctr_x < letters.length - 2 ; ctr_x++)
{
lettersr1[ctr_x] = letters[ctr_x];
}
sb.append(lettersr1);
but my app crashes when i do that. Any help please. Thanks!
I don't understand what you're trying to do, but I can comment on your code:
letters[ctr_x] = letters[ctr_x];
This is a noop: it sets an array element value to the value it already has.
char[] lettersr1 = null;
for(int ctr_x = (ctr_r1 + 2) ; ctr_x < letters.length - 2 ; ctr_x++) {
lettersr1[ctr_x] = letters[ctr_x];
This obviously causes a NullPointerException, since you're trying to access an array which is null. You must initialize the array before being able to modify it:
char[] lettersr1 = new char[someLength];
Additional note: you should choose better names for your variables. The names should tell what the variable represents, and they should respect the Java naming conventions (no underscores in variable names, camelCase). ctr_x, ctr_r1 and lettersr1 don't mean anything.
EDIT:
I'm still not sure what you want to do, and why you don't simply use substring(), but here's how to transform EUCHARIST to HARIST:
char[] eucharist = "EUCHARIST".toCharArray();
char[] harist = new char[6];
System.arraycopy(eucharist, 3, harist, 0, 6);
String haristAsString = new String(harist);
System.out.println(haristAsString);
// or
char[] harist2 = new char[6];
for (int i = 0; i < 6; i++) {
harist2[i] = eucharist[i + 3];
}
String harist2AsString = new String(harist2);
System.out.println(harist2AsString);
// or
String harist3AsString = "EUCHARIST".substring(3);
char[] harist3 = harist3AsString.toCharArray();
System.out.println(harist3AsString);
May be so:
String str = "EUCHARIST";
str = str.substring(3);
and after toCharArray() or smth another
I have a long JSON string representing a string[] array being returned from a WCF service. The array elements are simply strings, they are not objects. This is an example of the return data
["1|ArrayElement1","2|ArrayElement2","3|ArrayElement3"..."n|ArrayElementn"]
I don't mind the index being included in the string, but I need to parse the strings into an ArrayList in Android so that I can adapt it to a ListView.
Since these technically aren't JSONObjects, how can I iterate over them and extract the string from each array element?
this is a valid JSON array of strings, you can parse it normally like this
JSONArray jsonStrings = json.getJSONArray("items");
String strings[] = new String[jsonStrings.length()];
for(int i=0;i<strings.length;i++) {
strings[i] = jsonStrings.getString(i);
}
Maybe this post can help you out:
JSON Array iteration in Android/Java
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i = 0; i < settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
JSONArray names= json.names();
JSONArray values = json.toJSONArray(names);
for(int i = 0 ; i < values.length(); i++){
if(names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if(names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if(names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if(names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if(names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if(names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Just to clarify, as I understand it you are receiving a JSON array of strings which are strings of valid JSON prefixed with the array index and a pipe character?
First, I would suggest contacting the creator of this abomination and lecturing them on violating standards. If they won't listen, talk to their bosses. This kind of thing is unacceptable in my opinion and needs to stop.
Second, I'd suggest doing something like this:
string[] element_strings = JSON.deserialize(WCF_string_result);
object[] elements = new object[element_strings.length];
for(int x = 0; x < elements.length; x++)
{
int pipeIndex = element_strings.indexOf("|");
elements[x] = JSON.deserialize(element_strings[x].substr(pipeIndex + 1));
}
Of course this assumes you have some kind of method for deserializing strings of JSON objects. If you don't I'd recommend using the built in library available in Android:
http://developer.android.com/reference/org/json/package-summary.html
If you want to extract specific value from it using Java8 stream on JSONArray. Then this code will help.
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.json.JSONArray;
public class JsonArrayTest {
public static void main(String[] args) {
System.out.println("Output - "+ getValue("[{\"id\":\"11\",\"username\":\"ABC\"},{\"id\":\"12\",\"username\":\"ABC\"}]\""));
System.out.println("Output - "+ getValue("[{\"id\":\"13\",\"username\":\"XYZ\"}]\""));
}
private static String getValue(String input) {
JSONArray jsonArray = new JSONArray(input);
return IntStream
.range(0, jsonArray.length()).mapToObj(obj -> jsonArray.getJSONObject(obj))
.filter(filterObj -> filterObj.getString("id") != null && "12".equals(filterObj.getString("id")))
.map(finalObj -> finalObj.getString("username")).collect(Collectors.joining(""));
}
}
Note: This is just an example how can you extract a specific value from JSONArry using stream APIs. You can change the filter condition or drop it according to your requirement.
i have an array from a json feed i know that in the jArray there is one league but i need to work out the count of that array incase a second is added to the feed at a later date. at the moment log cat isn't logging out "teamFeedStructure" does anyone know what I'm doing wrong or know how to correctly turn the length of an array into a string that i can use in an intent?
heres the code
JSONObject obj = new JSONObject(json);
JSONObject objData = obj.getJSONObject("data");
JSONArray jArray = objData.getJSONArray("structure");
//String leagues = jArray.toString();
//Log.v("myapp", "structure" + leagues);
for (int i=0; i < jArray.length(); i++) {
JSONObject oneObject = jArray.getJSONObject(i);
leaguecountArray = oneObject.getJSONArray("league_id");
for (int l=0; l < leaguecountArray.length(); l++) {
if (leaguecountArray.length() == 1) {
teamFeedStructure = "One";
}
if (leaguecountArray.length() == 2) {
teamFeedStructure = "Two";
}
Log.v("myapp", teamFeedStructure);
}
}
Why do you need to iterate here:
for (int l=0; l < leaguecountArray.length(); l++)
{
if (leaguecountArray.length() == 1){
teamFeedStructure = "One";
}
if (leaguecountArray.length() == 2){
teamFeedStructure = "Two";
}
Log.v("myapp", teamFeedStructure);
}
Nevermind how many passes you do the result will still be the same.
Also you can use not English words, but String holding the number you need. Do like that:
teamFeedStructure = String.valueOf(leaguecountArray.length());
Then the value will become "2" for example. In your other activity you can parse it again to integer like that: int number = Integer.parseInt(teamFeedStructure);
Add the following line
teamFeedStructure = "greater two";
before
if (leaguecountArray.length() == 1){
If you get greater two message, means your array length more than two.
Thanks for your help everyone i discovered that i had gone a step too far into the feed which is why i was not getting anything in Logcat. now it's counting fine.
I'm working on code that takes two arrays with strings (the strings are just sentences) and allocates them to classes which are held in another array (The Sentence class array shown below in the code).
So here's my problem. When popList() is called, the for loop runs through twice and works fine, putting the first index of addStrings and addTranslation into the first class in the array. However, when the loop indexes up and runs temp.sentence = addStrings[1] again, it OVERRIDES the first class's .sentence also. Then when temp.translations = addTranslations[1] runs again it OVERRIDES the first class's .translation.
So by the end of the loop, all of the arrays are filled with the same thing: the last index of addStrings and addTranslation. Every time it loops it overwrites all the indices before it with the index it's supposed to be putting in.
Anyone know what the problem is here? Thanks!
public class Sentence {
public String sentence;
public String translation;
Sentence() {
sentence = " ";
translation = " ";
}
}
private void popStrings() {
addStrings[0] = "我是你的朋友。"; addTranslations[0] = "I am your friend.";
addStrings[1] = "你可以帮助我吗?"; addTranslations[1] = "Could you help me?";
addStrings[2] = "我不想吃啊!"; addTranslations[2] = "I don't want to eat!";
}
//Fill Sentence array with string and translation arrays
private void popList() {
int i = 0;
Sentence temp = new Sentence();
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
}
You need to create new Sentence() inside the loop:
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
Sentence temp = new Sentence();
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
Otherwise you set sentence and translation continuously in the same object.