Org.JSON.JSON Exception:End of Input at Character 0

org.json.JSONException: End of input at character

Change

 JSONObject jsonObject = new JSONObject(result);

to

result=getJSONUrl(url);  //<< get json string from server
JSONObject jsonObject = new JSONObject(result);

inside doInBackground method of DownloadJSONFileAsync because currently you are not making any post for getting Json data from the server and just trying to parse an empty string to json

JSONException: End of input at character 0

You are probably getting a blank response. Its not null but the jsontext is empty. So you are getting this error and not a Nullpointer exception

Are you sending right parameters to server.Also Check url respond to POST requests or not.

org.json.JSONException: End of input at character 0 of

Answer : Response object should of Generic type - ResponseBody.

See below Correct code for reference.

Now response.body() method will return object ResponseBody
i.e.

ResponseBody rb = response.body(); 
rb.string();

Here ResponseBody have method string() which returns String object but internally string() method calls Util.closeQuietly(source); which makes response empty once method string() gets called.

Just remove Log.d(TAG, response.body().string()); and follow below code.


Reference - okhttp3.ResponseBody.java

error : org.json.JSONException: End of input at character 0

Correct code :

@Override
public void onResponse(Call call, Response<ResponseBody> response) throws IOException {
if (response.isSuccessful()) {

String remoteResponse=response.body().string();
Log.d(TAG, remoteResponse);
try {
JSONObject forecast = new JSONObject(remoteResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}

org.json.JSONException: End of input at character 0 of, android

As you have seen in your logcat 1576-1576/com.example.neshat.androidhive2 D/RegisterActivity﹕ Register Response: which is the result of Log.d(TAG, "Register Response: " + response.toString());, response is an empty string, so your app will get org.json.JSONException: End of input at character 0 of at the line JSONObject jObj = new JSONObject(response);.

You should check response is not null and not an empty string first.

org.json.JSONException: End of input at character 0 of in android studio

    private void execute(final Context context)
{
String url = UrlManager.getUrl(context, R.string.signup_url);
User user = User.getInstance();
try {
url += "&name=" + mFirstName + "&last=" + mLastName + "&mob=" + mMobile +
"&email=" + mEmail+
"&pass=" + UrlManager.prepareUrlPart(mPassword);
} catch (Exception e) {
e.printStackTrace();
}

final ProgressDialog pDialog;
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();

Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response)
{
try
{
JSONObject userObj = response;
userInfo = new UserInfo();
userInfo.LoadItem(context,
userObj);
String state = userObj.getString("State");
if (state .equals("1")) {
// Load user data from json and save them into local database
// User user = User.getInstance();
// user.loadFromJSon(response);
/// user.saveUser();
onResult(true);
} else {
onResult(false);
}
}
catch (Exception e)
{
Log.d("Error", e.getMessage());
e.printStackTrace();
}
pDialog.dismiss();
}
};

Response.ErrorListener errorListener = new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
};

JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url,null, listener, errorListener);
MyApplication.getInstance().addToRequestQueue(request);
}

Volley JSONException: End of input at character 0 of

I also have encountered this issue.

It's not necessarily true that this is because a problem on your server side - it simply means that the response of the JsonObjectRequest is empty.

It could very well be that the server should be sending you content, and the fact that its response is empty is a bug. If, however, this is how the server is supposed to behave, then to solve this issue, you will need to change how JsonObjectRequest parses its response, meaning creating a subclass of JsonObjectRequest, and overriding the parseNetworkResponse to the example below.

    @Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));

JSONObject result = null;

if (jsonString != null && jsonString.length() > 0)
result = new JSONObject(jsonString);

return Response.success(result,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}

Keep in mind that with this fix, and in the event of an empty response from the server, the request callback will return a null reference in place of the JSONObject.

org.json.JSONException: End of input at character 0

org.json.JSONException: End of input at character 0

Usually means you are not getting any JSON. you will need to debug your app to find out why.

In the mean time I will give you some pointers:

PHP

  • Not sure if the INSERT is successful but I noticed you are not using $db variable.
  • You are open to sql injection using deprecated mysql extension
  • you should use boolean in your json
  • echo the json at the end.

<?php

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['driver'], $_POST['licencenum'], $_POST['officer'], $_POST['speed'] , $_POST['fine'],$_POST['category'])){

$driver = $_POST['driver'];
$licencenum = $_POST['licencenum'];
$officer = $_POST['officer'];
$speed = $_POST['speed'];
$fine = $_POST['fine'];
$category = $_POST['category'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO fineregister(driver,licencenum,officer,speed,fine,category) VALUES ('$driver','$licencenum','$officer','$speed','$fine','$category')");

// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = true;
$response["message"] = "Speed Ticket Successfully Registered.";
// echoing JSON response
} else {
// failed to insert row
$response["success"] = false;
$response["message"] = "Oops! An error occurred.";
}
} else {
// required field is missing
$response["success"] = false;
$response["message"] = "Required field(s) is missing";
}
// echoing JSON response
echo json_encode($response);
?>

Java:

  • I see that your method returns a JSONObject that limits you already
    from parsing arrays. Instead return the json as string then parse it.
  • You are parsing the data inside of the method, this makes it more
    difficult to use.
  • I see little to no reason to use GET you might as well split that
    function.

public String makeHttpRequest(String url, List<NameValuePair> params) 
{
InputStream is = null;
String json = "";

// Making HTTP request
try {
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();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// return JSON String
return json;

}

AsyncTask

protected String doInBackground(String... args) {
String driver = inputDriver.getText().toString();
String licencenum = inputLicence.getText().toString();
String officer = inputOfficer.getText().toString();
String speed = inputSpeed.getText().toString();
String fine= FineAppl.getText().toString();
String category = inputCategory.getText().toString();

// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("driver", driver));
params.add(new BasicNameValuePair("licencenum", licencenum));
params.add(new BasicNameValuePair("officer", officer));
params.add(new BasicNameValuePair("speed", speed));
params.add(new BasicNameValuePair("fine", fine));
params.add(new BasicNameValuePair("category", category));

// getting JSON String
// Note that create product url accepts POST method
String json = jsonParser.makeHttpRequest(url_create_fine, params);

return json;
}

protected void onPostExecute(String json) {
// dismiss the dialog once done
pDialog.dismiss();
Log.d("mylog", "json = " + json);
//parse here
}

In doInbackground perform the request and pass the result to post execute, log the json object there, if you get anything in the log you can start parsing. using boolean value it will be easier.

try {
JSONObject jsonData = new JSONObject(json);
Boolean success = jsonData.getBoolean("success");
String message = jsonData.getString("message");

if (success) {
//success
} else {
// failed to Register Fine
}
} catch (JSONException e) {
e.printStackTrace();
}


Related Topics



Leave a reply



Submit