2

I've been working with Volley on Android, it seems that I can't really get this particular part working

this is my json

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

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

it always skips that condition as it doesn't match, and toast print value 200 as a proof that status returns with value and that value is 200

I did try

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

if (status == 200)

which return "JSONException: Value of type java.lang.String cannot be converted to JSONObject", any insights?

Edit:

here is complete 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();
    }
}
11
  • maybe try to trim the String first Commented Mar 28, 2016 at 8:24
  • try String.valueOf(status).equals("200") . Does it match ? Commented Mar 28, 2016 at 8:26
  • not sure but you can trim your string or check 200.0 Commented Mar 28, 2016 at 8:26
  • First try to print the response to the log and see whether there's an extra character in the response. Commented Mar 28, 2016 at 8:28
  • 3
    Your JSON snippet shows that status is a number and not a string. So why do you call getString instead of getInt (or maybe getLong)? Comparison is also easier with that ... Commented Mar 28, 2016 at 8:28

5 Answers 5

0

First try to print your response check what is your response say or some extra thing is there or not.

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

and then compare with your value.

Sign up to request clarification or add additional context in comments.

Comments

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

Your status is not String format so,

Call this

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

Then

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

Note :

  1. You can use getInt directly instead of getString .

5 Comments

tried int getStatus = Integer.parseInt(json_response.getString("status")) and int status = json_response.getInt("status"), and I got this error toast "JSONException: Value of type java.lang.String cannot be converted to JSONObject"
@NikSaifulAnuar Facing same problem ?
@NikSaifulAnuar - can you please put whole updated code ?
@KevalPatel sorry for taking so long, here it is gist.github.com/sanik90/5476cbff81f0e67233a1
0

Use this class to get json string 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;
}
}

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

Comments

0

Ok if the problem is that either String or Integer is throwing an exception (which I cannot replicate in Android Studio 1.5.1), I recommend you to do this:

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

Also you can try doing this first:

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

I hope it helps.

2 Comments

if (json_response.get("status") instanceof Integer) {Toast.makeText(getApplicationContext(), "Its integer", Toast.LENGTH_LONG).show();} and yes thank you, this is getting somewhere, and how do I match those values? it has to match 200 then I can start store session
If it's integer, use just value == 200, if it's a string use value.equals("200"). You can create a method that you call inside both cases
0

Try with this

if(status.equalsIgnoreCase("200"))

1 Comment

Please add details .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.