有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

向数据库发送JSON时发生java错误

我正试图向数据库发送一些信息。看起来还可以,没有错误,但没有数据发送到数据库,我从服务器i/Create响应(2026)收到此消息:{“消息”:“缺少必需字段”,“成功”: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/安卓_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 (安卓.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, 安卓.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, 安卓.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(安卓.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__.'/安卓_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 安卓.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 安卓.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 安卓.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

共 (2) 个答案

  1. # 1 楼答案

    类别是必需的参数

    在Java代码中,我看到: //params。添加(新的BasicNameValuePair(“分类”,分类))

    注释掉了,但在分类上也有错别字,而不是类别

  2. # 2 楼答案

    “IngRadiants”!='配料

    “分类”!='类别'

    您正在发布的项目与脚本正在查找的项目不匹配