Error Parsing data org.json.Jsonexception

Asked

Viewed 194 times

-1

I’m new to Android and also don’t know much about JSON so I was doing a tutorial login But I’m wrong and I don’t know what to do. I think it is a php error or database because my register class and my insert query class also give the same error but my query class works well. This is the mistake:

Error Parsing data org.json.Jsonexception: Value  of type java.lang.String cannot be converted to Jsonobject

Android code:

    public class Login extends Activity implements OnClickListener{

        private EditText user, pass;
        private Button mSubmit, mRegister;

        // Progress Dialog
        private ProgressDialog pDialog;

        // JSON parser class
        JSONParser jsonParser = new JSONParser();

        //php login script location:

        //localhost :


//testing on your device
        //put your local ip instead,  on windows, run CMD > ipconfig
        //or in mac's terminal type ifconfig and look for the ip under en0 or en1
       // private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";

        //testing on Emulator:
        private static final String LOGIN_URL = "http://www.cresceranorte.com/WebService/login.php";

      //testing from a real server:
        //private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";

        //JSON element ids from repsonse of php script:
        private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

        @Override
protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        //setup input fields
        user = (EditText)findViewById(R.id.username);
        pass = (EditText)findViewById(R.id.password);

        //setup buttons
        mSubmit = (Button)findViewById(R.id.login);
    mRegister = (Button)findViewById(R.id.register);

        //register listeners
        mSubmit.setOnClickListener(this);
        mRegister.setOnClickListener(this);

}

    @Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
        case R.id.login:
                        new AttemptLogin().execute();
                    break;
            case R.id.register:
                    Intent i = new Intent(this, Register.class);
                        startActivity(i);
                    break;

       default:
                    break;
            }
    }

        class AttemptLogin extends AsyncTask<String, String, String> {

             /**
      * Before starting background thread Show Progress Dialog
      * */
                boolean failure = false;

                @Override
        protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(Login.this);
                pDialog.setMessage("Attempting login...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }

                @Override
        protected String doInBackground(String... args) {
                // TODO Auto-generated method stub
                 // Check for success tag
                int success;
                String username = user.getText().toString();
                String password = pass.getText().toString();
                try {
                    // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("username", username));
                        params.add(new BasicNameValuePair("password", password));

                        Log.d("request!", "starting");
                        // getting product details by making HTTP request
                    JSONObject json = jsonParser.makeHttpRequest(
                                       LOGIN_URL, "POST", params);

                        // check your log for json response
                    Log.d("Login attempt", json.toString());

                        // json success tag
                   success = json.getInt(TAG_SUCCESS);
                 if (success == 1) {
                          Log.d("Login Successful!", json.toString());
                           Intent i = new Intent(Login.this, ReadInfo.class);
                          finish();
                                startActivity(i);
                          return json.getString(TAG_MESSAGE);
                        }else{
                          Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                         return json.getString(TAG_MESSAGE);

                        }
                    } catch (JSONException e) {
                    e.printStackTrace();
                    }

          return null;

      }
   /**
         * After completing background task Dismiss the progress dialog
     * **/
                protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
                pDialog.dismiss();
                if (file_url != null){
                        Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
                    }

            }

        }

    }

PHP code:

<?php

//load and connect to MySQL database stuff
require("config.inc.php");

if (!empty($_POST)) {
    //gets user's info based off of a username.
    $query = "
            SELECT
                id,
                username,
                password
            FROM users
            WHERE
            username = :username
        ";

    $query_params = array(
        ':username' => $_POST['username']
    );

    try {
        $stmt   = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch (PDOException $ex) {
        // For testing, you could use a die and message.
        //die("Failed to run query: " . $ex->getMessage());

        //or just use this use this one to product JSON data:
        $response["success"] = 0;
        $response["message"] = "Database Error1. Please Try Again!";
        die(json_encode($response));

    }

    //This will be the variable to determine whether or not the user's information is correct.
    //we initialize it as false.
    $validated_info = false;

    //fetching all the rows from the query
    $row = $stmt->fetch();
    if ($row) {
        //if we encrypted the password, we would unencrypt it here, but in our case we just
        //compare the two passwords
        if ($_POST['password'] === $row['password']) {
            $login_ok = true;
        }
    }

    // If the user logged in successfully, then we send them to the private members-only page
    // Otherwise, we display a login failed message and show the login form again
    if ($login_ok) {
        $response["success"] = 1;
        $response["message"] = "Login successful!";
        die(json_encode($response));
    } else {
        $response["success"] = 0;
        $response["message"] = "Invalid Credentials!";
        die(json_encode($response));
    }
} 
?>

PHP code config.inc:

<?php

$username = "XXXXX";
$password = "XXXX";
$host = "XXXX";
$dbname ="android";

$options= array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');

try
{
    $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
    die("Failed to connect to the database".$ex->getMessage());
}

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);

if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
    function undo_magic_quotes_gpc(&$array)
    {
        foreach($array as &$value)
        {
            if(is_array($value))
            {
                undo_magic_quotes_gpc($value);
            }
            else
            {
                $value = stripslashes($value);
            }
        }
    }

    undo_magic_quotes_gpc($_POST);
    undo_magic_quotes_gpc($_GET);
    undo_magic_quotes_gpc($_COOKIE);
}

header('Content-Type: text/html; charset=utf-8');

session_start();

?>

1 answer

-1

I had the same problem with a project of mine. This exception indicates that your HTTP request is returning the text "", and not a JSON Object valid. Check that your PHP script is working correctly or that the parameter crossing is correct.

  • I also thought it was this but I in the application also have a log menu that also gives me a similar error but even giving error and the program stop responding and close the REGISTER APPEARS IN THE DATABASE. Class error record: Error Parsing data org.json.Jsonexception: Value  of type java.lang.String cannot be converted to Jsonobject

  • There is no other explanation for this error. The translation of the same already says: impossible to convert the "..." value of the String type to a Jsonobject. Debug your program and make sure your request response is in this format: Jsonobject

  • I was looking at the JSON results and came across this: {"Success":1,"message":"Invalid Credentials!" } the mistake that gives me is because 1 has no quotes? is that I until a few days had never heard of JSON.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.