简体   繁体   English

在另一个活动中将从图库中选择或从相机捕获的图像添加到 gridview

[英]Add images selected from gallery or captured from camera into a gridview in another activity

I have an activity with a capture button this catpture button when clicked,it prompts the user with an alert dialog asking to choose between gallery and camera after making the decision and capturing the image or choosing it the app currently save the image in an image view,now how can i save the image s in a gridview in another activity rather than the imageview,and as much as possible avoiding using sqlite?!我有一个带有捕获按钮的活动,单击此捕获按钮时,它会提示用户一个警报对话框,要求在做出决定并捕获图像后在图库和相机之间进行选择,或者选择它应用程序当前将图像保存在图像视图中,现在我如何在另一个活动中而不是 imageview 中将图像保存在gridview中,并尽可能避免使用 sqlite?!

mainactivity.java: mainactivity.java:

public static final int CAMERA_PERM_CODE = 101;
    public static final int CAMERA_REQUEST_CODE = 102;
    public static final int GALLERY_REQUEST_CODE = 105;

    DatabaseHelper mDatabaseHelper;
    Cursor data;
    Cursor price;
    ArrayList<myDataClass> listData;
    ArrayAdapter adapter;
    ArrayList arrayList;
    public SwipeMenuListView mListview;
    CustomAdapter custom;
    private TextView total;
    ImageView camera;
    ImageView display1;
    String currentPhotoPath;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listitemsbought);
        getSupportActionBar().hide();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mListview = (SwipeMenuListView) findViewById(R.id.list_items_bought);
        mDatabaseHelper = new DatabaseHelper(this);
        data  = mDatabaseHelper.getDataOfTable();
        total = (TextView) findViewById(R.id.totalpriceofitems);
        listData = new ArrayList<myDataClass>();
        camera = (ImageView) findViewById(R.id.imagetopic);
        display1 = (ImageView) findViewById(R.id.displayimage);

        display1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Listitemsbought.this,savedPics.class);
                overridePendingTransition(R.anim.slide_in,R.anim.slide_out);
                startActivity(intent);
            }
        });

        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                askCameraPermission();
            }
        });
       // adapter = new ArrayAdapter<String>(this, R.layout.list_boughts,R.id.Name,listData);

        populateListView();

        final SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {

                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0,
                        0, 0)));
                // set item width
                deleteItem.setWidth((250));
                // set a icon
                deleteItem.setIcon(R.drawable.sym_keyboard_delete_holo_dark);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };

// set creator
        mListview.setMenuCreator(creator);




        // Left
        mListview.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);


    }

    private void askCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.CAMERA}, CAMERA_PERM_CODE);
        }else {
            alert();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == CAMERA_PERM_CODE){
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                alert();
            }
        }else {
            Toast.makeText(this,"Camera Permission is required to use camera.",Toast.LENGTH_SHORT).show();
        }
    }

    private void alert() {
        new AlertDialog.Builder(Listitemsbought.this)
                .setTitle(null)
                .setMessage("Do you want to open gallery or take a new photo")

                // Specifying a listener allows you to take an action before dismissing the dialog.
                // The dialog is automatically dismissed when a dialog button is clicked.
                .setPositiveButton("Open Camera", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dispatchTakePictureIntent();
                    }
                })
                // A null listener allows the button to dismiss the dialog and take no further action.
                .setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent gallery = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(gallery, GALLERY_REQUEST_CODE);
                    }
                })
                .setIcon(android.R.drawable.ic_menu_camera)
                .show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode == CAMERA_REQUEST_CODE){
            if(resultCode == Activity.RESULT_OK){
                File f = new File(currentPhotoPath);
                display1.setImageURI(Uri.fromFile(f));
                Log.d("tag", "ABsolute Url of Image is " + Uri.fromFile(f));

                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(f);
                mediaScanIntent.setData(contentUri);
                this.sendBroadcast(mediaScanIntent);




            }

        }

        if(requestCode == GALLERY_REQUEST_CODE){
            if(resultCode == Activity.RESULT_OK){
                Uri contentUri = data.getData();
                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                String imageFileName = "JPEG_" + timeStamp +"."+getFileExt(contentUri);
                Log.d("tag", "onActivityResult: Gallery Image Uri:  " +  imageFileName);
                display1.setImageURI(contentUri);




            }

        }
    }

    private String getFileExt(Uri contentUri) {
        ContentResolver c = getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        return mime.getExtensionFromMimeType(c.getType(contentUri));
    }


    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
//        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }


    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {

            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.medicnes.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
            }
        }
    }

    private void populateListView(){

        while (data.moveToNext()){
            listData.add(new myDataClass(data.getString(data.getColumnIndex("Name")),data.getString(data.getColumnIndex("Amount")),data.getString(data.getColumnIndex("Price"))));
        }

            total.setText(mDatabaseHelper.getPriceSum());


        custom = new CustomAdapter(listData, this);

        mListview.setAdapter(custom);

        //custom.notifyDataSetChanged();


    }
    public class CustomAdapter extends BaseAdapter
    {
        private Context context;
        private List<String> strings;

        public class ViewHolder {

            TextView textName;
            TextView textAmount;
            TextView textPrice;

        }

        public List<myDataClass> parkingList;

        private CustomAdapter(List<myDataClass> apps, Context context) {
            this.parkingList = apps;
            this.context = context;
            arrayList = new ArrayList<myDataClass>();
            arrayList.addAll(parkingList);
        }

        @Override
        public int getCount() {
            return parkingList.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }



        @Override
        public View getView(int position, View convertView, final ViewGroup parent)
        {
            View rowView = convertView;
            ViewHolder viewHolder = null;
            if (rowView == null) {
                LayoutInflater inflater = getLayoutInflater();
                rowView = inflater.inflate(R.layout.list_boughts, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.textName = rowView.findViewById(R.id.Name);
                viewHolder.textAmount = rowView.findViewById(R.id.sdadprice);
                viewHolder.textPrice = rowView.findViewById(R.id.dfsdfad);
                rowView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            // here setting up names and images
            viewHolder.textName.setText(parkingList.get(position).getProdaname() + "");
            viewHolder.textAmount.setText(parkingList.get(position).getAmount());
            viewHolder.textPrice.setText(parkingList.get(position).getPrice());
            System.out.println(parkingList.get(position).getPrice());

            mListview.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                    // delete

                    mDatabaseHelper.delete(parkingList.get(position).getProdaname());
                    System.out.println(parkingList.get(position).getProdaname());
                    listData.remove(index);
                    custom.notifyDataSetChanged();
                    populateListView();
                    // false : close the menu; true : not close the menu
                    return false;
                }
            });

            return rowView;
        }
    }

Create a Offline database in scoped storage but this database will be deleted when user uninstall the app.在范围存储中创建一个离线数据库,但当用户卸载应用程序时,该数据库将被删除。

File mainfolder = getDir("datafolder", Context.MODE_PRIVATE);
Bitmap bitmap = BitmapFactory.decode(currentphotopath);
String name = new SimpleDateFormate("dd_mm_yyyy_hhss") + ".jpg"; // this or generate new file name each time user uploads.
File file = new File(mainfolder, name);
FileOutputStreme fout = new FIleOutputStreme(file);
bitmap.compress(jpg, 100, fout);
fout.close();

//listing all the files in mainfolder and set to gridview
File[] files = mainfolder.listFiles();
customView cview = new customView(this, files);
gridview.setAdapter(cview);

//adapter customview class //适配器customview class

public class customview extends ArrayAdapter{
private Files[] files;
.
.`
.

public customview (Activity activity, Files[] fls){
files = fls;
}

@Override
public View getView(int position, View convertView, final ViewGroup parent){

Bitmap bitmap = BitmapFactory.decode(files[position].getAbsolutePath());
imageview.setImageBitmap(bitmap);
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在pdf报告中添加从相机或图库捕获的图像? - How to add captured images from camera or gallery in pdf report? 如何将捕获的图像从自定义相机传递到另一个活动? - How to pass a captured image from custom camera to another activity? 如何在图像视图的另一个活动中加载从相机捕获的图片? - how to load a picture captured from camera in another activity on image view? 将捕获的图像从Camera2 Api传递到另一个活动 - Passing captured Image from Camera2 Api to another Activity 如何将相机拍摄的图像存储在图库中? - How to store image captured from camera in gallery? 如何将从相机或画廊获得的图像传递到另一个活动 - How to pass image gotten from camera or gallery to another activity 从相机或画廊拍摄图像并在活动中显示 - Take image from camera or gallery and show in activity 如何将图库中的图像动态添加到我的 gridview? 我可以 go 到画廊,但图像没有被添加到我的 gridview - How can I add images from the gallery to my gridview dynamically ? I can go to the gallery but images aren't getting added to my gridview 从图库中选择图像,然后在另一个活动中显示 - Select a image from the gallery and show it in another Activity 从图库中选择一个图像并发送到另一个活动 - Choose a Image from Gallery and send to another Activity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM