使用JSON和PHP将数据插入MAMP服务器
我目前正在开发一个android应用程序,它将与MAMP服务器通信。 在我的一个表中添加新记录时遇到问题 JSONParser类使用JSON和PHP将数据插入MAMP服务器,php,android,json,Php,Android,Json,我目前正在开发一个android应用程序,它将与MAMP服务器通信。 在我的一个表中添加新记录时遇到问题 JSONParser类 package com.example.transgoods; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import
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;
}
}
我猜测解析器有错误,但我似乎无法找到问题所在。有人知道我为什么老是犯这个错误吗
关于您根本没有得到任何响应,因为您的php脚本肯定会失败(在有机会输出单个字符之前)。您的is_集合有问题,在下一行(no“;”)等…您的查询也将失败。您正在定义一列,但有两个值。此外,mysql_*函数已弃用,不应使用。更多信息@DavidJones我应该用什么来代替mysql_*函数?@YvesLeBorg我更正了“;”但仍然是相同的问题,但不是代替“字符0处的输入结束”现在我得到“字符1处的输入结束”@pavlos您可以选择PDO或mysqli。我个人使用PDO。我建议您做一些研究,看看什么最适合您的用例。
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
//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