Error parsing data org.json.JSONException: Value

I want to make a login registration system with my app but is not working properly. Here the code where I think I’ve got an error.

PHP LOGIN SCRIPT :

<?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));
}
} else {
$response["message"] = "Enter username and password!";
die(json_encode($response));
}
?>
    <h1>Login</h1> 
    <form action="login.php" method="post"> 
        Username:<br /> 
        <input type="text" name="username" placeholder="username" /> 
        <br /><br /> 
        Password:<br /> 
        <input type="password" name="password" placeholder="password" value="" /> 
        <br /><br /> 
        <input type="submit" value="Login" /> 
    </form> 
    <a href="register.php">Register</a>
<?php


?> 

LoginActivity :

public class LoginActivity extends ActionBarActivity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;

private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();

// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static final String TAG_MESSAGE = "message";

// Testing on emulator
private static String LOGIN_URL = "http://10.0.2.2/webservice/login.php";

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

    // Importing all assets like buttons, text fields
    inputEmail = (EditText) findViewById(R.id.loginEmail);
    inputPassword = (EditText) findViewById(R.id.loginPassword);
    btnLogin = (Button) findViewById(R.id.btnLogin);
    btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
    loginErrorMsg = (TextView) findViewById(R.id.login_error);

    // Login button Click Event
    btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            new LoginProcess().execute();

        }
    });

    // 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 class LoginProcess extends AsyncTask<String, String, String> {

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

    }

    @Override
    protected String doInBackground(String... args) {
        // Check for success tag
        int success;
        String username = inputEmail.getText().toString();
        String password = inputPassword.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(KEY_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());
                Intent i = new Intent(LoginActivity.this,
                        MainActivity.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(LoginActivity.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}
}

JSONParser Class:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "n");
        }
        is.close();
        json = sb.toString();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    Log.d("JSON Parser", json);
    try {
        jObj = new JSONObject(json);            
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {
    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

When I want to login with the right username and password it’s working but if I put right username and wrong password I’ve got an error. But if I delete query_params at :

$result = $stmt->execute($query_params);

I don’t have any errors but I can’t login anymore

The logcat :

08-31 10:40:39.885: E/Trace(1239): error opening trace file: No such file or directory (2)
08-31 10:40:40.785: D/dalvikvm(1239): GC_FOR_ALLOC freed 118K, 2% free 10936K/11143K, paused 55ms, total 57ms
08-31 10:40:40.845: I/dalvikvm-heap(1239): Grow heap (frag case) to 13.346MB for 2764816-byte allocation
08-31 10:40:40.954: D/dalvikvm(1239): GC_CONCURRENT freed 1K, 2% free 13635K/13895K, paused 24ms+6ms, total 108ms
08-31 10:40:41.334: D/libEGL(1239): loaded /system/lib/egl/libEGL_emulation.so
08-31 10:40:41.345: D/(1239): HostConnection::get() New Host Connection established 0x2a126450, tid 1239
08-31 10:40:41.357: D/libEGL(1239): loaded /system/lib/egl/libGLESv1_CM_emulation.so
08-31 10:40:41.376: D/libEGL(1239): loaded /system/lib/egl/libGLESv2_emulation.so
08-31 10:40:41.455: W/EGL_emulation(1239): eglSurfaceAttrib not implemented
08-31 10:40:41.465: D/OpenGLRenderer(1239): Enabling debug mode 0
08-31 10:40:45.545: D/request!(1239): starting
08-31 10:40:45.645: W/EGL_emulation(1239): eglSurfaceAttrib not implemented
08-31 10:40:48.205: E/JSON Parser(1239): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
08-31 10:40:48.355: W/dalvikvm(1239): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
08-31 10:40:48.754: E/AndroidRuntime(1239): FATAL EXCEPTION: AsyncTask #1
08-31 10:40:48.754: E/AndroidRuntime(1239): java.lang.RuntimeException: An error occured while executing doInBackground()
08-31 10:40:48.754: E/AndroidRuntime(1239):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-31 10:40:48.754: E/AndroidRuntime(1239):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-31 10:40:48.754: E/AndroidRuntime(1239):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-31 10:40:48.754: E/AndroidRuntime(1239):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-31 10:40:48.754: E/AndroidRuntime(1239):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-31 10:40:48.754: E/AndroidRuntime(1239):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-31 10:40:48.754: E/AndroidRuntime(1239):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-31 10:40:48.754: E/AndroidRuntime(1239):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-31 10:40:48.754: E/AndroidRuntime(1239):     at java.lang.Thread.run(Thread.java:856)
08-31 10:40:48.754: E/AndroidRuntime(1239): Caused by: java.lang.NullPointerException
08-31 10:40:48.754: E/AndroidRuntime(1239):     at com.example.diycenter.LoginActivity$LoginProcess.doInBackground(LoginActivity.java:118)
08-31 10:40:48.754: E/AndroidRuntime(1239):     at com.example.diycenter.LoginActivity$LoginProcess.doInBackground(LoginActivity.java:1)
08-31 10:40:48.754: E/AndroidRuntime(1239):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-31 10:40:48.754: E/AndroidRuntime(1239):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-31 10:40:48.754: E/AndroidRuntime(1239):     ... 5 more
08-31 10:40:51.844: E/WindowManager(1239): Activity com.example.diycenter.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4148a190 that was originally added here
08-31 10:40:51.844: E/WindowManager(1239): android.view.WindowLeaked: Activity com.example.diycenter.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4148a190 that was originally added here
08-31 10:40:51.844: E/WindowManager(1239):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
08-31 10:40:51.844: E/WindowManager(1239):  at andr

Leave a Comment