Reputation: 2748
I'm trying to return the selected image from Activity B to Activity A list View
like image below. But some of the image cannot be returned from Activity B to A even I have compressed them, I still get
E/JavaBinder﹕ !!! FAILED BINDER TRANSACTION !!! Error.
Activity A ListView
Button addImage, submit;
Bitmap photo,bmp;
private void activeTakePhoto() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
@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) {
Uri selectedImage = data.getData();
try{
photo=MediaStore.Images.Media.getBitmap(getContentResolver(),selectedImage);
ByteArrayOutputStream stream =new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
bytes= stream.toByteArray();
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
imageView.setImageBitmap(photo);
}catch(IOException e)
{
e.printStackTrace();
}
}
break;
submit.setOnClickListener(new View.OnClickListener() { //return value 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();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
returnIntent.putExtra("type", type);
returnIntent.putExtra("description", description);
returnIntent.putExtra("amount", amount);
returnIntent.putExtra("photo", bytes);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Activity A
Bitmap ReceiveImage, photo;
@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");
byte[] bytes = data.getByteArrayExtra("photo");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
if (mClickedPosition == -1) { // if icon clicked
if (obj != null)
obj.addNewItem(ReceiveType, ReceiveAmount, bmp, ReceiveDescription);
} else {
if (obj != null)
obj.changeItem(mClickedPosition, ReceiveType, ReceiveAmount, ReceiveImage, ReceiveDescription);
}
}
Edited
Activity B
@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();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver()
.query(selectedImage, filePathColumn, null, null,
null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap a = (BitmapFactory.decodeFile(picturePath));
photo = scaleBitmap(a, 200, 150);
imageView.setImageBitmap(photo); // image looked blurry
}
break;
case REQUEST_IMAGE_CAPTURE:
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
String fileName = "tempimg.jpg";
try {
photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
} catch (Exception e) {
e.printStackTrace();
}
}
}
submit.setOnClickListener(new View.OnClickListener() { // return value and image to Activity A listView
@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);
returnIntent.putExtra("img_uri", selectedImage.toString());
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Activity A
PicCustomBaseAdapter obj;
ArrayList<ImageAndText> images = new ArrayList<ImageAndText>();
@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");
ReceiveImage = data.getParcelableExtra("photo");
Uri 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);
} else {
//if (obj != null)
// obj.changeItem(mClickedPosition, ReceiveType, ReceiveAmount, ReceiveImage, ReceiveDescription);
}
}
}
}
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { // button is clicked
Toast.makeText(getApplicationContext(), a + "", Toast.LENGTH_LONG).show();
uploadImageAndText(images, lastID);
Intent intent = new Intent(getApplicationContext(), HomePage.class);
startActivity(intent);
}
});
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]);
Uri uploadImage = i.getImage();
imagess = getImage(uploadImage); // cannot resolved getImages
object.put("image", imagess);
object.put("ts_id", id);
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) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("listItems", jsonArray.toString());
data.put(Configs.KEY_IMAGE,imagess);
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(Configs.STAFF_BENEFIT, data);
return result;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
}
staffBenefit.php
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( !empty( $_POST['listItems'] ) ){
$mysqli = new mysqli("127.0.0.1:3307", "root", "", "androiddb");
if( $mysqli->connect_errno ) echo "Failed to connect to MySQL";
$image = $_POST['image'];
$listItems = json_decode( $_POST['listItems'], true );
$sql="SELECT id FROM staff_benefit ORDER BY id ASC";
$id=0;
$res=$mysqli->query( $sql );
while( $rs=$res->fetch_object() ) $id=$rs->id;
$path="$id.png";
$actualpath="http://192.168.107.115:80/Android/CRUD/PhotoUpload/$path";
$sql="INSERT INTO `staff_benefit` ( `type`, `amount`, `description`, `image`, `ts_id` ) VALUES ( ?, ?, ?, ?, ? )";
$stmt=$mysqli->prepare( $sql );
$pathelements=array( realpath( $_SERVER['DOCUMENT_ROOT'] ), 'CRUD', 'PhotoUpload', '' );
$savepath = realpath( implode( DIRECTORY_SEPARATOR, $pathelements ) ) . "{$id}.png";
$bytes=file_put_contents( $savepath, base64_decode( $image ) );
if( !$bytes ){
echo 'Error saving image';
}
if ( $stmt ) {
foreach( $listItems as $item ){
$stmt->bind_param('sssss', $item['type'], $item['amount'], $item['description'], $actualpath, $item['ts_id'] );
$res=$stmt->execute();
if( !$res ) echo 'Query failed with code: '.$stmt->errno;
}
}
$mysqli->close();
}
}
?>
Upvotes: 1
Views: 6423
Reputation: 132992
Parcel used for sending data using Intent
. as see here:
If the arguments or the return value are too large to fit in the transaction buffer, then the call will fail and TransactionTooLargeException will be thrown.
The Binder transaction buffer has a limited fixed size, currently 1Mb...
So if we send byte
Array of any large image will cause TransactionTooLargeException
.
For sending image between two application components is use image URI,image path,id,... instead of sending Bitmap or byte Array.
In your case do it as:
1. Send selectedImage
URI which getting in onActivityResult
using Intent from Activity B to A:
Change :
returnIntent.putExtra("photo", bytes);
to:
returnIntent.putExtra("img_uri", selectedImage.toString());
2. Get img_uri
as String in Activity A from Intent then parse it to URI. In onActivityResult
method of Activity A:
Change :
byte[] bytes = data.getByteArrayExtra("photo");
to:
Uri imgURI = Uri.parse(data.getStringExtra("img_uri"));
3. Change addNewItem
method second parameter to URI from Bitmap
and pass imgURI
:
obj.addNewItem(ReceiveType, ReceiveAmount, imgURI, ReceiveDescription);
4. In ListView Adapter use setImageURI
for setting image for ImageView:
imageView.setImageURI(imgUri);
Upvotes: 2