java - 将 JSON 发送到数据库时出错

标签 java php android mysql

我正在尝试向数据库发送一些信息。看起来没问题,但没有数据发送到数据库,我从服务器 I/Create Response(2026) 收到此消息:{“message”:“缺少必填字段”,“成功” :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

最佳答案

类别是必需参数

在你的Java代码中我看到: //params.add(new BasicNameValuePair("类别", 类别));

已注释掉,但也有类别错误,而不是类别

关于java - 将 JSON 发送到数据库时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26643085/

相关文章:

java - 过滤后如何确定ListView的ArrayAdapter是否为空

osgi - 如何定义最低 GRE 要求(1.5 _ 或更高 _)?

java - 如何使用本地系统上运行的 Spring Boot 应用程序连接到 AWS 上的 DynamoDB?

php - 优化 MySQL 搜索过程

php - 如何从 PHP 的 DateTime::diff 中获取总天数?

android - ndk-build arm-linux-androideabi-gcc : Command not found

java - java如何解析像[new File ("filename.txt")]这样的相对路径?

java - libusb 与 USB 大容量存储器通信

php - 从小写到大写

java - 如何使用 Retrofit 2 在同一个键上发布多个值?