Android : Android/JSON: org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject

on Saturday, August 16, 2014


I am gettig the error in title when I try to upload contents of my SQLite DB to a corresponding MYSQL Database using a PHP script hosted on 00webhost.com.


I am also getting the toast output: "Error while uploading. Please try again later."which shows that the LongOperation class (shown below) is being called.


I asked a very similar question where the issue was that the log in details were not correct. However this isn't the case for this script.


What is the issue with the code below?


Step 1: obtaining values from SQLite Database in onCreate()



Cursor cur = loginDataBaseAdapter.getSinlgeEntry();

if (cur != null) {

cur.moveToFirst();

while (cur.isAfterLast() == false) {

String sessionId = cur.getString(cur
.getColumnIndex("sessionid"));
String game = cur.getString(cur.getColumnIndex("game"));
String name = cur.getString(cur.getColumnIndex("name"));
int avgAttention = Integer.parseInt(cur.getString(cur
.getColumnIndex("avgattention")));
int avgMediation = Integer.parseInt(cur.getString(cur
.getColumnIndex("avgmeditation")));
int maxAttention = Integer.parseInt(cur.getString(cur
.getColumnIndex("maxattention")));
int maxMediation = Integer.parseInt(cur.getString(cur
.getColumnIndex("maxmeditation")));
int score = Integer.parseInt(cur.getString(cur
.getColumnIndex("score")));
String date = cur.getString(cur.getColumnIndex("date"));

if (!sessionId.equals(null))
UploadDataAuto(sessionId, game, name,
avgAttention, avgMediation, maxAttention,
maxMediation,score, date);
// }

cur.moveToNext();
}

}
}


UploadDataAuto Method called above:



public void UploadDataAuto(String sessionId, String game, String name,
Integer score, Integer avgAttn, Integer avgMed, Integer maxAttn,
Integer maxMed, String date){

// Defined URL where to send data
String ServerUrl = "http://ry.net16.net/gameRegistration.php?sessionId="
+ sessionId
+ "&game="
+ game
+ "&name="
+ name
+ "&avgMed="
+ avgMed
+ "&maxMed="
+ maxMed
+ "&avgAttn="
+ avgAttn
+ "&maxAttn="
+ maxAttn
+ "&score="
+ score
+ "&date="
+ date
+ "";

LongOperation longOperation = new LongOperation();
longOperation.sessionId = sessionId;
longOperation.execute(ServerUrl);

}


Private class LongOperation (called in method above):



private class LongOperation extends AsyncTask<String, String, Void> {

// Required initialization
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(LoginHome.this);
String data = "";
int sizeData = 0;
public String sessionId = "";

protected void onPreExecute() {
// NOTE: You can call UI Element here.

// Start Progress Dialog (Message)

Dialog.setMessage("Please wait.. Data is uploading .");
Dialog.show();

}

// Call after onPreExecute method
protected Void doInBackground(String... urls) {

/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;

// Send data
try {

// Defined URL where to send data
URL url = new URL(urls[0]);

// Send POST data request

URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();

// Get the server response

reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;

// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "");
}

// Append Server Response To Content String
Content = sb.toString();
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {

reader.close();
}

catch (Exception ex) {
}
}

/*****************************************************/
return null;
}

protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.

// Close progress dialog
Dialog.dismiss();

if (Error != null) {

// uiUpdate.setText("Output : "+Error);

} else {

// Show Response Json On Screen (activity)
// uiUpdate.setText( Content );

/****************** Start Parse Response JSON Data *************/

String OutputData = "";
JSONObject jsonResponse;

try {

/******
* Creates a new JSONObject with name/value mappings from
* the JSON string.
********/
jsonResponse = new JSONObject(Content);

String result = jsonResponse.get("result").toString();

if (result.equals("true")) {

//loginDataBaseAdapter.deleteUploadedRecord(sessionId);

Toast.makeText(LoginHome.this,
"Data is successfully uploaded.",
Toast.LENGTH_LONG).show();

} else {
Toast.makeText(
LoginHome.this,
"Error while uploading. Please try again later.",
Toast.LENGTH_LONG).show();
}

}
/****************** End Parse Response JSON Data *************/

catch (JSONException e) {

e.printStackTrace();
}

}
}

}


Corresponding PHP script from URL (log in details removed):



<?php

if(isset($_GET['sessionId']) && isset($_GET['game']) && isset($_GET['name']) && isset($_GET['avgMed']) && isset($_GET['maxMed']) && isset($_GET['avgAttn']) && isset($_GET['maxAttn']) && isset($_GET['score']) && isset($_GET['date']) )
{

$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";


// Provide host ip, mysql user name, password
$con = mysql_connect($mysql_host,$mysql_user,$mysql_password);

// Provide database name.
mysql_select_db($mysql_database);

$sessionId=$_GET['sessionId'];

$game=$_GET['game'];

$name=$_GET['name'];

$avgMed=$_GET['avgMed'];

$maxMed=$_GET['maxMed'];

$avgAttn=$_GET['avgAttn'];

$maxAttn=$_GET['maxAttn'];

$score=$_GET['score'];

$date=$_GET['date'];


$flag="false";


if(!empty($game) && !empty($name) && !empty($date) && !empty($sessionId))
{

$sql="Insert into `GameDetails` (`SessionId`,`game`,`name`,`AvgMediation`,`MaxMediation`,`AvgAttention` ,`MaxAttention`,`Score`,`Date`) values ('$sessionId','$game','$name','$avgMed','$maxMed','$avgAttn','$maxAttn','$score','$date') ";

$result=mysql_query($sql);

if($result)
{
$count= mysql_affected_rows();
if($count > 0)
{
$flag="true"; //result true

}

}

mysql_close($con);

echo json_encode(array("result"=>$flag));
}
}

?>


Full Logcat Error:



08-15 22:48:10.907: W/System.err(20233): org.json.JSONException: Value <!-- of type java.lang.String cannot be converted to JSONObject
08-15 22:48:10.907: W/System.err(20233): at org.json.JSON.typeMismatch(JSON.java:111)
08-15 22:48:10.907: W/System.err(20233): at org.json.JSONObject.<init>(JSONObject.java:159)
08-15 22:48:10.907: W/System.err(20233): at org.json.JSONObject.<init>(JSONObject.java:172)
08-15 22:48:10.907: W/System.err(20233): at com.example.brianapp.LoginHome$LongOperation.onPostExecute(LoginHome.java:259)
08-15 22:48:10.907: W/System.err(20233): at com.example.brianapp.LoginHome$LongOperation.onPostExecute(LoginHome.java:1)
08-15 22:48:10.907: W/System.err(20233): at android.os.AsyncTask.finish(AsyncTask.java:632)
08-15 22:48:10.907: W/System.err(20233): at android.os.AsyncTask.access$600(AsyncTask.java:177)
08-15 22:48:10.907: W/System.err(20233): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
08-15 22:48:10.907: W/System.err(20233): at android.os.Handler.dispatchMessage(Handler.java:102)
08-15 22:48:10.907: W/System.err(20233): at android.os.Looper.loop(Looper.java:157)
08-15 22:48:10.907: W/System.err(20233): at android.app.ActivityThread.main(ActivityThread.java:5356)
08-15 22:48:10.907: W/System.err(20233): at java.lang.reflect.Method.invokeNative(Native Method)
08-15 22:48:10.907: W/System.err(20233): at java.lang.reflect.Method.invoke(Method.java:515)
08-15 22:48:10.907: W/System.err(20233): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
08-15 22:48:10.907: W/System.err(20233): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
08-15 22:48:10.907: W/System.err(20233): at dalvik.system.NativeStart.main(Native Method)

0 comments:

Post a Comment