Android string.equals()与条件不匹配

时间:2016-03-28 08:23:37

标签: java android android-volley

我一直在使用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();
    }
}

它始终跳过该条件,因为它不匹配,并且吐司打印值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();
    }
}

5 个答案:

答案 0 :(得分:0)

首先尝试打印您的response检查您的回复是什么或有些额外的事情是否存在。

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

然后与您的价值进行比较。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

使用此类获取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();
        }
    }
}  

答案 3 :(得分:0)

试试这个

if (!EventLog.SourceExists(sourceName))
{
    lock (_eventSourceCreationLock)
    {
        if (!EventLog.SourceExists(sourceName))
        {
            EventLog.CreateEventSource(sourceName, _logName);
        }
    }
}

答案 4 :(得分:0)

好的,如果问题是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);

我希望它有所帮助。