Opening a downloaded file and copying it - java

I am trying to open a file I demand from my user to download so I can use it so I am trying to copy it to my internal storage.
I tried using this code:
Intent myIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
myIntent.setType("text/*");
myIntent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(myIntent, 100);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if(resultCode == Activity.RESULT_OK){
Uri result= data.getData();
Log.e("fag", result.getPath());
copyFile(result);
}
if (resultCode == Activity.RESULT_CANCELED) {
Log.e("", "canceled");
}
}
Intent a = new Intent(getApplicationContext(), MainActivity.class);
startActivity(a);
}
private void copyFile(Uri inputFile) {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(inputFile.getPath());
out = openFileOutput(NAME , MODE_PRIVATE);
byte[] buffer = new byte[1024];
while ( in.read(buffer) != -1) {
out.write(buffer);
}
in.close();
in = null;
out.close();
out = null;
} catch (FileNotFoundException fnfe1) {
Log.e("tag", fnfe1.getMessage());
fnfe1.printStackTrace();
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
But when I run this code, I got a File Not Found Exception. so I checked what URI I get from the intent and it isn't the path to the file but this path
/document/primary:Download/5643_05072018-13-48.csv
and I don't know how to use this URI.
I got a simmmilar resualt using the ACTION_GET_CONTENT intent.
So my question is can I use this code and the URI that I got to copy that file or I need to do it in an other way? and how in both cases?

in = new FileInputStream(inputFile.getPath());
Change to:
InputStream is = getContentResolver().openInputStream(inputFile);
And dont name that inputFile but uri.

Related

Is there a way I can access files from an Android app that is saved by another app?

I'm developing an Android app that need to read csv files saved by another app. However, I'm not sure how to access the csv files saved by another app. Is there anyone have some suggestions about this?
You can use Cloud Firestore.
Or if you want to read csv from storage:
private void loadCsvFromStorage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, PICK_CSV_REQUEST);
}
// When results returned
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_CSV_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null){
Uri uri = data.getData();
if(uri.getPath().endsWith(".csv")) {
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, Charset.forName("UTF-8"))
);
String line = "";
try {
reader.readLine();
while ((line = reader.readLine()) != null) {
String[] tokens = line.split(",");
//Read data
}
Toast.makeText(Activity.this, "Done!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
} catch (FileNotFoundException e) {
Toast.makeText(Activity.this, "Failed!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
else{
Toast.makeText(Activity.this, "Please select the .csv file!", Toast.LENGTH_SHORT).show();
}
}
}
Refer to the answer Reading CSV File In Android App

How to fix my "FileNotFoundException"(No such file or directory) error with Uri-Path in Android-Studio?

I am writing an App to save files (pictures) as a certain name given by a column from csv-file. The user have to choose the csv with the filebrowser first and then the file will be copyied to my Dir-Data directory.
Everything worsk fine but it seems like the Path i get form the File src Object doesn't work with the Operation.
I expect the error obviously here(2nd Code-Box)
And sry in advance if it is obvious/easy to avoid, it is my first Android-Project ever.
I already tryed to use different Copy Functions with different parameter types and also tryed other formats such as String given by uri.toString().
//CSV Opener
public void performFileSearch() {
// ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's file
// browser.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
// Filter to only show results that can be "opened"
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Filter to show only .csv using the image MIME data type.
// For all it would be "*/*".
intent.setType("text/comma-separated-values");
startActivityForResult(intent, READ_REQUEST_CODE);
}
//create paths
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK)
{
if (resultData != null) {
Uri path = resultData.getData();
stringUri = path.getPath();
File src = new File(stringUri);
File destination = new File(getFilesDir().getPath());
try {
copyDirectoryOneLocationToAnotherLocation(src,destination);
}
catch(IOException e) {
e.printStackTrace();
System.out.print("error in upload");
}
Toast.makeText(MainActivity.this, "Path: "+stringUri , Toast.LENGTH_SHORT).show();
}
}
}
//copy-operation from StackOverflow
public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
I want the choosen file to be copied in my data/data/... directory to be used later in the App.
BUT: the path i get from the objets doesn`t work for me
Thx #Mike M. , the tip with using getContentResolver() brougth me the anwser after trying around.
Finally is used an other Copy funktion and reworked the onActivityResult();
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK)
{
if (resultData != null) {
try {
String destination = getFilesDir().getPath();
InputStream src = getContentResolver().openInputStream(resultData.getData()); // use the uri to create an inputStream
try {
convertInputStreamToFile(src, destination);
} catch (IOException e) {
e.printStackTrace();
System.out.print("error in upload");
}
} catch (FileNotFoundException ex) {
}
String destination = getFilesDir().getPath();
Toast.makeText(MainActivity.this, "Success!: CSV-File copyed to : " +destination , Toast.LENGTH_SHORT).show();
}
}
}
public static void convertInputStreamToFile(InputStream is, String destination) throws IOException
{
OutputStream outputStream = null;
try
{
File file = new File(destination + "/Student.csv");
outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
finally
{
if(outputStream != null)
{
outputStream.close();
}
}
}

Android app crop photo

I have a question.
This is the code that my application already have and it works like this : takes photo >crop > upload.
I don't want to crop the photo .How can I do this? Just deleting the dispatchCropImageIntent method?
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(this.getClass().getSimpleName(), "onActivityResult");
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
File imageFile = new File(mCurrentPhotoPath);
if (imageFile.exists()) {
dispatchCropImageIntent(Uri.fromFile(imageFile));
}
} else if (requestCode == REQUEST_IMAGE_FROM_GALLERY_SELECT) {
dispatchCropImageIntent(data.getData());
} else if (requestCode == REQUEST_PICTURE_CROP) {
String filePath = Environment.getExternalStorageDirectory()
+ "/temporary_holder.jpg";
setCurrentBitmap(BitmapFactory.decodeFile(filePath));
} else if(requestCode == CAMERA_ACTIVITY_CODE){
// Get path
String path = data.getStringExtra(CustomCamera.OUT_PATH);
// Read file
byte[] imgData = AppFS.readFileFromPath(path);
if (imgData != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(imgData , 0, imgData.length);
// TODO: Do something with the image, it should be okay
//((ImageView)findViewById(R.id.img)).setImageBitmap(bitmap);
} else {
Log.e("Main", "Data is null");
}
}
}
else{
onBackPressed();
}
}
And :
private void dispatchCropImageIntent(Uri uri) {
Intent cropImageIntent = new Intent("com.android.camera.action.CROP");
cropImageIntent.setDataAndType(uri, "image/*");
cropImageIntent.putExtra("crop", "true");
cropImageIntent.putExtra("noFaceDetection", true);
cropImageIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
// retrieve data on return
cropImageIntent.putExtra("return-data", true);
File f = new File(Environment.getExternalStorageDirectory(),
"/temporary_holder.jpg");
try {
f.createNewFile();
} catch (IOException ex) {
Log.e("io", ex.getMessage());
}
uri = Uri.fromFile(f);
cropImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(cropImageIntent, REQUEST_PICTURE_CROP);
}
If I understand you correctly,you want to make your app working like this: takes photo > upload. So, you need to replace dispatchCropImageIntent() with setCurrentBitmap() or upload methond.

Change an image that is store in parse through android

I am trying to update an image that is saved in parse through the android app, I am able o retrieve it and load it to the app but I am not able to save the new image that I selected to replace the old one. This is how I tried to do it and it only saves the file on the current state and not to parse. This is the code that I have currently and it is not working the way I want it to. Kindly assist.
Code is as follows
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == LOAD_IMAGE_RESULTS) {
Uri pickedImage = data.getData();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(pickedImage);
Bitmap selectedImages = BitmapFactory.decodeStream(inputStream);
imageSelected.setImageBitmap(selectedImages);
selectedImages = ((BitmapDrawable) imageSelected.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedImages.compress(Bitmap.CompressFormat.PNG, 5, stream);
byte[] imageRec = stream.toByteArray();
file = new ParseFile("profileUpdate.png", imageRec);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (null == e)
currentUser.put("ProfilePicture", file);
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Unable to load image",
Toast.LENGTH_LONG).show();
}
}
}
}
I just added the currentUser.saveInBackground(); line after currentUser.put("ProfilePicture", file); and added a currentUser.remove("ProfilePicture"); before it and it worked.

File not found error after selecting a file in android

I want to open a .pdf file in my android app.now i can browse the pdf file and after browsing the file I am getting File Not Found Error when i check the file exist or not. Now after selecting the file my selected file Uri data.getData() is like
content://com.android.externalstorage.documents/document/6333-6131:SHIDHIN.pdf
and the path when i parse using data.getData().getPath().toString() is like
/document/6333-6131:SHIDHIN.pdf Here is my code. Please Help me.
// To Browse the file
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, PICK_FILE_REQUEST);
After selecting file
//onActivityResult
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
try {
switch (requestCode) {
case PICK_FILE_REQUEST:
if (resultCode == RESULT_OK) {
try {
Uri fileUri = data.getData();
String path = fileUri.getPath().toString();
File f = new File(path);
if (f.exists()) {
System.out.println("\n**** Uri :> "+fileUri.toString());
System.out.println("\n**** Path :> "+path.toString());
final Intent intent = new Intent(MainActivity.this, ViewPdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} else {
System.out.println("\n**** File Not Exist :> "+path);
}
} catch (Exception e) {
ShowDialog_Ok("Error", "Cannot Open File");
}
}
break;
}
} catch (Exception e) {
}
}
This is not the answer but a workaround.
File file = new File("some_temp_path"); # you can also use app's internal cache to store the file
FileOutputStream fos = new FileOutputStream(file);
InputStream is = context.getContentResolver().openInputStream(uri);
byte[] buffer = new byte[1024];
int len = 0;
try {
len = is.read(buffer);
while (len != -1) {
fos.write(buffer, 0, len);
len = is.read(buffer);
}
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
pass this file's absolute path to your activity.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File pdfFile = new File(Environment.getExternalStorageDirectory(), "Case Study.pdf");
try {
if (pdfFile.exists()) {
Uri path = Uri.fromFile(pdfFile);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(objIntent);
} else {
Toast.makeText(MainActivity.this, "File NotFound", Toast.LENGTH_SHORT).show();
}
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, "No Viewer Application Found", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});

Categories