简体   繁体   中英

string comparison in android / java

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);
                        }
                    }
                });
            }
        });
    }
}

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"))

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();
}

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) {

} 

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().

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM