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

I have been stuck on this for a while. Simply cannot figure out whats wrong. A pair of fresh eyes would be very helpful. I keep on getting the org.json.JSONException: End of input at character 0 of and cannot figure it out.
My JSONParser
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 response = httpClient.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
//HttpEntity httpEntity = httpResponse.getEntity();
//is = httpEntity.getContent();
JSONArray jsArray = new JSONArray(responseBody);
JSONObject js = jsArray.getJSONObject(0);
String returnvalmsg = js.getString("message");
String returnvalsucc = js.getString("success");
}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();
// } catch (JSONException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
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;
}
}
Activity
btnRegisterfine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewFine().execute();
}
});
}
/**
* Background Async Task to Register Fine
* */
class CreateNewFine extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Finecalc.this);
pDialog.setMessage("Registering Fine..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Registering Fine
* */
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 Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_fine,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully Registered Fine
//Intent i = new Intent(getApplicationContext(), Finecalc.class);
//startActivity(i);
registerFine.setText("DONE");
// closing this screen
finish();
} else {
// failed to Register Fine
}
} 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 done
pDialog.dismiss();
}
}
My Php
<?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"] = 1;
$response["message"] = "Speed Ticket Successfully Registered.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
And my error:
08-05 09:53:03.321: W/System.err(3072): org.json.JSONException: End of input at character 0 of
08-05 09:53:03.321: W/System.err(3072): at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
08-05 09:53:03.321: W/System.err(3072): at org.json.JSONTokener.nextValue(JSONTokener.java:97)
08-05 09:53:03.331: W/System.err(3072): at org.json.JSONArray.(JSONArray.java:92)
08-05 09:53:03.331: W/System.err(3072): at org.json.JSONArray.(JSONArray.java:108)
08-05 09:53:03.331: W/System.err(3072): at com.lta.fine.JSONParser.makeHttpRequest(JSONParser.java:60)
08-05 09:53:03.341: W/System.err(3072): at com.lta.fine.MainActivity$CreateNewFine.doInBackground(MainActivity.java:191)
08-05 09:53:03.341: W/System.err(3072): at com.lta.fine.MainActivity$CreateNewFine.doInBackground(MainActivity.java:1)
08-05 09:53:03.351: W/System.err(3072): at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-05 09:53:03.351: W/System.err(3072): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-05 09:53:03.361: W/System.err(3072): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-05 09:53:03.361: W/System.err(3072): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-05 09:53:03.361: W/System.err(3072): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-05 09:53:03.361: W/System.err(3072): at java.lang.Thread.run(Thread.java:841)
08-05 09:53:03.361: E/Buffer Error(3072): Error converting result java.lang.NullPointerException: lock == null
08-05 09:53:03.371: E/JSON Parser(3072): Error parsing data org.json.JSONException: End of input at character 0 of

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();
}

Your is (member var?) isn't set for the POST case. Could its value be left over from some previous request?
In general, good idea to use local vars wherever possible.

Related

Android app not inserting values into MySQL through PHP

I am making an app which performs a transaction through a PHP script stored in the www folder of Wampserver of localhost.
But when I perform the transaction values are not inserted into the database and logcat displays this error:
07-26 16:55:54.036: E/Buffer Error(5511): Error converting result java.lang.NullPointerException
07-26 16:55:54.037: E/JSON Parser(5511): Error parsing data org.json.JSONException: End of input at character 0 of
But my app does not even crash and says the transaction is successful, which is called onPostExecute of my AsyncTask.
Please help me found out the bug that is causing unsuccessful insertion into the database.
I have two classes JSONParser and NewProductActivity as follows:
This one is NewProductActivity.java:
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
// url to create new product use wireless lan adapter wifi ipv4 address using ipconfig
// String url_create_product = "http://192.168.0.100/toll_system/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
String first_name;
String last_name;
String toll_no;
String toll_location;
String trans_amt;
String v_license_no;
String make_model;
String v_type;
String email_id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
TextView tv=(TextView)findViewById(R.id.textView1);
String contents = getIntent().getStringExtra("KEY1");
String ip_address=getIntent().getStringExtra("KEY2");
/* String arr[]=contents.split(",");
String trans_receipt_no=arr[0];
String firstname=arr[1];
String lastname=arr[2];
String toll_no=arr[3];
String toll_location=arr[4];
String trans_amt=arr[5];
String v_license_no=arr[6];
String make_model=arr[7];
String v_type=arr[8];*/
Toast toast = Toast.makeText(this, "Content:" + contents , Toast.LENGTH_LONG);
toast.show();
new CreateNewProduct().execute(contents,ip_address);
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Woooohoooo...");
Log.d("Perform:", "Performing");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// String name = inputName.getText().toString();
// String price = inputPrice.getText().toString();
// String description = inputDesc.getText().toString();
String contents=args[0];
String ip_address=args[1];
String arr[]=contents.split(",");
Log.d("Inside doInBackground :", contents);
//String trans_receipt_no=arr[0];
first_name=arr[0];
Log.d("First_name", first_name);
last_name=arr[1];
Log.d("Last_name", last_name);
toll_no=arr[2];
toll_location=arr[3];
trans_amt=arr[4];
v_license_no=arr[5];
make_model=arr[6];
v_type=arr[7];
email_id=arr[8];
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("name", name));
//params.add(new BasicNameValuePair("price", price));
//params.add(new BasicNameValuePair("description", description));
// params.add(new BasicNameValuePair("trans_receipt_no", trans_receipt_no));
params.add(new BasicNameValuePair("first_name", first_name));
params.add(new BasicNameValuePair("last_name", last_name));
params.add(new BasicNameValuePair("toll_no", toll_no));
params.add(new BasicNameValuePair("toll_location", toll_location));
params.add(new BasicNameValuePair("trans_amount", trans_amt));
params.add(new BasicNameValuePair("v_license_no", v_license_no));
params.add(new BasicNameValuePair("v_make_model", make_model));
params.add(new BasicNameValuePair("v_type", v_type));
params.add(new BasicNameValuePair("email_id", email_id));
// getting JSON Object
String url_create_product = "http://"+ip_address+"/toll_system/create_product.php";
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
// Log.d("Create Response", json.toString());
// check for success tag
/* try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
// Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
//startActivity(i);
String s="Transaction done!";
Toast toast = Toast.makeText(getApplicationContext(),"Status:"+s, Toast.LENGTH_LONG);
toast.show();
// closing this screen
finish();
} else {
Toast toast = Toast.makeText(getApplicationContext(),"Status:Failed", Toast.LENGTH_LONG);
toast.show();
// failed to create product
}
} 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 done
TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText("Transaction done!!!");
TextView tv1=(TextView)findViewById(R.id.textView3);
tv1.setText(first_name+" "+last_name);
TextView tv2=(TextView)findViewById(R.id.textView5);
tv2.setText(make_model);
TextView tv3=(TextView)findViewById(R.id.textView7);
tv3.setText(v_license_no);
TextView tv4=(TextView)findViewById(R.id.textView9);
tv4.setText("Rs."+trans_amt);
pDialog.dismiss();
}
}
}
And this is JSONParser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// 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;
}
}

Variables Not Being Sent To Server

I'm trying to insert data into the database from my app. I can fetch data, but when I try to pass variables to my server, I get the "Required field(s) is missing" error.
I've done this before with a different app, but that was before I had SSL installed on my website. Is there any chance SSL could be stopping the variables.
I tried keeping the code as simple as possible for testing purposes but I just can't figure it out. I have re-done several tutorials just to make sure I'm not making errors, but clearly I'm going wrong somewhere. Any help much appreciated!
class CreateNewProduct extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "name"));
params.add(new BasicNameValuePair("price", "2"));
params.add(new BasicNameValuePair("imgurl", "imgurl"));
JSONObject json = jsonParser.makeHttpRequest("http://myserver.com",
"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
finish();
} else {
Log.d("TEST", "Failed to create product");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
PHP Code:
<?php
$response = array();
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['imgurl'])) {
$name = "joey";
$price = "3";
$imgurl = "blowey";
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysqli_query("INSERT INTO products(name, price, imgurl) VALUES('$name', '$price', '$imgurl')");
if ($result) {
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
JSON Parser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// 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, "utf-8"));
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;
}
}
Try to replace:
post.setEntity(new UrlEncodedFormEntity(dataToSend));
with
post.setRequestBody(dataToSend);

Android: JSONParser returns NullPointerException

I've read many other topics on SO from people who received the same exception, but none of the proposed solutions worked. So here's my problem:
I'm trying to download a userlist from my database through a function in my app. The JSONParser keeps returning a NullPointException on this particular table from the database. I've successfully used the JSONParser class on other queries, but it doesn't work on this one. I've tested the PHP file which handles the query, and it returns the exact values I want as a JSON OBject. If the table is empty, it returns:
{
"success":0,
"message":"No users found"
}
If the table contains user information, it returns:
{
"success":1,
"users":[
{
"ID":someID1,
"NAME":someName1
"PHONE":somePhoneNumber1
},
{
"ID":someID2,
"NAME":someName2
"PHONE":somePhoneNumber2
}]
}
I'm starting the request by calling
LoadAllUsers load = new LoadAllUsers();
load.execute();
in a certain method. This is my LoadAllUsers class:
public class LoadAllUsers extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(allUsers.this);
pDialog.setMessage("Laden van alle gebruikers...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... args) {
updateJSONData();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
I receive a NullPointerException on the first line of my updateJSONdata() method, which is:
public void updateJSONData() {
JSONObject json = jParser.getJSONFromUrl(my_url);
try {
int success = json.getInt("success");
if (success == 1) {
JSONArray users = json.getJSONArray("users");
for (int i = 0; i<users.length(); i++) {
JSONObject c = users.getJSONObject(i);
String id = c.getString("ID");
String name = c.getString("NAAM");
String phone =c.getString("TELEFOON");
HashMap<String,String> map = new HashMap<String, String>();
map.put("ID",id);
map.put("name",name);
map.put("phonenumber",phone);
if (phoneNumber == phone) {
ID = Integer.parseInt(id);
this.name = name;
}
userlist.add(map);
}
} else {
Log.d("Geen succes!", "Helaas!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
So, the exception is thrown in the line with jParser.getJSONFromUrl(...).
My JSONParser class, of which jParser is an instance, is:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
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");
Log.d("Gemaakte paramstring",paramString);
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.d("httpResponse: ",httpResponse.toString());
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;
}
}
And the LogCat message is:
05-07 10:46:24.995 27615-27686/com.example.user.my_app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.user.my_app, PID: 27615
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.example.user.my_appcenter_tile.updateJSONData(center_tile.java:376)
at com.example.user.my_app.center_tile$Memberlist.doInBackground(center_tile.java:419)
at com.example.user.my_app.center_tile$Memberlist.doInBackground(center_tile.java:406)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
I would be very grateful if you could help me out with this problem.
Well, jParser is null in updateJSONdata().
Make sure to check if it's != null before using it.
And if it should not be null, then fix your code.
Your error is just a NullPointerException.
You can use 'has' keyword to check availability of json keys, then can parse Json to avoid exception,otherwise you can track via Null Pointer exception.
public void updateJSONData() {
JSONObject json = jParser.getJSONFromUrl(my_url);
try {
int success = json.getInt("success");
boolean isAvail=json.has("users");
if (success == 1) {
if(isAvail)
JSONArray users = json.getJSONArray("users");
for (int i = 0; i<users.length(); i++) {
}
}
}
catch(Exception e){
}
}
1. jParser is NULL so use
// make sure my_url has json string in it
// read json first and use in place of my_url
JSONObject jsonObjTokener = (JSONObject) new JSONTokener(my_url).nextValue();
// get success
String isSuccess = jsonObjTokener.getString("success");
// get users
JSONObject mUser = jsonObjTokener.getJSONObject("users");
at that line
2. You did spelling mistake at
String name = c.getString("NAAM");
correct to
String name = c.getString("NAME");

Unable to insert row from Android to MySQL using PHP

I am trying to insert data from android to MySQL but it does not show any error in logcat but displays the json message in the app.
Here is my PHP script.
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
require("config.inc.php");
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['userName']) && isset($_POST['userContact']) && isset($_POST['userAddress']) && isset($_POST['userStore']) && isset($_POST['userRequest'])) {
$userName = $_POST['userName'];
$userContact = $_POST['userContact'];
$userAddress = $_POST['userAddress'];
$userStore = $_POST['userStore'];
$userRequest = $_POST['userRequest'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO userrequests(userName, contactNumber, userAddress, storeList, requestBody) VALUES('$userName', '$userContact', '$userAddress', '$userStore', '$userRequest')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "IsitdispllayingthusOops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Here is my JSONParser.java
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, "utf-8"), 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");
Log.i("log_tag","Line reads: " + line);
}
// 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, "utf-8"), 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;
}
}
Here is my MainActivity.java
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private EditText userName, userContact, userAddress, userRequest;
private Spinner userStore;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://10.0.2.2/callarocket/register.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner dropdown = (Spinner)findViewById(R.id.StoreSpinner);
String[] items = new String[]{"NZ Mamak", "Indo Shop", "NZ Supermarket"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
userName = (EditText)findViewById(R.id.EditName);
userContact = (EditText)findViewById(R.id.EditContact);
userAddress = (EditText)findViewById(R.id.EditAddress);
userStore = (Spinner)findViewById(R.id.StoreSpinner);
userRequest = (EditText)findViewById(R.id.EditRequest);
mRegister = (Button)findViewById(R.id.SubmitButton);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating Request...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = userName.getText().toString();
String usercontact = userContact.getText().toString();
String useraddress = userAddress.getText().toString();
String userstore = userStore.getSelectedItem().toString();
String userrequest = userRequest.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", username));
params.add(new BasicNameValuePair("userContact", usercontact));
params.add(new BasicNameValuePair("userAddress", useraddress));
params.add(new BasicNameValuePair("userStore", userstore));
params.add(new BasicNameValuePair("userRequest", userrequest));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
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(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
And the error I am getting inside the emulator is this json message in my php script
$response["message"] = "IsitdispllayingthusOops! An error occurred.";
I couldn't find the reason why new row cannot be inserted into MySQL.
POST can not be used by external applications. You have to use GET instead.

Android httpGET JSON array

GOAL: Call this function and look into an array of JSON returned from php and see if element[0] or [1] == 1. PHP queries a table of booleans and I want to know which are 1 and 0 in order to continue functionality.
I have this function to perform a httpGET and return a JSON object
class CheckVotingStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Vote.this);
pDialog.setMessage("Checking vote Status...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
try {
// Building Parameters
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jParser.getJSONFromUrl(LOGIN_URL);
// check your log for json response
// Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Log.d("Login Successful!", json.toString());
JSONArray answerObj = json.getJSONArray(TAG_ANSWER);
// get first product object from JSON Array
JSONObject answer = answerObj.getJSONObject(0);
String bool1s = answer.getString(TAG_BOOL1);
JSONObject answer2 = answerObj.getJSONObject(1);
String bool2s = answer2.getString(TAG_BOOL2);
/******************************************/
if (bool1s.equals("1")&& bool2s.equals("0"))
{
startVoting = true;
}
else if (bool1s.equals("0")&& bool2s.equals("1"))
{
endVoting = true;
voted = false;
}
/*******************************************/
//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;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Vote.this, file_url, Toast.LENGTH_LONG).show();
}
}
My PHP page queries to return two bools from a database
$response = array();
$resttt = "SELECT startingBool, endingBool FROM vote_count";
$result = mysql_query("$resttt");
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$answer = array();
$answer["startingBool"] = $result["startingBool"];
$answer["endingBool"] = $result["endingBool"];
// success
$response["success"] = 1;
$response["answer"] = array();
array_push($response["answer"], $answer);
// echoing JSON response
echo json_encode($response);
}
I'm getting an end of input exception and an err for no value for answer
JSON PARSER
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
//DefaultHttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = createHttpClient();
HttpGet httpGet = new HttpGet(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpGet);
// 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 {
Log.v("JSON", json);
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return the JSON Object.
return jObj;
}
your echo from php must be like this
{"success":1,"answer":[{"bool1":"0","bool2":"1"}]}
and your php skript
//conect to database, create table bool_table, insert data to bool_table.......
$response = array();
$resttt = "SELECT bool1, bool2 FROM bool_table";
$result = mysql_query("$resttt");
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$answer = array();
$answer["bool1"] = $result["bool1"];
$answer["bool2"] = $result["bool2"];
// success
$response["success"] = 1;
$response["answer"] = array();
array_push($response["answer"], $answer);
// echoing JSON response
echo json_encode($response);
}
and parsing JSON
private static final String TAG_SUCCESS = "success";
private static final String TAG_ANSWER = "answer";
private static final String TAG_BOOL1 = "bool1";
private static final String TAG_BOOL2 = "bool2";
int success;
......
...
JSONObject json = jsonParser.makeHttpRequest("xxxxxxxxxxxxxx", "GET", params);
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray answerObj = json.getJSONArray(TAG_ANSWER);
// get first product object from JSON Array
JSONObject answer = answerObj.getJSONObject(0);
String bool1s = answer.getString(TAG_BOOL1));
String bool2s = answer.getString(TAG_BOOL2));
}else{
.......
....
when you have jsonarray try get value
JSONArray json = jParser.getJSONFromUrl(LOGIN_URL);
JSONObject json_obj = json.getJSONObject(0);
String bool1s = json_obj.getString(TAG_BOOL1);
String bool2s = json_obj.getString(TAG_BOOL2);

Categories

Resources