Android - Convert file path to uri (not working) - java

i want to convert a file path to a uri. but i get errors saying it can't resolve the uri. The image come from saving an image from a camera intent. the image is saved to this directory: getFilesDir(); which is in the app.
in my cursor adapter:
String imgPath = cursor.getString(cursor.getColumnIndexOrThrow( InventoryContract.InventoryEntry.COLUMN_PRODUCT_IMG_PATH ));
String productName = cursor.getString(cursor.getColumnIndexOrThrow( InventoryContract.InventoryEntry.COLUMN_PRODUCT_NAME ));
int productStock = cursor.getInt(cursor.getColumnIndexOrThrow( InventoryContract.InventoryEntry.COLUMN_PRODUCT_STOCK ));
Uri uri = ContentUris.withAppendedId(InventoryContract.InventoryEntry.CONTENT_URI,
cursor.getLong(cursor.getColumnIndexOrThrow( InventoryContract.InventoryEntry.COLUMN_PRODUCT_ID )));
File imgFile = new File(imgPath);
Uri imgURI = Uri.fromFile(imgFile);
if(imgFile.exists()) {
Log.v("image file" , String.valueOf(imgFile));
//Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
productImage.setImageURI(imgURI);
Log.v("Image does exist", "file | " + String.valueOf(imgURI));
}
else {
Log.v("bitmap --- ", "Could not find file | " + imgPath);
}
one of the error lines:
W/ImageView: resolveUri failed on bad bitmap uri: file:///data/user/0/com.example.android.inventoryapp/files/JPEG_20170710_094130_1552703275.jpg

Try to use this below code
Uri uri = Uri.fromFile(new File(filepath));

thanks everyone for the help. I found a solution. The filepath was good but it was an empty file, i think. I had to write to it like this:
private File createImageFile(Bitmap image) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File directory = this.getFilesDir();
// Save Bitmap
this.photo = new File(directory, imageFileName + ".jpg");
this.photo.createNewFile();
// Write to/Compress the Bitmap from the camera intent to the file
FileOutputStream fos = new FileOutputStream(this.photo);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
// path to file
this.imgPath = this.photo.getAbsolutePath();
return this.photo;
}

Related

E/PDFView: load pdf error. java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)

DETAILS : My application creates a pdf using data previously entered. The PDF is created in the application itself using :
//PDF GENERATOR
implementation 'com.itextpdf:itext7-core:7.1.3'
implementation 'com.itextpdf:itextg:5.5.10'
I view that PDF in the same Activity using :
//PDF VIEW
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
The code for that is as follows :
private void createPdf() throws FileNotFoundException {
File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Zomato/Receipts");
file = new File(folder.getAbsolutePath(), "Reciept.pdf");
pdfView.fromFile(file).load();
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
OutputStream outputStream = new FileOutputStream(file);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDocument = new PdfDocument(writer);
pdfDocument.setDefaultPageSize(PageSize.A4.rotate());
Document document = new Document(pdfDocument);
document.setMargins(15, 15, 15, 15);
float[] columnWidth = {110, 550, 140};
Table table1 = new Table(columnWidth);
//Table1------- 01
table1.addCell(new Cell().add(new Paragraph("Hello Welcome")).setVerticalAlignment(VerticalAlignment.MIDDLE));
table1.addCell(new Cell().add(new Paragraph("This is the PDF Data").setBold().setFontSize(14f)
.setTextAlignment(TextAlignment.CENTER)));
table1.addCell(new Cell().add(new Paragraph("Address : " + Common.currentCompany.getAddress()).setBold().setFontSize(8f).setTextAlignment(TextAlignment.CENTER)));
document.add(table1);
document.close();
textView.setText(R.string.downloaded_message);
}
This code works on phone Samsung M31 but it does not work on Redmi Y2 and Oppo. When I run this code on these phones I get the following error :
E/PDFView: load pdf error
java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
Please help. I have been stuck on this problem for a long time.
Thank you for the help. So here is the solution. I replaced this part of the code :
File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Zomato/Receipts");
file = new File(folder.getAbsolutePath(), "Reciept.pdf");
pdfView.fromFile(file).load();
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
OutputStream outputStream = new FileOutputStream(file);
With this :
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File folder = new File(root.getAbsolutePath() + "/" + DOCUMENTS);
Log.e("Tag", folder.getAbsolutePath());
if (!folder.exists()) {
folder.mkdirs();
}
File file = new File(folder.getAbsolutePath() + "/" + epoch + ".pdf");
And I shifted the PDFView to the bottom below:
document.close();
pdfView.fromFile(file).load();

ImageIO.write() not saving file

The absolute file path seems to be forming correctly but the file is not being written.
Code:
var image = ImageIO.read(new ByteArrayInputStream(attachPageScreenshot()));
var saveDirectory = Paths.get("target", "screenshots").toAbsolutePath().toString();
var builder = new StringBuilder();
builder.append("\\").append(context.getDisplayName()).append(".png");
var filePath = saveDirectory.concat(builder.toString());
var saveFile = new File(filePath);
ImageIO.write(image, "png", saveFile);
Output:
java.io.FileNotFoundException: E:\workspace\java\selenium-junit5-starter\target\screenshots\Verify Total Interest Per Annum - Deposit = 30000, Term = 2 Years.png (The system cannot find the path specified)
Anything amiss?
I assumed Paths.get() automatically created the directory if it did not exist.
var dir = new File(saveDirectory);
if (!dir.exists()) {
dir.mkdirs();
}
ImageIO.write(image, "png", saveFile);

Taking Screenshot of Layout Android CardView

I am trying to capture one of my layout but getting black border in screenshot like below. How can I remove it ?
My code for taking screenshot is like below
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1= findViewById(R.id.quoteViewPager);
v1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
Thanks
Actually, I didn't get your code,
View v1= findViewById(R.id.quoteViewPager);
v1.getRootView();
it should be :
v1 = v1.getRootView();
Hope it will help you :)

Saving images in app Folder?

I am making a chat application in which user also has the option to send pictures. I want to save the images to the application folder so I can access those images to fill the chat window up with previous messages with pictures and text. So my question is how can I add an image to the application folder?
Thanks
first you have to create your app name folder into sd card then you have to write your file/image into it
String SDCardRoot = Environment.getExternalStorageDirectory().toString();
String filename = "fileName" + ".jpg";
File myDir = new File(SDCardRoot + "/AppName");
myDir.mkdirs();
File file = new File(myDir, filename);
FileOutputStream fileOutput = new FileOutputStream(file);
//write the file into the sdcard folder specify your buffer , bufferLength
fileOutput.write(buffer, 0, bufferLength);
fileOutput.close();
then only you can access the files from app folder
File imgFile;
String path = Environment.getExternalStorageDirectory() + "/AppName/" + ".jpg";
imgFile = new File(path);
if (imgFile.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(bitmap);
}

Android:save captured image format from JPEG to PNG in internal storage directory

In Eclipse,i have Captured Image from emulator and it save the format as JPEG.But i want to save the image format as PNG. How can i convert image format from JPEG to PNG.
Here I am using this code to save the image in directory.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "Picture_" + date + ".PNG";
// String photoFile = "Picture_" + date + ".JPEG";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast.makeText(context, "New Image saved:" + photoFile,
Toast.LENGTH_LONG).show();
} catch (Exception error) {
//Log.d(IntersaActivity.DEBUG_TAG, "File" + filename + "not saved: "+ error.getMessage());
Toast.makeText(context, "Image could not be saved.",
Toast.LENGTH_LONG).show();
}
Thanks in Advance.
Here the code for creating image file using Bitmap class
Edit
you need to first open your existing image file into this bmp object and in file object give another name for save.
Bitmap bmp = BitmapFactory.decodeFile(pathName);// here you need to pass your existing file path
File image = new File(your_sdcard_file_path);
FileOutputStream outStream;
try {
image.createFile(); // need to create file as empty first if it was exist already then change the name
outStream = new FileOutputStream(image);
// here you need to pass the format as I have passed as PNG so you can create the file with specific format
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Categories

Resources