2014-10-30 4 views
2

데이터베이스에 정보를 보내려고합니다. 그것은 괜찮아 보이는 오류가 아니지만 데이터가 데이터베이스에 전송되며, 서버 에서이 메시지를 받고 있어요/응답 (2026) 만들기 : { "메시지": "필수 입력란이 누락되었습니다", "성공" : 0}. 비슷한 게시물에서 해결책을 찾으려고했지만 운이 없었습니다.데이터베이스에 JSON을 보내는 중 오류가 발생했습니다.

미리 감사드립니다.

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 

답변

1

카테고리는 자바 코드에서 필요한 매개 변수

입니다 내가 볼 :,//params.add(New BasicNameValuePair ("catagory", catagory));

하지만 대신 카테고리의 catagory에 오타, 주석

1

'ingrediants'! = '성분'

'catagory'! = '카테고리'

당신이하고있는 항목 게시 및 스크립트가 찾고있는 항목이 일치하지 않습니다.

+2

나는 그것을 고쳤지 만 지금은 비판적이다 : AsyncTask # 2 오류는 logcat 오류 메시지 – sasuri

+0

에 대한 편집 된 버전을 보아라. 나는 정말로 자바를 모르지만 그것을 보면서 나는 어디서나 정의를 보지 못한다. 'getApplicationContext()'호출 (아마도 글로벌/어딘가에있을 수도 있습니다). 그러면 null 포인터를 반환하는 경우와 같은 오류가 발생할 수 있습니다. – AlpineCoder

+2

아니요, 문제의 원인이 아닙니다. – sasuri

관련 문제