1

I really can't see where I'm going wrong with this. Any help would be much appreciated.

I have a JSONArray

JSONArray jsonArray = new JSONArray(responseString);

Where responseString is ["prob", "2"]

I get the 1st String

String maybeProb = jsonArray.getString(0);

and when I show it using a Toast all is ok and the toast popup just says prob

Toast.makeText(getBaseContext(),maybeProb ,Toast.LENGTH_LONG).show();

But when I use an if (maybeProb == "prob") it doesnt return true

Why not??? What am I doing wrong???

Some more details for you:

responseString which forms the original JSONArray comes from an HttpPost to my server

InputStream is = null;

HttpResponse response = httpclient.execute(httppost);

HttpEntity entity = response.getEntity();

is = entity.getContent();

//Convert response to string
responseString = convertStreamToString(is);

public String convertStreamToString(InputStream inputStream) {

    StringBuilder sb = null;
    String result = null;

    try
    {           
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
      sb = new StringBuilder();
      String line = null;

      while ((line = reader.readLine()) != null)
      {
        sb.append(line + "\n");
      }

      inputStream.close();
      result = sb.toString();

    }
      catch(Exception e)
    {
      Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
    }

    // return the string
    return result;
}

The PHP on my server which makes the response is

$message = array("prob", "2");

$response = json_encode($message);

print($response);

Many thanks to anyone that can help me

2 Answers 2

4

To compare objects in java use .equals() method instead of "==" operator

Replace the following code

 if(maybeProb  == "prob") {
 }

with this one.

 if(maybeProb.equals("prob")) {
 }
Sign up to request clarification or add additional context in comments.

1 Comment

And the problem is no more. Thank you very much, I'm still very new to Java.
2

The equals operator (==) returns true only if both objects are the same, not if their value is the same. Therefore, when you compare the object maybeProb with the object "prob" it returns false

If you want to do the comparison, you have to use maybeprob.equals("prob").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.