繁体   English   中英

android / java中的字符串比较

[英]string comparison in android / java

我从API获得了JSON响应,该API已转换为字符串,并尝试将它的真值或假值进行比较,在日志猫上,我可以看到结果:

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

我正在尝试将其适合如下的if语句

我已经尝试了大多数比较方法(== 、. equals()、. compareTo()),但没有得到任何结果

谁能让我知道正确的处理方式,因为我还是Java和Android的新手。 我见过很多类似的帖子,但无法弄清楚。

非常感谢您的时间和协助。

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

您应该解析JSON字符串并比较消息。

if (message.equals("success"))

如果您不喜欢解析,则可以尝试以下一种方法(错误的做法):

if(response.contains("success"))

在您的代码中尝试一下。

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(); 不起作用。 请使用string()方法代替toString()

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

private void doSomething(String response) {

} 

问题与OkHttp有关

这是因为当您调用以下命令时:

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

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

字符串结果将为空,因为您已经在Log中调用了response.body() 当您调用它时,它将被清空。

因此,您需要先将其保存到结果中,然后才能从日志中调用它。 像这样:

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

文档这里:

响应主体只能使用一次。

此类可用于流式传输很大的响应。 例如,可以使用此类读取大于分配给当前进程的整个内存的响应。 它甚至可以流式传输比当前设备上的总存储更大的响应,这是视频流应用程序的常见要求。

因为此类不在内存中缓冲完整的响应,所以应用程序可能不会重新读取响应的字节。 使用此快照可以将整个响应读取到具有bytes()或string()的内存中。 或使用source(),byteStream()或charStream()流式传输响应。

我用volley代替okhttp并进行了排序,下面是代码

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

如果有人能让我知道okhttp出了什么问题,那对将来的参考将很有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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