简体   繁体   中英

How to set filename to textview in android

Hi in the below code I am using one button named as choose file. If users click on choose file button showing three options like take a photo, gallery, cancel. Suppose click on take a photo open a camera and taking a photo and then want to set the image name to my textview.

the same feature wants to applicable to the gallery also.

Example: If I am taking a photo from camera image name abc.jpeg Gallery also image name

Can anyone help me?

public class OpportunityCreateFragment extends Fragment {
  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the borderdashboard for this fragment
        View rootView = inflater.inflate(R.layout.opportunity_form, container, false);
    Textview no_file_pan=rootview.findViewById(R.id.no_file_pan);
    pan_card.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    selectImage();
                                                }
                                            });
    
    
     private void selectImage() {
            final CharSequence[] items = {"Take Photo", "Choose from Gallery",
                    "Cancel"};
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getContext());
            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if (items[item].equals("Take Photo")) {
                        requestStoragePermission(true);
                    } else if (items[item].equals("Choose from Gallery")) {
                       requestStoragePermission(false);
                    } else if (items[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }
    
        /**
         * Capture image from camera
         */
        private void dispatchTakePictureIntent() {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                } catch (IOException ex) {
                    ex.printStackTrace();
                    // Error occurred while creating the File
                }
                if (photoFile != null) {
                    Uri photoURI = GenericFileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", photoFile);
    
                    mPhotoFile = photoFile;
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                    startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
    
                }
            }
        }
    
    
        /**
         * Select image fro gallery
         */
        private void dispatchGalleryIntent() {
            Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            pickPhoto.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivityForResult(pickPhoto, REQUEST_GALLERY_PHOTO);
        }
    
    
       @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == REQUEST_TAKE_PHOTO) {
            try {
                mPhotoFile = mCompressor.compressToFile(mPhotoFile);
                no_file_pan.setText(mPhotoFile.getAbsolutePath().substring(mPhotoFile.getAbsolutePath().lastIndexOf("/")+1));
            } catch (IOException e) {
                e.printStackTrace();
            }
           // Glide.with(getActivity()).load(mPhotoFile).apply(new RequestOptions().centerCrop().circleCrop().placeholder(R.drawable.profile_pic_place_holder)).into(profile);

        } else if (requestCode == REQUEST_GALLERY_PHOTO) {
            Uri selectedImage = data.getData();
            try {
                mPhotoFile = mCompressor.compressToFile(new File(getRealPathFromUri(selectedImage)));
                no_file_pan.setText(mPhotoFile.getAbsolutePath().substring(mPhotoFile.getAbsolutePath().lastIndexOf("/")+1));
            } catch (IOException e) {
                e.printStackTrace();
            }
            //Glide.with(getApplicationContext()).load(mPhotoFile).apply(new RequestOptions().centerCrop().circleCrop().placeholder(R.drawable.profile_pic_place_holder)).into(profile);

        }
    }
}
    
        /**
         * Requesting multiple permissions (storage and camera) at once
         * This uses multiple permission model from dexter
         * On permanent denial opens settings dialog
         */
        private void requestStoragePermission(final boolean isCamera) {
            Dexter.withActivity((Activity) getContext()).withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                    .withListener(new MultiplePermissionsListener() {
                        @Override
                        public void onPermissionsChecked(MultiplePermissionsReport report) {
                            // check if all permissions are granted
                            if (report.areAllPermissionsGranted()) {
                                if (isCamera) {
                                    dispatchTakePictureIntent();
                                } else {
                                    dispatchGalleryIntent();
                                }
                            }
                            // check for permanent denial of any permission
                            if (report.isAnyPermissionPermanentlyDenied()) {
                                // show alert dialog navigating to Settings
                                showSettingsDialog();
                            }
                        }
    
                        @Override
                        public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                            token.continuePermissionRequest();
                        }
                    }).withErrorListener(new PermissionRequestErrorListener() {
                @Override
                public void onError(DexterError error) {
                    Toast.makeText(getActivity().getApplicationContext(), "Error occurred! ", Toast.LENGTH_SHORT).show();
                }
            })
                    .onSameThread()
                    .check();
        }
    
    
        /**
         * Showing Alert Dialog with Settings option
         * Navigates user to app settings
         * NOTE: Keep proper title and message depending on your app
         */
        private void showSettingsDialog() {
            android.app.AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setTitle("Need Permissions");
            builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
            builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                    openSettings();
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.show();
    
        }
    
        // navigating user to app settings
        private void openSettings() {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", getContext().getPackageName(), null);
            intent.setData(uri);
            startActivityForResult(intent, 101);
        }
    
        /**
         * Create file with current timestamp name
         *
         * @return
         * @throws IOException
         */
        private File createImageFile() throws IOException {
            // Create an image file name
            String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String mFileName = "PAN"+"_";
            File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            File mFile = File.createTempFile(mFileName, ".jpg", storageDir);
            return mFile;
        }
    
        /**
         * Get real file path from URI
         *
         * @param contentUri
         * @return
         */
        public String getRealPathFromUri(Uri contentUri) {
            Cursor cursor = null;
            try {
                String[] proj = {MediaStore.Images.Media.DATA};
                cursor = getContext().getContentResolver().query(contentUri, proj, null, null, null);
                assert cursor != null;
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }

return rootView;

    }

Use this method:

public String getFileName(File file) {
    if (file == null) return "";
    String fileName = "";
    String path = file.getAbsolutePath();
    int cut = path.lastIndexOf('/');
    if (cut != -1) {
        fileName = path.substring(cut + 1);
    }
    return fileName;
}

And call like this:

no_file_pan.setText(getFileName(mPhotoFile));

Try this

no_file_pan.setText(mPhotoFile.getAbsolutePath().substring(mPhotoFile.getAbsolutePath().lastIndexOf("/")+1));

Use this helpful library to pick image from gallery and take picture from camera https://github.com/esafirm/android-image-picker

Note :-

Remove this no_file_pan.setText(mPhotoFile.getName()); from dispatchTakePictureIntent() method like this

/**
     * Capture image from camera
     */
    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                ex.printStackTrace();
                // Error occurred while creating the File
            }
            if (photoFile != null) {
                Uri photoURI = GenericFileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", photoFile);

                mPhotoFile = photoFile;
               // no_file_pan.setText(mPhotoFile.getName()); //remove or comment this line because file has not been created yet, better to set text in onActivity result
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);

            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM