Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've got an error in the LogCat when I'm trying to update a score via PHP to MYSQL. The given error: "Error parsing data org.json.JSONException: Value < form of type java.lang.String cannot be converted to JSONObject". I'm quite new to this so I don't know how to fix this...

Here is my code:

Android code for updating the score:

int scoreEL;
String username;


if(DifficultyMenu.scoreEL1 < scoreEL1){
            new UpdateScores().execute();

        }




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

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
       int success;
       try {
           List<NameValuePair> params = new ArrayList<NameValuePair>();
           params.add(new BasicNameValuePair("username", username));
           params.add(new BasicNameValuePair("stars", String.valueOf(scoreEL1)));

           Log.d("request!", "starting");

           JSONObject json = jsonParser.makeHttpRequest(
                  LOGIN_URL_1, "POST", params);

           Log.d("Login attempt", json.toString());

           success = json.getInt(TAG_SUCCESS);
           if (success == 1) {
            Log.d("Updated successful!", json.getString(TAG_MESSAGE));

            finish();
            return json.getString(TAG_MESSAGE);
           }else{
            Log.d("Login Failure!", json.getString(TAG_MESSAGE));
            return json.getString(TAG_MESSAGE);

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

       return null;

 }

JSONParser class:

public class JSONParser {

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

// constructor
public JSONParser() {

}


public JSONObject getJSONFromUrl(final String url) {

    // Making HTTP request
    try {
        // Construct the client and the HTTP request.
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // Execute the POST request and store the response locally.
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // Extract data from the response.
        HttpEntity httpEntity = httpResponse.getEntity();
        // Open an inputStream with the data content.
        is = httpEntity.getContent();

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

    try {
        // Create a BufferedReader to parse through the inputStream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        // Declare a string builder to help with the parsing.
        StringBuilder sb = new StringBuilder();
        // Declare a string to store the JSON object data in string form.
        String line = null;

        // Build the string until null.
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        // Close the input stream.
        is.close();
        // Convert the string builder data to an actual string.
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // Try to 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 the JSON Object.
    return jObj;

}


// function get json from url
// by making HTTP POST or GET mehtod
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;

}

}

PHPcode:

<?php
if($_POST['submit']){

$stars= $_POST['stars'];
$username = $_POST['username'];

$connect = mysql_connect("*****", "****", "*****") or die("Can't connect to database!");
mysql_select_db("a9698368_webserv") or die("Can't select database!");

try{

    $checkUsername = mysql_query("SELECT username FROM users WHERE username =      '$username'");
    $checkuser = mysql_fetch_assoc($checkUsername);
    if($username == $checkuser){
        $response["success"] = 0;
        $response["message"] = "User doesn't exist!";
        die(json_encode($response));
    }

}
catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error. Please Try Again!";
    die(json_encode($response));
}


try{

mysql_query("
UPDATE users SET easy_level1 = '$stars' WHERE username = '$username'
");
}
catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error. Please Try Again!";
    die(json_encode($response));
}

try{
$check = mysql_query("
SELECT easy_level1 FROM users WHERE username = '$username'
");
}
catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Can't check if the new score is successfully updated!";
    die(json_encode($response));
}

if($check !== $stars){
    $updated = true;
}

if ($updated) {
    $response["success"] = 1;
    $response["message"] = "Updated successful!";
    die(json_encode($response));
} else {
    $response["success"] = 0;
    $response["message"] = "Can't update the stars!";
    die(json_encode($response));
}

mysql_close();

}
else{

echo"
<form action='updateEL1.php' method='POST'>
Username: <input type='text' name='username'><br>
Stars: <input type='text' name='stars'><br>
<input type='submit' name='submit' value='Update'>
</form>
";
}
?>

Can somebody help me?

Thanks in advance!

share|improve this question

put on hold as off-topic by Jon Skeet, Sadikhasan, NidhishKrishnan, EdChum, 2Dee 7 hours ago

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example." – Jon Skeet, Sadikhasan, NidhishKrishnan, EdChum, 2Dee
If this question can be reworded to fit the rules in the help center, please edit the question.

6  
paste your stacktrace and your JSON too –  bhargavg 21 hours ago
5  
And additionally, try to pin it down to a much shorter piece of code. I very much doubt that you need ~250 lines to demonstrate the problem. –  Jon Skeet 21 hours ago

1 Answer 1

This is a bad designed for API, I wonder who wrote this tutorial, Everytime I see someone use it it's the same issue occuring.

You are writing an android app, there should be no HTML involved, when the field are missing you should still return json data and not HTML form.

Read the error carefully:

"Error parsing data org.json.JSONException: Value < form of type java.lang.String cannot be converted to JSONObject"

Yes form is the html tag, and that means the condition was not met.

Then if you look at the condition

if($_POST['submit'])

That will never be true because you dont have an html submit button in your app.

You should be checking if the value you sent by the app are set, if not send back a json response error stating that.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.