Добавить изображения, выбранные из галереи или захваченные с камеры, в виде сетки в другой деятельности - PullRequest
1 голос
/ 01 мая 2020

У меня есть действие с кнопкой захвата, при нажатии на эту кнопку захвата пользователю предлагается диалоговое окно с предупреждением о необходимости выбора между галереей и камерой после принятия решения и захвата изображения или выбора приложения, в настоящее время приложение сохраняет изображение в представление изображения, теперь как я могу сохранить изображение s в виде сетки в другом действии, а не в просмотре изображения, и, насколько это возможно, избегать использования sqlite?!

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

1 Ответ

0 голосов
/ 01 мая 2020

Создайте автономную базу данных в хранилище с областью действия, но эта база данных будет удалена при удалении пользователем приложения.

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

// класс настраиваемого адаптера

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);
}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...