Android を使用して http リクエストをサーバーに送信しようとしています。サーバーには、MySQL データベースのアイテムを追加/削除/編集するための PHP スクリプトがあります。サーバーに接続しているのか、コードの実行時に何が起こっているのかわかりません。データの解析中にエラーが発生します org.json.JSONException: Value
私は PHP に非常に慣れていないため、ガイドラインとしてこのチュートリアルに従っています。私はかなり立ち往生しています。
飲み物を追加する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();
// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['quantity'])) {
$name = $_POST['name'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
// 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 drinks(name, price, quantity) VALUES('$name', '$price', '$quantity')");
// 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"] = "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);
}?>
新しい飲み物の活動:
public class NewDrinkActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputQuantity;
// url to create new Drink
private static String url_create_Drink = "http://jjohnson.bugs3.com/android_connect/create_drink.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_drink);
// Edit Text
inputName = (EditText) findViewById(R.id.edtName);
inputPrice = (EditText) findViewById(R.id.edtPrice);
inputQuantity = (EditText) findViewById(R.id.edtQuantity);
// Create button
Button btnAddDrink = (Button) findViewById(R.id.btnAdd);
// button click event
btnAddDrink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new Drink in background thread
new CreateNewDrink().execute();
}
});
}
/**
* Background Async Task to Create new Drink
* */
class CreateNewDrink extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewDrinkActivity.this);
pDialog.setMessage("Creating Drink..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating Drink
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String quantity = inputQuantity.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("quantity", quantity));
// getting JSON Object
// Note that create Drink url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_Drink,
"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 Drink
Intent i = new Intent(getApplicationContext(), StockActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create Drink
}
} 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();
}
}
}
JSON パーサー:
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;
}
}
それが役立つ場合は、ServerFree.com を使用してファイルをホストしています。