I need seriously help !!
I use below code to get the image from gallery and finally insert it into MySQL
through php
. Image will get from Activity B, and finally return to Activity A and save into MySQL once the button in Activity A is clicked.
Activity B
Uri selectedImage;
private Uri imageUri;
ImageView imageView;
private void activeGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
selectedImage = data.getData();
imageView.setImageURI(selectedImage);
}
break;
submit.setOnClickListener(new View.OnClickListener() { // back to Activity A
@Override
public void onClick(View v) {
Intent returnIntent = new Intent();
amount = Amount.getText().toString();
description = Description.getText().toString();
type = spinnerType.getSelectedItem().toString();
returnIntent.putExtra("type", type);
returnIntent.putExtra("description", description);
returnIntent.putExtra("amount", amount);
if(selectedImage!=null) {
returnIntent.putExtra("img_uri", selectedImage.toString());
}
else
{
returnIntent.putExtra("img_uri", Uri.parse("android.resource://com.example.project.myapplication/mipmap/no_image").toString());
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Activity A (Image and text can be returned from B to A)
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
if (resultCode == RESULT_OK) {
if (requestCode == PROJECT_REQUEST_CODE) {
ReceiveType = data.getStringExtra("type");
ReceiveDescription = data.getStringExtra("description");
ReceiveAmount = data.getStringExtra("amount");
imgURI = Uri.parse(data.getStringExtra("img_uri"));
// Toast.makeText(getApplication(),ReceiveType+ReceiveAmount+ReceiveDescription+"",Toast.LENGTH_LONG).show();
if (mClickedPosition == -1) { // if icon clicked
if (obj != null)
obj.addNewItem(ReceiveType, ReceiveAmount, imgURI, ReceiveDescription);
addOrRemoveFooter();
} else {
if (obj != null)
obj.changeItem(mClickedPosition, ReceiveType, ReceiveAmount, imgURI, ReceiveDescription);
}
}
}
}
Here comes to the interesting part. When submit button in Activity A, is clicked
public void uploadImageAndText(ArrayList<ImageAndText> listItems, final String id) {
JSONArray jsonArray = new JSONArray();
try {
for (ImageAndText i : listItems) {
JSONObject object = new JSONObject();
String type = i.getType();
String[] Type = type.split(":");
object.put("type", Type[1]);
// Toast.makeText(getApplicationContext(), Type[1], Toast.LENGTH_LONG).show();
String amount = i.getAmount();
String[] Amount = amount.split(":");
object.put("amount", Amount[1]);
String description = i.getDescription();
String[] Description = description.split(":");
object.put("description", Description[1]);
String image=i.getImage().toString();
Uri imageUri = Uri.parse(image);
object.put("image", image);
object.put("ts_id", id);
object.put(Configs.KEY_IMAGE,getStringImage(imageUri));
jsonArray.put(object);
}
} catch (JSONException e) {
e.printStackTrace();
}
AddStaff ru = new AddStaff(jsonArray);
ru.execute();
}
class AddStaff extends AsyncTask<String, Void, String> {
ProgressDialog loading;
JSONArray jsonArray;
AddStaff(JSONArray jsonArray) {
this.jsonArray = jsonArray;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(AddClaims.this, "Please Wait", null, true, true);
}
@Override
protected String doInBackground(String... params) {
try {
HashMap<String, String> data = new HashMap<String, String>();
data.put("listItems", jsonArray.toString());
//Log.d("log", "This json = " + jsonArray.toString());
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(Configs.STAFF_BENEFIT, data);
return result;
} catch (Exception e) {
return "";
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
//Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
}
public String getStringImage(Uri imgUri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
} catch (Exception e) {
}
return "";
}
}
I did many test here. If the selected image is from download
or whatsapp
, it can be inserted. If I select the image from My photos
, no image will be inserted. Why would this happen ???
SaffBenefit.php
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( !empty( $_POST['listItems'] ) ){
$listItems = json_decode( $_POST['listItems'], true );
$mysqli = new mysqli("localhost", "spiral69_wp178", "q1w2e3r4", "spiral69_androiddb");
if( $mysqli->connect_errno ) echo "Failed to connect to MySQL";
$sql="INSERT INTO `staff_benefit`
( `type`, `amount`, `description`, `image`, `ts_id` )
VALUES ( ?, ?, ?, ?, ? )";
if($stmt=$mysqli->prepare($sql )){
$url="http://www.ss.com/Android/CRUD/PhotoUpload/";
foreach( $listItems as $item ){
$id = uniqid();
$image_name = $id.".png";
$save_path = 'PhotoUpload/'.$image_name;
$image_url = $url.$image_name;
$bytes=file_put_contents($save_path, base64_decode($item['image']));
if( !$bytes ){
echo 'Error saving image';
}else{
$stmt->bind_param('sssss',
$item['type'],
$item['amount'],
$item['description'],
$image_url,
$item['ts_id'] );
if( !$res=$stmt->execute()){
echo 'Query failed with code: '.$stmt->errno;
}
}
}
}
$mysqli->close();
}
}
?>
There can be the issue that base64 encode data
is too high which you are sending to server and MySql
is unable to handle. What you should do is change the compression value to 70%
as bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
Hope this helps.