2014-09-02 138 views
0

当我试图通过PHP更新分数到MYSQL时,我在LogCat中出现错误。 给出的错误: “解析数据org.json.JSONException时出错:值<类型java.lang.String的表单不能转换为JSONObject”。 我很新的这个,所以我不知道如何解决这个问题?解析JSON数据时出错,org.json.jsonexception,java.lang.String无法转换

这里是我的代码:

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; 

} 

更新比分的Android代码JSONParser类:

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> 
"; 
} 
?> 

有人可以帮我吗?

在此先感谢!

+6

粘贴您的堆栈跟踪和你的JSON太 – bhargavg 2014-09-02 18:14:10

+5

,另外,尽量用别针把它降低到一个更短的一段代码。我非常怀疑你需要250行来证明这个问题。 – 2014-09-02 18:16:10

回答

0

这是一个糟糕的API设计,我不知道是谁写的这个教程,每次我看到有人使用它,这是同一个问题发生。

您正在编写一个android应用程序,应该没有涉及HTML,当字段丢失时,您仍然应该返回json数据和而不是 HTML表单。

仔细阅读错误:

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

是形式是HTML标签,这意味着该条件不成立。

然后,如果你看一下条件

if($_POST['submit']) 

,因为你没有一个html在您的应用程序提交按钮,将永远是正确的。

你应该检查你的应用程序发送的值是否已设置,如果不发回一个json响应错误,说明。


<?php 
$response = array(); 

if(isset($_POST['stars'], $_POST['username'])){ 

    $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{ 
     $query = sprintf("UPDATE users SET easy_level1 ='%s' WHERE username ='%s'", 
            mysql_real_escape_string($stars), 
            mysql_real_escape_string($username)); 
     mysql_query($query); 
    } 
    catch (Exception $ex) { 
     $response["success"] = 0; 
     $response["message"] = "Database Error. Please Try Again!"; 
    } 


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

} 
else{ 
    $response["success"] = 0; 
    $response["message"] = "Missing post data!"; 
} 
echo json_encode($response); 
?> 
+0

感谢您的反馈,您是对的!该按钮从来没有点击......我从来没有想过这个!非常感谢你!我将编辑代码! – Joeri 2014-09-04 18:40:26

+0

如果您想感谢我,请接受答案 – meda 2014-09-04 18:41:36

+0

完成后,我会立即更改按钮的代码! – Joeri 2014-09-04 18:42:53

相关问题