0

I have got a JSON response from an API that I have converted to a string and trying to compare it for true or false value, On the log cat I can see the result:

{
  "message": "success",
  "status": "Auth_Successful",
  "response": "Authentication successful"
}

I am trying fit it into an if statement like below

I have tried most of the comparison methods(==, .equals(), .compareTo()) but not getting any result

Can anyone let me know what is the correct way to approach it as I am still new to Java and Android. I have seen a lot of similar posts but unable to figure out.

Thank you very much for your time and assistance in this matter.

package com.example.shiben.fabapp;
public class MainActivity extends AppCompatActivity {

    private Request request;
    private static final String Tag = MainActivity.class.getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button LoginButton = (Button) findViewById(R.id.loginButton);
        EditText userName = (EditText) findViewById(R.id.userName);
        EditText userPassword = (EditText) findViewById(R.id.userPassword);
        final TextView displayTest = (TextView)    findViewById(R.id.displayTest);

        LoginButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                OkHttpClient client = new OkHttpClient();

                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                RequestBody body = RequestBody.create(mediaType, "username=xxxxxxxxx&password=xxxxxxxxx");

                Request request = new Request.Builder()
                .url("http://9.xxx.xxx.xxx/test/xxxxx_api.aspx")
                .post(body)
                .addHeader("cache-control", "no-cache")
                .addHeader("content-type", "application/json")
                .build();
                //execute the request
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.i(Tag, e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.i(Tag, response.body().string());

                        String result = response.body().toString();
                        //if (result==("{\"message\":\"success\",\"status\":\"Auth_Successful\",\"response\":\"Authentication successful\"}")){
                        if (result.compareTo("{\"message\":\"success\",\"status\":\"Auth_Successful\",\"response\":\"Authentication successful\"}")==0) {
                        //if (result.equals("{\"message\":\"success\",\"status\":\"Auth_Successful\",\"response\":\"Authentication successful\"}")) {
                            TastyToast.makeText(MainActivity.this, "String Comparison Success", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
                        }
                    }
                });
            }
        });
    }
}
Henry
  • 42,982
  • 7
  • 68
  • 84
shiben
  • 23
  • 3
  • 11
  • 1
    you are not comparing to the exact string that you are receiving from the server. could be an extra space, line return, ... Your input is apparently json, you should parse it as such, and get the result from there instead of comparing the strings. – njzk2 Sep 18 '17 at 02:35

5 Answers5

0

You should parse the JSON string and compare the message.

if (message.equals("success"))

If you don't like to parse, you may try this one (Bad practice):

if(response.contains("success"))
Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59
0

Try this in your code .

String result = response.body().toString();
if(TextUtils.isEmpty(result)){
        Toast.makeText(this, "result is null", Toast.LENGTH_SHORT).show();
        return;
}
try {
        JSONObject jsonObject = new JSONObject(result);
        String message = jsonObject.optString("message");
        String status = jsonObject.optString("status");
        String response = jsonObject.optString("response");
        if (TextUtils.equals("success", message)) {
            TastyToast.makeText(MainActivity.this, "String Comparison Success", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
    }
} catch (JSONException e) {
        e.printStackTrace();
}
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
  • thank you for the Suggestion Using the above code i get the below log com.google.android.finsky.wear.bl.a(3): onConnectionFailed: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null} Does this relate to the API call i am trying to make ? Any suggestions is appreciated Thanks in advance – shiben Sep 18 '17 at 09:44
  • You can look at [this link](https://stackoverflow.com/questions/21280794/error-connectionresultstatuscode-internal-error-resolution-null) . And try it .@shiben – KeLiuyue Sep 18 '17 at 09:48
0

String result = response.body().toString(); doesn't work. Please use string() method instead of toString()

@Override
public void onResponse(Response response) throws IOException {
  if (response.isSuccessful()) {
    doSomething(response.body().string());
  }
}

private void doSomething(String response) {

} 
kimkevin
  • 2,202
  • 1
  • 26
  • 48
0

The problem is related with OkHttp

This is because when you called the following:

Log.i(Tag, response.body().string());

String result = response.body().toString();

String result will be empty because you've already called response.body() in Log. When you called it, it will be emptied.

So, you need to save it to the result before calling it from the log. Something like this:

String result = response.body().toString();
Log.i(Tag, result);

Here from the documentation:

The response body can be consumed only once.

This class may be used to stream very large responses. For example, it is possible to use this class to read a response that is larger than the entire memory allocated to the current process. It can even stream a response larger than the total storage on the current device, which is a common requirement for video streaming applications.

Because this class does not buffer the full response in memory, the application may not re-read the bytes of the response. Use this one shot to read the entire response into memory with bytes() or string(). Or stream the response with either source(), byteStream(), or charStream().

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
  • I have commented the use of log.i and instead saved the result like : String result = response.body().toString(); but still don't get any response. The toast does not initiate anyway Is there any other way to handle this response ? Any suggestions will be great help – shiben Sep 18 '17 at 09:20
  • Is there any result when using log? – ישו אוהב אותך Sep 18 '17 at 09:21
  • I/com.example.shiben.fabapp.MainActivity: okhttp3.internal.http.RealResponseBody@c6e010b – shiben Sep 18 '17 at 09:58
  • What is the result if you try using `Log.i(Tag, result);`? – ישו אוהב אותך Sep 18 '17 at 10:00
  • I don't see any log using Log.i(Tag, result); The only relevant information on log cat is : I/com.example.shiben.fabapp.MainActivity: okhttp3.internal.http.RealResponseBody@c6e010b However i do see a log if i use : Log.i(Tag, response.body().string()); even after saving the response like : String result = response.body().toString(); – shiben Sep 18 '17 at 10:10
0

I used volley instead of okhttp and got it sorted , Below is the code

public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getName();

private Button btnSendRequest;


private RequestQueue mRequestQueue;

//creating a string request
private StringRequest stringRequest;
private String url = "http://9.xxx.xxx.xxx/test/xxxxxxx.aspx";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnSendRequest = (Button) findViewById(R.id.loginBtn);

    btnSendRequest.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //on click of the button send request and print the response

            //initializing request queue and string request in sendRequestAndPrintResponse
            sendRequestAndPrintResponse();
        }
    });
}

private void sendRequestAndPrintResponse() {
    mRequestQueue = Volley.newRequestQueue(this);
    stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i(TAG, "Success" + response.toString());
            String result = response.toString();
            TextView displayText = (TextView) findViewById(R.id.displayText);
            displayText.setText(result);

            if (result.equalsIgnoreCase("{\"message\":\"success\",\"status\":\"Auth_Successful\",\"response\":\"Authentication successful\"}")){
                Toast.makeText(getApplicationContext(), "comparison successful", Toast.LENGTH_LONG).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.i(TAG, error.toString());
        }
    }){
        @Override
        protected Map<String, String> getParams()
        {
            Map<String, String>  params = new HashMap<String, String>();
            params.put("username", "someone@example.com");
            params.put("password", "myPassword");
            return params;
        }
    };
    mRequestQueue.add(stringRequest);
  }
}

If anyone could let me know what went wrong with okhttp, it would be very helpful for future reference.

shiben
  • 23
  • 3
  • 11