我目前正在开发一个与MAMP服务器通信的Android应用程序。 我在向其中一个表格添加新记录时遇到问题
JSONParser类
package com.example.transgoods;
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;
`enter code here`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 method
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;
}
}
MainActivity类
package com.example.transgoods;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.kosalgeek.asynctask.AsyncResponse;
import com.kosalgeek.asynctask.PostResponseAsyncTask;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
Intent startActivity;
EditText txtCarId;
private int success;
// url to create new product
private static String insert_new_car = "http://10.0.2.2/insert_new.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);
//edit text
txtCarId = (EditText) findViewById(R.id.txtCarID);
//start activity
startActivity = new Intent(this, StartActivity.class);
//button
Button btnNext = (Button) findViewById(R.id.btnCarNext);
btnNext.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.btnCarNext){
new InsertNewCar().execute();
if(success == 1){
Toast.makeText(getApplicationContext(), "new car saved", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "new car failed to save", Toast.LENGTH_LONG).show();
}
}
}
/**
* Background Async Task to Create new product
* */
class InsertNewCar extends AsyncTask<String, String, String> {
//get value for EditText
String carLicenseNo = txtCarId.getText().toString();
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating Product ("+carLicenseNo+")...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("carLicenseNo", carLicenseNo));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(insert_new_car,
"POST", params);
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
用于插入数据的PHP脚本
<?php
//array for json response
$response = array();
//check for required fields
if(isset($_GET[carLicenseNo])){
$carLicenseNo = $_GET['carLicenseNo']
//include db connect class
require_once __DIR__ . '/connect.php';
//connecting to db
$db = new DB_CONNECT();
//mysql inserting a new row
$result = mysql_query("INSERT INTO Cars(carLicenseNo) VALUES('', $carLicenseNo)");
//Check if row inserted or not
if ($result){
//success insert into db
$response["sucess"] =1;
$response["message"] = "new car saved...";
//echoing JSON response
echo json_encode($response);
} else {
//failed to insert row
$response ["success"] = 0;
$response["message"] = "An error has occurred....";
echo json_encode($response);
}
}else {
//required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
//echo json response
echo json_encode($response);
}
?>
当我在我的模拟器中运行应用程序时,我收到此错误
03-22 04:54:54.215: E/JSON Parser(2002): Error parsing data
org.json.JSONException: End of input at character 0 of
我猜测解析器有错误,但我似乎无法找到问题所在。有没有人对我为什么一直收到这个错误有任何想法?
此致