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

14ifxucb  于 2021-07-13  发布在  Java
关注(0)|答案(5)|浏览(199)

我一直在用安卓上的凌空,似乎我真的不能让这个特别的部分工作
这是我的json

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

这是活动课

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

cpjpxq1n1#

先把你的照片打印出来 response 检查你的回答是什么,或者有没有什么额外的东西。

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

然后和你的价值观比较。

zynd9foi

zynd9foi2#

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

你的 status 不是 String 所以,
叫这个

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

然后

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

注:

你可以用 getInt 直接代替 getString .

u4dcyp6a

u4dcyp6a3#

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

kjthegm64#

好的,如果问题是字符串或整数抛出异常(我无法在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);

希望对你有帮助。

ippsafx7

ippsafx75#

试试这个

if(status.equalsIgnoreCase("200"))

相关问题