代码之家  ›  专栏  ›  技术社区  ›  Tony

仍然获得E/JavaBinder!!!绑定器事务失败!!!压缩图像时出错

  •  1
  • Tony  · 技术社区  · 9 年前

    我正在尝试从中返回所选图像 活动B 活动A list View 如下图所示。但有些图像无法从 活动B A. 即使我压缩了它们,我还是会

     E/JavaBinder﹕ !!! FAILED BINDER TRANSACTION !!! Error.
    

    活动A列表视图

    enter image description here 活动B

         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();
                }
            }
    

    员工福利.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();
            }
        }
    ?>
    
    1 回复  |  直到 9 年前
        1
  •  2
  •   ρяσѕρєя K    9 年前

    Parcel 用于使用发送数据 Intent .如此处所示:

    TransactionTooLargeException:

    如果参数或返回值太大,无法放入 事务缓冲区,则调用将失败 将引发TransactionTooLargeException。

    Binder事务缓冲区的固定大小有限,目前为1Mb。。。

    所以如果我们发送 byte 任何大型图像的阵列都会导致 TransactionTooLargeException .

    要在两个应用程序组件之间发送图像,请使用图像URI、图像路径、id…,而不是发送位图或字节数组。

    在您的情况下,请按以下方式执行:

    1. 邮寄 selectedImage 进入的URI onActivityResult 使用活动B到A的意图:

    更改:

       returnIntent.putExtra("photo", bytes);
    

    收件人:

       returnIntent.putExtra("img_uri", selectedImage.toString());
    

    2. 收到 img_uri 作为活动A中的字符串,然后将其解析为URI。在里面 onActivityResult(活动结果) 活动A的方法:

    更改:

    byte[] bytes = data.getByteArrayExtra("photo");
    

    收件人:

    Uri imgURI = Uri.parse(data.getStringExtra("img_uri"));
    

    3. 改变 addNewItem 方法URI的第二个参数 Bitmap 并通过 imgURI :

    obj.addNewItem(ReceiveType, ReceiveAmount, imgURI, ReceiveDescription);
    

    4. 在ListView适配器中使用 setImageURI 为ImageView设置图像:

    imageView.setImageURI(imgUri);