2014-01-23 3 views
1

У меня есть текущее приложение, которое отправляет и извлекает данные из базы данных MySQL, но информация, которую я передавал, была String. Как я могу обновить приведенный ниже код, чтобы иметь возможность отправлять изображения.Отправка изображения в базу данных MySQL с помощью Android

public class NewProductActivity extends Activity { 

// Progress Dialog 
private ProgressDialog pDialog; 

JSONParser jsonParser = new JSONParser(); 
EditText inputName; 
EditText inputPrice; 
EditText inputDesc; 
EditText inputImg; 
Button btnTakePhoto; 
ImageView imgTakenPhoto; 
private static final int CAM_REQUREST = 1313; 
// url to create new product 
private static String url_create_product = "http://buiud.com/android_connect/create_product.php"; 

// JSON Node names 
private static final String TAG_SUCCESS = "success"; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.add_product); 

    // Edit Text 
    inputName = (EditText) findViewById(R.id.inputName); 
    inputPrice = (EditText) findViewById(R.id.inputPrice); 
    inputDesc = (EditText) findViewById(R.id.inputDesc); 
    inputImg = (EditText) findViewById(R.id.imageView1); 
    // Create button 
    Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct); 

    // button click event 
    btnCreateProduct.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View view) { 
      // creating new product in background thread 
      new CreateNewProduct().execute(); 
     } 
    }); 
    btnTakePhoto = (Button) findViewById(R.id.button1); 
    imgTakenPhoto = (ImageView) findViewById(R.id.imageView1); 

    btnTakePhoto.setOnClickListener(new btnTakePhotoClicker()); 

} 
@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    // TODO Auto-generated method stub 
    super.onActivityResult(requestCode, resultCode, data); 

     if (requestCode == CAM_REQUREST) { 
      Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); 
      imgTakenPhoto.setImageBitmap(thumbnail); 
     } 
} 

class btnTakePhotoClicker implements Button.OnClickListener 
{ 
    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 

     Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
     startActivityForResult(cameraIntent, CAM_REQUREST); 
    } 
} 
/** 
* 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(NewProductActivity.this); 
     pDialog.setMessage("Creating Product.."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    /** 
    * Creating product 
    * */ 
    protected String doInBackground(String... args) { 
     String name = inputName.getText().toString(); 
     String price = inputPrice.getText().toString(); 
     String description = inputDesc.getText().toString(); 
     String image = inputImg.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("description", description)); 
     params.add(new BasicNameValuePair("image", image)); 

     // getting JSON Object 
     // Note that create product url accepts POST method 
     JSONObject json = jsonParser.makeHttpRequest(url_create_product, 
       "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 product 
       Intent i = new Intent(getApplicationContext(), AllProductsActivity.class); 
       startActivity(i); 

       // closing this screen 
       finish(); 
      } else { 
       // failed to create product 
      } 
     } 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(); 
    } 

} 
} 

Примечание: Я добавил поле изображения, как я сделал другие поля String, но теперь приложение останавливается, он не может преобразовать изображение как текст, очевидно. Дайте мне знать, что вы думаете, или какой-либо доступ к кастингу. Я просто беру фотографию, и эта фотография должна быть отправлена ​​в MySQL.

+2

магазин путь изображения в базе данных – Raghunandan

+0

вы можете сохранить фотографию во внешней или внутренней памяти устройства и сохранить путь в примере MySQL базы данных – DroidDev

+1

кода будет высоко ценится – raklar

ответ

1

Если вы хотите отправить изображение на сервер! Вы должны изменить его в строке Base 64.

Для сохранения его в базе данных! Вы должны преобразовать его в Blob типа!

попробуйте этот код:

 Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);   
     ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want. 
     byte [] byte_arr = stream.toByteArray(); 
     String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT); 

И передать это в качестве параметра, как вы добавляете другие параметры в запросе!

params.add(new BasicNameValuePair("image",image_str)); 

Надеюсь, это поможет! См. Это link для более подробной информации.

+0

Это LONGBLOB в области баз данных, как IMG, но как я могу изменить код выше, прямо сейчас это действительно вид вида из макета. – raklar

+0

@ user3129325 См. Ответ на обновления, если он помогает –

+0

Кажется, работает, но единственной ошибкой, которую я получаю, является то, что; Метод encodeBytes (byte []) не определен для типа Base64 – raklar

Смежные вопросы