мое приложение, которое должно передавать пользовательские входные данные в мою базу данных SQL. Я должен заполнить все поля, а затем нажмите "Сохранить", чтобы данные обновлялись в моем sql файле. После очистки много ошибок, я, наконец, застрял на 1 ошибка, которую я не могу решить. любая предоставленная помощь будет чрезвычайно оценена. Пожалуйста, совет, какие изменения я могу сделать, чтобы избавиться от ошибки. Ошибка
08-04 05:47:48.799: E/JSON Parser(1506): Error parsing data [End of input at character 0 of ]
Мои коды ниже:
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputDriver;
EditText inputLicence;
EditText inputOfficer;
EditText inputSpeed;
EditText FineAppl;
EditText inputCategory;
TextView registerFine;
// url to create new fine
private static String url_create_fine = "http://192.168.1.1/android_api/create.php";
// JSON Node names/
private static final String TAG_SUCCESS = "success";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
speed = (EditText) findViewById(R.id.editText3);
Fine = (TextView)findViewById(R.id.editText4);
btnSelectDate=(Button)findViewById(R.id.buttonSelectDate);
btnSelectTime=(Button)findViewById(R.id.buttonSelectTime);
inputDriver = (EditText) findViewById(R.id.editText1);
inputLicence = (EditText) findViewById(R.id.editText2);
inputOfficer = (EditText) findViewById(R.id.editText5);
inputSpeed = (EditText) findViewById(R.id.editText3);
FineAppl = (EditText) findViewById(R.id.editText4);
inputCategory = (EditText) findViewById(R.id.editText6);
registerFine = (TextView) findViewById(R.id.fineregistered);
// Create button
Button btnRegisterfine = (Button) findViewById(R.id.savefine);
// button click event
btnRegisterfine.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewFine().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewFine extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FineCalc.this);
pDialog.setMessage("Registering Fine..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
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 from response
//Log.d("Create Response", json.toString());
// check for success tag
try {
//if (json.getString(TAG_SUCCESS) != null) {
if(json != null && !(json).isNull(TAG_SUCCESS)){
registerFine.setText("");
String success = json.getString(TAG_SUCCESS);
// int success = json.getInt(TAG_SUCCESS);
// if (success == 1) {
if(Integer.parseInt(success) == 1){
// successfully created product
//Intent i = new Intent(getApplicationContext(), UserLogin.class);
//startActivity(i);
registerFine.setText("Successful");
// closing this screen
finish();
} else {
} // failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public 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 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, HTTP.UTF_8), 8);
//BufferedReader reader = new BufferedReader(new InputStreamReader(
// is, HTTP.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());
Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
}
// return JSON String
return jObj;
}
}
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);
}
?>