我尝试将所选图片从活动B 返回到活动A list View
,如下图所示。但有些图片无法从活动B 返回到 A ,即使我已压缩它们,我仍然可以
E/JavaBinder﹕ !!! FAILED BINDER TRANSACTION !!! Error.
活动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();
}
});
活动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);
}
}
被修改
活动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();
}
});
活动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();
}
}
?>
答案 0 :(得分:2)
http://codepen.io/DevinGray/pen/gPxwvB用于使用Intent
发送数据。如下所示:
如果参数或返回值太大而不适合 事务缓冲区,然后调用将失败和 将抛出TransactionTooLargeException。
Binder事务缓冲区的固定大小有限,目前为1Mb ......
因此,如果我们发送byte
任何大图片的数组将导致TransactionTooLargeException
。
在两个应用程序组件之间发送图像是使用图像URI,图像路径,id,...而不是发送位图或字节数组。
在您的情况下,请执行以下操作:
1。使用来自活动B的意图发送selectedImage
进入onActivityResult
的URI到A:
更改:
returnIntent.putExtra("photo", bytes);
为:
returnIntent.putExtra("img_uri", selectedImage.toString());
2. 从Intent中获取img_uri
作为活动A中的字符串,然后将其解析为URI。在活动A的onActivityResult
方法中:
更改:
byte[] bytes = data.getByteArrayExtra("photo");
为:
Uri imgURI = Uri.parse(data.getStringExtra("img_uri"));
3。将addNewItem
方法第二个参数从Bitmap
更改为URI并传递imgURI
:
obj.addNewItem(ReceiveType, ReceiveAmount, imgURI, ReceiveDescription);
4. 在ListView适配器中使用setImageURI
为ImageView设置图像:
imageView.setImageURI(imgUri);