Android : JSONException when using php to enter data to database

on Thursday, July 10, 2014


this is MainActivity.class which consists of two edit text fields and a button . when a button is pressed the data just entered in edit text field is sent to database in server.



package com.Users.user.booking;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity{
EditText etNumberOfTickets,etId;
Button btnConfirmBook;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();


private static String urlbooking= "http://10.0.2.2/minor_project/bookingdetails";
private static final String TAG_SUCCESS = "success";

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.ticketbook);

etId =(EditText) findViewById(R.id.etId);
etNumberOfTickets=(EditText) findViewById(R.id.etNumberOfTickets);
btnConfirmBook= (Button) findViewById(R.id.btnConfirmBook);
btnConfirmBook.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
new BookingSeats().execute();

}
});
}
class BookingSeats extends AsyncTask<String, Void, Void>{

String success;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("adding to our database..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected Void doInBackground(String... arg0) {
String numberticket = etNumberOfTickets.getText().toString();
String passedid=etId.getText().toString();
Integer price=Integer.parseInt(numberticket)*100;
String p=price.toString();



// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("customer_id", passedid));
params.add(new BasicNameValuePair("number", numberticket));
params.add(new BasicNameValuePair("price", p));
Log.d("passedid /numberof ticket/ price", passedid + " / " + numberticket +" / " + price);

// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = JSONParser.makeHttpRequest(urlbooking,"POST", params);

// check log cat for response
Log.d("Create Response", json.toString());

// check for success tag
try {

int success = json.getInt(TAG_SUCCESS);

if (success == 1) {
// successfully created product
Toast.makeText(getBaseContext(), "success", Toast.LENGTH_LONG).show();
// Intent i = new Intent(getApplicationContext(), DashboardActivity.class);
// startActivity(i);
//
// closing this screen
finish();
} else {
Toast.makeText(getBaseContext(), "something went wrong", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}

return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}

}
}


this is my JSONParser.class



package com.Users.user.booking;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

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 static 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();
reader.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;

}
}


my php file named bookingdetails.php



<?php


/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/

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


$customer_id = $_POST['customer_id'];

$price = $_POST['price'];

$numberticket = $_POST['numberticket'];

//$date = date('Y-m-d H:i:s');
// 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 bookingtable(customer_id, numberticket, price) VALUES( '$customer_id', '$numberticket', '$price')");


// check if row inserted or not

if ($result) {
// successfully inserted into database

$response["success"] = 1;

$response["message"] = "successfully created.";


// 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);


}
?>


my logcatoutput shows these errors 07-11 10:12:13.992: E/JSON Parser(2951): Error parsing data org.json.JSONException: Value


0 comments:

Post a Comment