【问题标题】:Android string.equals() doesn't match conditionAndroid string.equals() 不匹配条件
【发布时间】:2016-03-28 08:23:37
【问题描述】:

我一直在 Android 上使用 Volley,似乎我无法真正让这个特定部分正常工作

这是我的 json

{
  "code": 1,
  "status": ​200,
  "data": "bla... bla..."
}

这是 Activity.class

try
{
    JSONObject json_response = new JSONObject(response);
    String status = json_response.getString("status");

    if (status.equals("200"))
    {
        do something
    }
    else
    {
        Toast.makeText(getApplicationContext(), status, Toast.LENGTH_LONG).show();
    }
}

它总是跳过该条件,因为它不匹配,并且 toast 打印值 200 作为状态返回值且该值为 200 的证明

我试过

int status = json_response.getInt("status");

if (status == 200)

返回“JSONException:java.lang.String 类型的值无法转换为 JSONObject”,有什么见解吗?

编辑:

这里是完整的 LoginActivity.java

package my.sanik.loginandregistration.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import my.sanik.loginandregistration.R;
import my.sanik.loginandregistration.app.AppConfig;
import my.sanik.loginandregistration.app.AppController;
import my.sanik.loginandregistration.helper.SessionManager;

public class LoginActivity extends Activity
{
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn())
        {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty())
                {
                    // login user
                    checkLogin(email, password);
                }
                else
                {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
                Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    private void checkLogin(final String email, final String password)
    {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response)
            {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try
                {
                    JSONObject json_response = new JSONObject(response);
                    String status = json_response.getString("status");

                    if (status.equals("200"))
                    {
                        session.setLogin(true);

                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                    else
                    {
                        // Error in login. Get the error message
                        Toast.makeText(getApplicationContext(), "Wrong username or password", Toast.LENGTH_LONG).show();
                    }
                }
                catch (JSONException e)
                {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener()
        {

            @Override
            public void onErrorResponse(VolleyError error)
            {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams()
            {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog()
    {
        if (!pDialog.isShowing()) pDialog.show();
    }

    private void hideDialog()
    {
        if (pDialog.isShowing()) pDialog.dismiss();
    }
}

【问题讨论】:

  • 可能先尝试修剪字符串
  • 试试String.valueOf(status).equals("200")。匹配吗?
  • 不确定,但您可以修剪字符串或检查 200.0
  • 先尝试将响应打印到日志中,看看响应中是否有多余的字符。
  • 您的 JSON sn-p 显示 status 是一个数字而不是字符串。那你为什么叫getString而不是getInt(或者getLong)呢?比较也更容易......

标签: java android android-volley


【解决方案1】:

首先尝试打印您的response,检查您的回复是什么或一些额外的东西是否存在。

   try{
  Log.d(TAG, "Json response :" + response);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

然后和你的值比较。

【讨论】:

    【解决方案2】:
    {
      "code": 1,
      "status": ​200,     // Need this 
      "data": "bla... bla..."
    }
    

    您的status 不是String 格式所以,

    调用这个

     int getStatus = Integer.parseInt(json_response.getString("status"));
    

    然后

     if (getStatus==200)
    {
        // Your code
    }
    

    注意:

    1. 您可以直接使用getInt,而不是getString

    【讨论】:

    • 试过 int getStatus = Integer.parseInt(json_response.getString("status")) 和 int status = json_response.getInt("status"),我得到了这个错误 toast "JSONException: Value of type java.lang.String 无法转换为 JSONObject"
    • @NikSaifulAnuar 面临同样的问题?
    • @NikSaifulAnuar - 你能把整个更新的代码放进去吗?
    • @KevalPatel 抱歉花了这么长时间,这里是gist.github.com/sanik90/5476cbff81f0e67233a1
    【解决方案3】:

    使用该类获取json字符串 ServiceHandler.java

    package com.example;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import android.util.Log;
    
    public class ServiceHandler {
    
    static String response = null;
    public final static int GET = 1;
    
    public ServiceHandler() {
    
    }
    
    public String makeServiceCall(String url, int method) {
        return this.makeMyServiceCall(url, method);
    }
    
    public String makeMyServiceCall(String myurl, int method) {
        InputStream inputStream = null;
        HttpURLConnection urlConnection = null;
        try {
            /* forming th java.net.URL object */
            URL url = new URL(myurl);
            urlConnection = (HttpURLConnection) url.openConnection();
    
            /* optional request header */
            urlConnection.setRequestProperty("Content-Type", "application/json");
    
            /* optional request header */
            urlConnection.setRequestProperty("Accept", "application/json");
    
            /* for Get request */
            urlConnection.setRequestMethod("GET");
            int statusCode = urlConnection.getResponseCode();
    
            /* 200 represents HTTP OK */
            if (statusCode == 200) {
                inputStream = new BufferedInputStream(urlConnection.getInputStream());
                response = convertInputStreamToString(inputStream);
    
            }
        } catch (Exception e) {
            Log.d("tag", e.getLocalizedMessage());
        }
        return response;
    
    }
    
    private String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null) {
            result += line;
        }
    
        /* Close Stream */
        if (null != inputStream) {
            inputStream.close();
        }
        return result;
    }
    }
    

    在 MainActivty.java 中

    package com.example;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    import android.app.Activity;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    
    String jsonStr = "";
    JSONObject jo;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new GetDatas().execute();
    }
    
    class GetDatas extends AsyncTask<Void, Void, Void> {
    
        @Override
        protected Void doInBackground(Void... params) {
            ServiceHandler sh = new ServiceHandler();
    
            // put your url here...
            // Making a request to url and getting response
            jsonStr = sh.makeServiceCall("http://192.168.1.51/sumit/temp.txt",
                    ServiceHandler.GET);
    
            return null;
        }
    
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            try {
                jo = new JSONObject(jsonStr);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            try {
                if (jo.getInt("status") == 200) {
                    Toast.makeText(getApplicationContext(), "do something",
                            Toast.LENGTH_LONG).show();
    
                } else {
                    Toast.makeText(getApplicationContext(),
                            "" + jo.getInt("status"), Toast.LENGTH_LONG).show();
                }
    
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }  
    

    【讨论】:

      【解决方案4】:

      好的,如果问题是 String 或 Integer 抛出异常(我无法在 Android Studio 1.5.1 中复制),我建议您这样做:

      try
      {
          JSONObject json_response = new JSONObject(response);
          Object status = json_response.getString("status");
      
          if (json_response.get("status") instanceof Integer)
          {
              // it's an integer
          }
          else if (json_response.get("status") instanceof String)
          {
              // it's a String
          } else {
              // let's try to find which class is it
              Log.e("MYTAG", "status is an instance of "+json_parse.get("status").getClass().getName());
          }
      } catch (Exception e) {
          Log.e("MYTAG", "Error parsing status => "+e.getMessage());
      }
      

      您也可以先尝试这样做:

      JSONObject json_response = new JSONObject(response);
      String status = json_response.getString("status");
      int statint = Integer.parseInt(status);
      

      希望对你有帮助。

      【讨论】:

      • if (json_response.get("status") instanceof Integer) {Toast.makeText(getApplicationContext(), "Its integer", Toast.LENGTH_LONG).show();} 是的,谢谢,这正在某个地方,我如何匹配这些值?它必须匹配 200 然后我才能开始存储会话
      • 如果是整数,只使用 value == 200,如果是字符串,使用 value.equals("200")。您可以创建在两种情况下都调用的方法
      【解决方案5】:

      试试这个

      if(status.equalsIgnoreCase("200"))
      

      【讨论】:

      • 请添加详细信息。
      猜你喜欢
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 2021-05-13
      相关资源
      最近更新 更多