当我从另一个活动中删除元素时,如何清除一个活动的arraylist?

时间:2017-01-27 07:03:00

标签: java android android-intent arraylist bundle

我有两个活动,我在第一个活动中有2个arraylist,并且我在第二个活动中存储了另一个arraylist的数组列表。当我删除第二个活动的arraylist的元素时,我想从第一个活动的相同索引elememt arraylist也将被删除。我已尝试用户给出的以下答案,我正面临另一个问题。

更新了问题: 当我删除视频时,它应该只从数组中删除该视频的缩略图,但是从数组中删除所有缩略图。

活动代码A

 private HandlerThread mBackgroundHandlerThread;
private Handler mBackgroundHandler;
private String mCameraId;
private Size mPreviewSize;
private Size mVideoSize;
private MediaRecorder mMediaRecorder;
private Chronometer mChronometer;
private ImageView thumb;
//private String V1, V2, V3, V4, V5;
//    private Map<String, String> mapA = new HashMap<>();
// private ImageView[] IMGS = {mImageView1, mImageView2, mImageView3, mImageView4, mImageView5};
private int mTotalRotation;
private CaptureRequest.Builder mCaptureRequestBuilder;
public static int count;
public static int max = 5;
private ImageButton mRecordImageButton;
private boolean mIsRecording = false;
public static File mVideoFolder;
private static File mRawVideoFolder;
public static String mVideoFileName;

//Test
private List<Bitmap> bitMapsAvailable = new ArrayList<>();
private List<String> bitMapsFilePath = new ArrayList<>();
private int bitMapIndex;
CameraCaptureSession storedSession;
private ArrayAdapter bitMapAdapter;
private ArrayAdapter bitMapFileAdapter;
private static SparseIntArray ORIENTATIONS = new SparseIntArray();
public int index;
static {
    ORIENTATIONS.append(Surface.ROTATION_0, 0);
    ORIENTATIONS.append(Surface.ROTATION_90, 90);
    ORIENTATIONS.append(Surface.ROTATION_180, 180);
    ORIENTATIONS.append(Surface.ROTATION_270, 270);

}

private static class CompareSizeByArea implements Comparator<Size> {

    @Override
    public int compare(Size lhs, Size rhs) {
        return Long.signum((long) lhs.getWidth() * lhs.getHeight() / (long) rhs.getWidth() * rhs.getHeight());
    }
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    createVideoFolder();

    mMediaRecorder = new MediaRecorder();
    mChronometer = (Chronometer) findViewById(R.id.chronometer);
    mTextureView = (TextureView) findViewById(R.id.textureView);

    mRecordImageButton = (ImageButton) findViewById(R.id.videoButton);
    mRecordImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mIsRecording) {
                mChronometer.stop();
                mChronometer.setVisibility(View.INVISIBLE);
                mIsRecording = false;
                mRecordImageButton.setImageResource(R.mipmap.start_recording);
                //Toast.makeText(getApplicationContext(),"Started",Toast.LENGTH_SHORT).show();

                if(storedSession != null){
                    try {
                        storedSession.stopRepeating();
                        storedSession.abortCaptures();
                    }catch (CameraAccessException e){
                        throw new RuntimeException(e.getMessage());
                    }
                }
                mMediaRecorder.stop();
                mMediaRecorder.reset();
                startPreview();
                //Create bitmap with current video file path
                Bitmap bitMap = ThumbnailUtils.createVideoThumbnail(mVideoFileName, MediaStore.Video.Thumbnails.MICRO_KIND);
                //Add bitmap to array list
                bitMapsAvailable.add(bitMap);
                bitMapsFilePath.add(mVideoFileName);
                // Shows  thumbnails
                showThumbnails();
            } else {
                checkWriteStoragePermission();
            }
        }

    });
}

private void showThumbnails() {

    LinearLayout layout = (LinearLayout) findViewById(R.id.thumbnails);

    bitMapAdapter = new ArrayAdapter(this, R.layout.activity_main, bitMapsAvailable);
    bitMapFileAdapter = new ArrayAdapter(this, R.layout.activity_main, bitMapsFilePath);


    bitMapIndex = 0;
    if (layout.getChildCount() > 0) {
        layout.removeAllViews();
    }
    for (Bitmap eachBitMap : bitMapsAvailable) {

        bitMapIndex++;
        ImageView thumb = new ImageView(this);
        thumb.setId(new Integer(bitMapIndex+ 17));
        thumb.setLayoutParams(new android.view.ViewGroup.LayoutParams(100, 80));
        thumb.setImageBitmap(eachBitMap);
        // Adds the view to the layout
        thumb.setOnClickListener(previewThumb(thumb));


        layout.addView(thumb);
    }
}
View.OnClickListener previewThumb(final ImageView imageview) {

    return new View.OnClickListener() {
        public void onClick(View arg0) {

            index = imageview.getId()-18;
            imageview.setBackgroundColor(0xff999999);
            // Start NewActivity.class
            Intent myIntent = new Intent(MainActivity.this,
                    VideoViewActivity.class);
            //                   VideoView mVideoView = (VideoView) findViewById(R.id.VideoView);
            Bundle bundle = new Bundle();

            bundle.putStringArrayList("bitMapsAvailable", new ArrayList(bitMapsAvailable));
            bundle.putStringArrayList("bitMapsFilePath", new ArrayList(bitMapsFilePath));
            //Add your data to bundle
            bundle.putInt("urlIndex", index);
            myIntent.putExtras(bundle);
            bitMapAdapter.notifyDataSetChanged();
            bitMapFileAdapter.notifyDataSetChanged();

            //  startActivity(myIntent);
            startActivityForResult(myIntent, 111);

        }
    };
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 111) {
            int indexToBeDeleted = data.getIntExtra("indexToDeleted", -1);
            bitMapsFilePath.remove(indexToBeDeleted);
            bitMapsAvailable.remove(indexToBeDeleted);

        }
    }

活动代码B

   public VideoView videoview;
    ImageButton imgButton;
    ImageButton saveButton;
    List<String> bitMapsAvailable = new ArrayList<>();
    List<String> bitMapsFilePath = new ArrayList<>();
    int indexClicked;
    String videoURL;
    //String videoURL = getIntent().getExtras().getString("url");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.videoview_main);
        videoview = (VideoView) findViewById(R.id.VideoView);
        //Toast.makeText(this, videoURL, Toast.LENGTH_SHORT).show();

        Bundle bundle = getIntent().getExtras();
        bitMapsAvailable = bundle.getStringArrayList("bitMapsAvailable");
        bitMapsFilePath = bundle.getStringArrayList("bitMapsFilePath");
        indexClicked = bundle.getInt("urlIndex");
        videoURL = bitMapsFilePath.get(indexClicked);


        try {
            // Start the MediaController
            MediaController mediacontroller = new MediaController(
                    VideoViewActivity.this);
            mediacontroller.setAnchorView(videoview);
            // Get the URL from String VideoURL
            Uri video = Uri.parse(videoURL);
            videoview.setMediaController(mediacontroller);
            videoview.setVideoURI(video);

        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }

        videoview.requestFocus();
        videoview.setOnPreparedListener(new OnPreparedListener() {
            // Close the progress bar and play the video
            public void onPrepared(MediaPlayer mp) {

                videoview.start();
            }
        });


        imgButton = (ImageButton) findViewById(R.id.deleteVideo);
        imgButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (deleteVideoFile(indexClicked)) {
                    AlertDialog.Builder deletebuilder = new AlertDialog.Builder(VideoViewActivity.this);// use you activity name
                    deletebuilder.setMessage("Are you sure you want to delete? ");
                    deletebuilder.setPositiveButton("Yes",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface deletedialog, int delwhich) {
                                    bitMapsFilePath.remove(indexClicked);
                                    bitMapsAvailable.remove(indexClicked);
                                    Toast.makeText(VideoViewActivity.this, "Selected video file is deleted successfully.", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(VideoViewActivity.this,MainActivity.class);
                                    intent.putExtra("indexToBeDeleted", indexClicked);
//                                    intent.getIntExtra()
                                    setResult(RESULT_OK, intent);
                                    startActivity(intent);
                                    finish();
                                }
                            });
                    deletebuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface deletedialog, int delwhich) {
                            // Toast.makeText(VideoViewActivity.this, "Abort by user", Toast.LENGTH_SHORT).show();
                        }
                    });
                    AlertDialog deletedialog = deletebuilder.create();
                    deletedialog.show();
                } else {
                    Toast.makeText(VideoViewActivity.this, "Not deleted", Toast.LENGTH_SHORT).show();
                }
            }
        });
        saveButton = (ImageButton) findViewById(R.id.saveVideo);
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // final int index = checkBox.getId()-31;
                AlertDialog.Builder builderSave = new AlertDialog.Builder(VideoViewActivity.this);// use you activity name
                builderSave.setMessage("Save the selected file and delete the rest?")
                        .setPositiveButton("Yes",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogSave, int whichSave) {
                                        String src = bitMapsFilePath.get(indexClicked);
                                        String destination = mVideoFolder + "/" + new File(src).getName();
                                        File srcFile = new File(src);
                                        srcFile.renameTo(new File(destination));
                                        Toast.makeText(VideoViewActivity.this, "Saved in " + destination, Toast.LENGTH_SHORT).show();
                                        bitMapsAvailable.clear();
                                        for (String filePath : bitMapsFilePath) {
                                            File file = new File(filePath);
                                            file.delete();
                                        }
                                        bitMapsFilePath.clear();
                                        Toast.makeText(VideoViewActivity.this, "Temporary videos are deleted successfully", Toast.LENGTH_SHORT).show();
                                        finish();
                                    }
                                })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogSave, int whichSave) {
                                Toast.makeText(VideoViewActivity.this, "Not deleted", Toast.LENGTH_SHORT).show();
                            }
                        });
                AlertDialog dialogSave = builderSave.create();
                dialogSave.show();
                //Toast.makeText(VideoViewActivity.this, "Not deleted", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private boolean deleteVideoFile(final int index) {

        try {
            File file = new File(videoURL);
            return file.delete();
        } catch (Exception e) {
            Toast.makeText(VideoViewActivity.this, "Not deleted", Toast.LENGTH_SHORT).show();
            Log.e("Error", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }

1 个答案:

答案 0 :(得分:1)

尝试以下解决方案!

活动A:

View.OnClickListener previewThumb ( final ImageView imageview){

        return new View.OnClickListener() {
            public void onClick(View arg0) {

                int index = imageview.getId() - 18;
                imageview.setBackgroundColor(0xff999999);
                // Start NewActivity.class
                Intent myIntent = new Intent(MainActivity.this,
                        VideoViewActivity.class);

                Bundle bundle = new Bundle();

                bundle.putStringArrayList("bitMapsAvailable", new ArrayList(bitMapsAvailable));
                bundle.putStringArrayList("bitMapsFilePath", new ArrayList(bitMapsFilePath));
                //Add your data to bundle
                bundle.putInt("urlIndex", index);
                myIntent.putExtras(bundle);
                bitMapAdapter.notifyDataSetChanged();
                bitMapFileAdapter.notifyDataSetChanged();

                //Change this line
                startActivityForResult(myIntent, 111);


            }
        };
    }


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 111) {
            int indexToBeDeleted = data.getIntExtra("indexToBeDeleted");
            bitMapsFilePath.remove(indexToBeDeleted);
            bitMapsAvailable.remove(indexToBeDeleted);
        }
    }
}

活动B:

imgButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (deleteVideoFile(indexClicked)) {
                AlertDialog.Builder deletebuilder = new AlertDialog.Builder(VideoViewActivity.this);// use you activity name
                deletebuilder.setMessage("Are you sure you want to delete? ")
                        .setPositiveButton("Yes",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface deletedialog, int delwhich) {
                                        bitMapsFilePath.remove(indexClicked);
                                        bitMapsAvailable.remove(indexClicked);
                                        Toast.makeText(VideoViewActivity.this, "Selected video file is deleted successfully.", Toast.LENGTH_SHORT).show();

                                        //Change here too-----------
                                        Intent intent = new Intent();
                                        intent.putExtra("indexToBeDeleted",indexClicked);
                                        setResult(RESULT_OK,intent);
                                        finish();
                                    }
                                })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface deletedialog, int delwhich) {
                                // Toast.makeText(VideoViewActivity.this, "Abort by user", Toast.LENGTH_SHORT).show();
                            }
                        });
                AlertDialog deletedialog = deletebuilder.create();
                deletedialog.show();
            } else {
                Toast.makeText(VideoViewActivity.this, "Not deleted", Toast.LENGTH_SHORT).show();
            }
        }
    });

希望这对你有用!!