如何在适配器列表中的3个不同的imageview中设置图像并上传

时间:2019-02-02 08:53:04

标签: android android-recyclerview image-uploading android-adapter

我面对,其中我不得不图像集成问题3个不同的imageview,并上传,因为我必须表明imageview在适配器列表我不能呼叫的 {{ 1}} 在适配器类中,由于该原因我无法获得onActivityRessult

的ID

试图在活动类中调用imageview,但是onActivityResult的ID来自适配器列表

screenshot

当我单击“添加”按钮时,它会打开一个对话框以从相机或图库中选择图像,然后应该可以在imageviews中设置

编辑后: UploadAdapter.java

imageviews

编辑后:UploadActivity

public class UploadAdapter extends RecyclerView.Adapter<UploadAdapter.UploadViewHolder> {

    private Callback mCallback;
    private Context ctx;
    private List<UploadModelClass> uploadModelClassList;

    public interface Callback {
        void showPictureDialog();
        void uploadMultipart();
    }

    public UploadAdapter(Context ctx, List<UploadModelClass> uploadModelClassList,Callback callback) {
        this.ctx = ctx;
        this.uploadModelClassList = uploadModelClassList;
        this.mCallback = callback;
    }

    @NonNull
    @Override
    public UploadViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        LayoutInflater inflater=LayoutInflater.from(ctx);
        View view=inflater.inflate(R.layout.layout_upload_list,null);
        return new UploadViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull UploadViewHolder holder, final int position) {

        holder.txtv_item_code.setText(uploadModelClassList.get(position).getItem_code());
        holder.txtv_item_name.setText(uploadModelClassList.get(position).getItem_name());

        holder.txtv_item_choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mCallback.showPictureDialog();

            }
        });

        holder.txtv_item_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCallback.uploadMultipart();
            }
        });


        if(position %2 == 1)
        {
            holder.itemView.setBackgroundColor(Color.parseColor("#ffffff"));

        }
        else
        {
            holder.itemView.setBackgroundColor(Color.parseColor("#dddddd"));

        }

    }


    @Override
    public int getItemCount() {
        return uploadModelClassList.size();
    }

    public class UploadViewHolder extends RecyclerView.ViewHolder {
        ImageView imageviewUpload,imageviewUpload2;
        TextView txtv_item_code,txtv_item_name,txtv_item_choose,txtv_item_image;


        public UploadViewHolder(@NonNull View itemView) {
            super(itemView);

            txtv_item_code=itemView.findViewById(R.id.txtv_layoutUploadList_item_code);
            txtv_item_name=itemView.findViewById(R.id.txtv_layoutUploadList_name);
            txtv_item_choose=itemView.findViewById(R.id.txtv_layoutUploadList_choose);
            txtv_item_image=itemView.findViewById(R.id.txtv_layoutUploadList_image);
            imageviewUpload=itemView.findViewById(R.id.imageview_layoutUploadList1);
            imageviewUpload2=itemView.findViewById(R.id.imageview_layoutUploadList2);

        }
    }
}

layout_upload_list.xml

public class UploadActivity extends AppCompatActivity implements UploadAdapter.Callback {

    UploadAdapter uploadAdapter;
    RecyclerView recyclerView_upload;
    ArrayList<UploadModelClass> uploadModelClassArrayList;

    private int GALLERY = 1, CAMERA = 2,GALLERY2 = 3;
    Uri filePath;
    private static final String IMAGE_DIRECTORY = "/abcipl";

    ImageView imageView,imageView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        requestMultiplePermissions();

       // ProductAdapter productAdapter=new ProductAdapter();
        uploadModelClassArrayList=new ArrayList<>();
        recyclerView_upload = findViewById(R.id.recycler_view_upload_activity);


      /*  imageView=findViewById(R.id.testttt);
        imageView2=findViewById(R.id.testttt2);*/


        uploadModelClassArrayList.add(new UploadModelClass("123445","Bulb"));
        uploadModelClassArrayList.add(new UploadModelClass("123445","Bulb"));
        uploadModelClassArrayList.add(new UploadModelClass("123445","Bulb"));
        uploadModelClassArrayList.add(new UploadModelClass("123445","Bulb"));


        recyclerView_upload.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        uploadAdapter = new UploadAdapter(this, uploadModelClassArrayList,UploadActivity.this);
        recyclerView_upload.setAdapter(uploadAdapter);

    }

    private void  requestMultiplePermissions(){
        Dexter.withActivity(this)
                .withPermissions(
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        // check if all permissions are granted
                        if (report.areAllPermissionsGranted()) {
                            //Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
                        }

                        // check for permanent denial of any permission
                        if (report.isAnyPermissionPermanentlyDenied()) {
                            // show alert dialog navigating to Settings
                            //openSettingsDialog();
                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).
                withErrorListener(new PermissionRequestErrorListener() {
                    @Override
                    public void onError(DexterError error) {
                        Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
                    }
                })
                .onSameThread()
                .check();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        onBackPressed();
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == this.RESULT_CANCELED) {
            return;
        }
        if (requestCode == GALLERY) {
            if (data != null) {
                filePath = data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(UploadActivity.this.getContentResolver(), filePath);
                    String path = saveImage(bitmap);
                    Toast.makeText(UploadActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
                    //imageviewUpload.setImageBitmap(bitmap);


                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(UploadActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
                }
            }

        }

       else if (requestCode == GALLERY2) {
            if (data != null) {
                filePath = data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(UploadActivity.this.getContentResolver(), filePath);
                    String path = saveImage(bitmap);
                    Toast.makeText(UploadActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
                    //imageviewUpload.setImageBitmap(bitmap);



                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(UploadActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
                }
            }

        }


        else if (requestCode == CAMERA) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
           // imageviewUpload.setImageBitmap(thumbnail);
            //imageView.setImageBitmap(thumbnail);
            saveImage(thumbnail);
            Toast.makeText(UploadActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
        }
    }

    public String saveImage(Bitmap myBitmap) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File wallpaperDirectory = new File(
                Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
        // have the object build the directory structure, if needed.
        if (!wallpaperDirectory.exists()) {
            wallpaperDirectory.mkdirs();
        }

        try {
            File f = new File(wallpaperDirectory, Calendar.getInstance()
                    .getTimeInMillis() + ".jpg");
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            MediaScannerConnection.scanFile(UploadActivity.this,
                    new String[]{f.getPath()},
                    new String[]{"image/jpeg"}, null);
            fo.close();
            Log.d("TAG", "File Saved::---&gt;" + f.getAbsolutePath());

            return f.getAbsolutePath();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return "";
    }



    @Override
    public void showPictureDialog() {
        AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
        pictureDialog.setTitle("Select Action");
        String[] pictureDialogItems = {
                "Select photo from gallery",
                "Capture photo from camera" };
        pictureDialog.setItems(pictureDialogItems,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                choosePhotoFromGallery();
                                break;
                            case 1:
                                takePhotoFromCamera();
                                break;
                        }
                    }
                });
        pictureDialog.show();

    }

    /*
     * This is the method responsible for image upload
     * We need the full image path and the name for the image in this method
     * */
    @Override
    public void uploadMultipart() {
        //getting name for the image
        // String name = editTextImgName.getText().toString().trim();

        //getting the actual path of the image
        String path = getPath(filePath);

        //Uploading code
        try {
            String uploadId = UUID.randomUUID().toString();

            //Creating a multi part request
            new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
                    .addFileToUpload(path, "image") //Adding file
                    //.addParameter("name", name) //Adding text parameter to the request
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload

        } catch (Exception exc) {
            Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    //method to get the file path from uri
    public String getPath(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();

        cursor = getContentResolver().query(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        cursor.close();

        return path;
    }

    public void choosePhotoFromGallery() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(galleryIntent, GALLERY);
    }

    private void takePhotoFromCamera() {
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA);
    }
}

1 个答案:

答案 0 :(得分:0)

这是AdapterActivity通信的方式。

public class SomeActivity extends AppCompatActivity
        implements SomeAdapter.Callback {
    ArrayList<String> imagesUris1 = new ArrayList();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.layout_file);

        SomeAdapter adapter = new SomeAdpter(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //calling saveImage()
    }

    public String saveImage(Bitmap myBitmap) {
        try{
            //...getting file uri
            imageUris1.add(f.getAbsolutePath());
            adapter.setFirstImageUris(imageUris1);
            return f.getAbsolutePath(); //Ignored
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return "";
    }

    //..Other activity related stuff

    @Override
    void showImageDialog() {
      //Open gallary or camera from here
    }
}

public class SomeAdpter extends RecyclerView.Adapter<SomeAdapter.SomeHolder> {
  Callback callback;
  ArrayList<String> firstImageUris, secondImageUris, thirdImagesUris = new ArrayList();

  public SomeAdapter(Callback callback) {
    this.callback = callback;
    firstImageUris = new ArrayList();
    for(int i=0; i<uploadModelClassList.size(); i++) {
        firstImageUris.add("");
    }
  }
  //Adapter related methods, call callback.showImageDialog() in onBindViewHolder
  @Override
  public void onBindViewHolder(@NonNull UploadViewHolder holder, final int position) {
      //Use uri arraylist to show image in imageview.
      holder.imageviewUpload.setImageURI(firstImageUris.get(position));
  }

  public void setFirstImageUris(ArrayList<String> imagesUris) {
      this.firstImageUris = imageUris;
      notifyDataSetChanged();
  }
  //Similar methods to store 2nd and 3rd image uris.

  public interface Callback {
    void showImageDialog();
  }
}

您将忽略保存的图像的absoluteFilePath。做一个arraylist {在{1}}保存它,并把它传递给activity。活动不必知道adapter的ID,它只需要将数据传递给适配器即可。适配器应使用imageview更新自身。我添加了一些虚拟代码来帮助您处理第一张图片,您必须对第二张和第三张图片执行相同的操作。

您必须编写自己的处理图像索引和URI列表的逻辑。添加一些示例代码,以帮助你一点。

notifyDataSetChanged