我试图将一些信息发送到数据库。它没有错误,但没有数据发送到数据库,我从服务器获取此消息I / Create Response(2026):{" message":&# 34;缺少必填字段","成功":0}。 我试图找到类似帖子的解决方案,但没有运气。
提前致谢!
java code:
public class AddRecipeActivity extends Activity {
private ImageView imageView;
private Button buttonNewPic;
private Button buttonImage;
private Bitmap image;
private static final int IMAGE_PICK = 1;
private static final int IMAGE_CAPTURE = 2;
JSONParser jsonParser = new JSONParser();
EditText AddRecipeTitleEditText; //title
EditText AddIngredientsEditTextMultiLine; // ingrediants
EditText AddDirectionsEditTextMultiLine; // directions
EditText Add_spinner; //catagory
EditText AddImageView ; //image
// url to create new product
private static String url_create_recipe = "http://studentcookbook.comoj.com/android_connect/create_recipe.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
Spinner spnr;
String[] Category = {
" - - - - - - Select Category - - - - - - ",
"chicken",
"meat",
"fish",
"pasta",
"salad",
"soup"
};
public ProgressDialog pDialog;
public String TAG_SCB_ID;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_recipe);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//testaddimageView
this.imageView = (ImageView) this.findViewById(R.id.AddImageView);
this.buttonNewPic = (Button) this.findViewById(R.id.CameraButton);
this.buttonImage = (Button) this.findViewById(R.id.GalleryButton);
AddRecipeTitleEditText=(EditText) findViewById(R.id.AddRecipeTitleEditText);//title
AddIngredientsEditTextMultiLine= (EditText) findViewById(R.id.AddIngredientsEditTextMultiLine);// ingrediants
AddDirectionsEditTextMultiLine=(EditText) findViewById(R.id.AddDirectionsEditTextMultiLine);//Dirctions
spnr = (Spinner)findViewById(R.id.Add_spinner);//category
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Category);
spnr.setAdapter(adapter);
this.buttonImage.setOnClickListener(new ImagePickListener());
this.buttonNewPic.setOnClickListener(new TakePictureListener());// Create button
Button btnCreateProduct = (Button) findViewById(R.id.AddSubmitButton1);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddRecipeActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
String isLoaded;
String title= AddRecipeTitleEditText.getText().toString();
String ingrediants = AddIngredientsEditTextMultiLine.getText().toString();
String description = AddDirectionsEditTextMultiLine.getText().toString();
// String catagory = Add_spinner.getText().toString();
// String image = AddImageView.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jsonParser.makeHttpRequest(url_create_recipe,
"POST", params);
params.add(new BasicNameValuePair("title", title));
params.add(new BasicNameValuePair("ingrediants", ingrediants));
params.add(new BasicNameValuePair("description", description));
//params.add(new BasicNameValuePair("catagory", catagory));
// params.add(new BasicNameValuePair("image", image));
// getting JSON Object
// Note that create product url accepts POST method
if(json!=null){
// do something
// check log cat fro response
Log.i("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AddRecipeActivity.class);
startActivity(i);
Toast.makeText(getApplicationContext(), "working fine", Toast.LENGTH_SHORT).show();
isLoaded = "Success";
// closing this screen
finish();
} else {
// failed to create product
isLoaded = "failed";
}
} catch (JSONException e) {
e.printStackTrace();
}}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
// if(file_url.equals("Success")) {
// // success: launch another activity
// Intent i = new Intent(getApplicationContext(), AddRecipeActivity.class);
// startActivity(i);
// AddRecipeActivity.this.finish();
// } else if(file_url.equals("Failed")) {
// // failed: do something
// Toast.makeText(getApplicationContext(), "An error occurred...", Toast.LENGTH_SHORT).show();
// }
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case IMAGE_PICK:
this.imageFromGallery(resultCode, data);
break;
case IMAGE_CAPTURE:
this.imageFromCamera(resultCode, data);
break;
default:
break;
}
}
}
/**
* Update the imageView with new bitmap
* @param newImage
*/
private void updateImageView(Bitmap newImage) {
BitmapProcessor bitmapProcessor = new BitmapProcessor(newImage, 300, 300, 0);
this.image = bitmapProcessor.getBitmap();
this.imageView.setImageBitmap(this.image);
}
/**
* Image result from camera
* @param resultCode
* @param data
*/
private void imageFromCamera(int resultCode, Intent data) {
this.updateImageView((Bitmap) data.getExtras().get("data"));
}
/**
* Image result from gallery
* @param resultCode
* @param data
*/
private void imageFromGallery(int resultCode, Intent data) {
Uri selectedImage = data.getData();
String [] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
this.updateImageView(BitmapFactory.decodeFile(filePath));
}
/**
* Click Listener for selecting images from phone gallery
* @author tscolari
*
*/
class ImagePickListener implements OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Escolha uma Foto"), IMAGE_PICK);
}
}
/**
* Click listener for taking new picture
* @author tscolari
*
*/
class TakePictureListener implements OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, IMAGE_CAPTURE);
}
}
}
php代码:
<?php
error_reporting(0);
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
error_reporting(0);
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['title'])&& isset($_POST['ingredients'])&& isset($_POST['directions'])&& isset($_POST['category'])) {
$title = $_POST['title'];
$ingredients = $_POST['ingredients'];
$directions = $_POST['directions'];
$category = $_POST['category'];
print_r($_POST);
// include db connect class
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'/android_connect/db_connect.php');
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO scb( title, ingredients, directions, category ) VALUES('$title', '$ingredients', '$directions', '$category')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Recipe successfully created.";
$response["id"] = mysql_insert_id();
// 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);
}
?>
logact错误消息:
10-30 00:56:29.695: E/AndroidRuntime(2245): FATAL EXCEPTION: AsyncTask #2
10-30 00:56:29.695: E/AndroidRuntime(2245): Process: com.example.studentcookbook, PID: 2245
10-30 00:56:29.695: E/AndroidRuntime(2245): java.lang.RuntimeException: An error occured while executing doInBackground()
10-30 00:56:29.695: E/AndroidRuntime(2245): at android.os.AsyncTask$3.done(AsyncTask.java:300)
10-30 00:56:29.695: E/AndroidRuntime(2245): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
10-30 00:56:29.695: E/AndroidRuntime(2245): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
10-30 00:56:29.695: E/AndroidRuntime(2245): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
10-30 00:56:29.695: E/AndroidRuntime(2245): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
10-30 00:56:29.695: E/AndroidRuntime(2245): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-30 00:56:29.695: E/AndroidRuntime(2245): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-30 00:56:29.695: E/AndroidRuntime(2245): at java.lang.Thread.run(Thread.java:841)
10-30 00:56:29.695: E/AndroidRuntime(2245): Caused by: java.lang.NullPointerException
10-30 00:56:29.695: E/AndroidRuntime(2245): at com.example.studentcookbook.AddRecipeActivity$CreateNewProduct.doInBackground(AddRecipeActivity.java:146)
10-30 00:56:29.695: E/AndroidRuntime(2245): at com.example.studentcookbook.AddRecipeActivity$CreateNewProduct.doInBackground(AddRecipeActivity.java:1)
10-30 00:56:29.695: E/AndroidRuntime(2245): at android.os.AsyncTask$2.call(AsyncTask.java:288)
10-30 00:56:29.695: E/AndroidRuntime(2245): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-30 00:56:29.695: E/AndroidRuntime(2245): ... 4 more
答案 0 :(得分:1)
类别是必需参数
在你的Java代码中,我看到: //params.add(new BasicNameValuePair(&#34; catagory&#34;,catagory));
注释掉,但也有关于catagory而不是类别
的拼写错误答案 1 :(得分:1)
&#39;成分&#39; !=&#39;成分&#39;
&#39;产品类别&#39; !=&#39;类别&#39;
您发布的内容以及脚本要查找的内容不匹配。