I am saving my file to app's private internal storage like this then I pass that file into a Uri so I can return it as a result in my other activity
String filename = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(data);
outputStream.close();
Intent intent = new Intent();
intent.setData(Uri.fromFile("")); //pass file here somehow
setResult(Activity.RESULT_OK);
finish();
} catch (IOException e) {
Toast.makeText(CameraActivity.this, "Error creating file " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
How do you get the File from openFileOutput ?
How do you get the File from openFileOutput ?
Use Context.getFilesDir() for getting file path which is created using openFileOutput method:
String rootDir = this.getFilesDir().getAbsolutePath();
File file = new File(rootDir + filename);
.....
intent.setData(Uri.fromFile(file));
I made this solution for the very same problem, I like this one better:
Uri internalFilesUri = Uri.fromFile(getContext().getFilesDir());
Uri fileUri = Uri.withAppendedPath(internalFilesUri , filename);
Related
I try to open a PDF in my application.
First, I create the PDF like that :
String filename = Environment.getExternalStorageDirectory().toString()+"/mypdf.pdf";
File file = new File(filename);
try {
FileOutputStream bos = new FileOutputStream(file);
bos.write(Base64.decode(base64, 0));
bos.flush();
bos.close();
} catch (IOException e) {
Log.e(TAG, "IOError with PDF");
e.printStackTrace();
}
Intent intent = new Intent(this, PdfActivity.class);
intent.putExtra("file", filename);
startActivity(intent);
The file is well created and readable, I can open this with ESExplorer application.
This file is located in /storage/emulated/0/myfile.pdf
in the PdfActivity I try to open the PDF :
Bundle extras = getIntent().getExtras();
String url = extras.getString("file");
File file = new File(url);
try {
if (file.exists()) {
Uri path = Uri.parse(url);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(objIntent);
} else {
Toast.makeText(this, "File NotFound", Toast.LENGTH_SHORT).show();
}
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No Viewer Application Found", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
file.exists() return true, Intent start, but my PDF reader says : "File not found"
I've added read and write permissions on external storage.
Does someone have any idea why it can't access to my file ?
objIntent.setDataAndType(url, "application/pdf");
use above line in your second snippest also declare String url as a global variable hope it will help you if it will not work try to use hardcode value of file path and see is it working or not ?
and are you sure file is exist? check this scenario tooo :)
I found the solution.
I've replace the Uri like that:
Uri path = Uri.fromFile(file);
And it works!
I'm a newbie Android developer. I have loaded an image using universal-image-loader and I would like to save it on my sd card. The file is created in the desired directory with the correct filename, but it always has a size of 0. What am I doing wrong?
A relevant snippet follows:
PS: The image already exists on disk, it's not being downloaded from the Internet.
private void saveImage(String imageUrls2, String de) {
String filepath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
File SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
String filename = de;
File myDir = new File(SDCardRoot+"/testdir");
Bitmap mSaveBit = imageLoader.getMemoryCache();
File imageFile = null;
try {
//create our directory if it does'nt exist
if (!myDir.exists())
myDir.mkdirs();
File file = new File(myDir, filename);
if (file.exists())
file.delete();
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bos.flush();
bos.close();
} catch (IOException e) {
filepath = null;
e.printStackTrace();
Toast.makeText(getApplicationContext(),
R.string.diskful_error_message, Toast.LENGTH_LONG)
.show();
}
Log.i("filepath:", " " + filepath);
}
Yes, your code creates an file on sdcard_root/testdir/de only, and didn't write anything to it. Is "imageUrls2" the source image file? If yes, you can open that file with BufferedInputStream, read the data from BufferedInputStream, and copy them to output file with bos.write() before bos.flush() and bos.close().
Hope it helps.
I would like to upload a string as a text file to skydrive from my android application. Is this possible?
Thanks.
Yes it is possible, you have to create a file from the user Entered String, and then save this .txt file on your Server(skydrive)
Its the code which will create a file from the string.
private String filename = "MySampleFile.txt";
private String filepath = "MyFileStorage";
File myInternalFile;
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
myInternalFile = new File(directory , filename);
FileOutputStream fos = new FileOutputStream(myInternalFile);
fos.write(myInputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
Toast.makeText(context, MySampleFile.txt saved to Internal Storage...", 1000).show;
}
Now save this file in skydrive using skydrive api.
My problem is whenever I save the bitmap. I saves one in the folder I want(MyFolder) and one in the DCIM/Camera. I don't see any code that makes it save int he DCIM directory?
Here are my codes...
case R.id.menu_save:
try {
String path = Environment.getExternalStorageDirectory()
.toString();
File myNewFolder = new File(path + "/MyFolder");
myNewFolder.mkdirs();
OutputStream fOut = null;
File file = new File(path, "/MyFolder/HK" + filename + ".jpg");
fOut = new FileOutputStream(file);
newBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
file.getAbsolutePath(), file.getName(), file.getName());
Toast.makeText(getApplicationContext(),
filename + "Has been saved!", Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
Toast.makeText(
getApplicationContext(),
"Problem to Save the File", Toast.LENGTH_LONG).show();
}
break;
As in the thread #Dixit linked, you can specify the file path URI with
File fileDir = new File(Environment.getExternalStorageDirectory() +
"/saved_images");
fileDir.mkdirs();
File file = new File(fileDir, "image.jpg");
Uri outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
This way the camera will save the image to the specified path instead of the DCIM folder.
EDIT: You have to create the folder on the sdcard beforehand, maybe that's the problem. Otherwise, this should work.
I think I have looked at all of the relevant questions and I still can't get this to work.
Here is the code:
File sdCard = Environment.getExternalStorageDirectory();
File directory= new File (sdCard.getAbsolutePath() + appName);
directory.mkdirs();
File file = new File(directory,fileName);
The folder is created, but I get an error saying the file does not exist. appName is a string containing the name of the folder and that works correctly. fileName is a string containing the name of the file I want to include.
I have included the permission in the manifest.
What am I doing wrong?
Update:
The code tries to make a subdirectory and a file at the same time, which hidden because the code uses a named String rather than a String literal. Adding an intermediate step to create the subdirectory solved the problem.
If the directory is created, then you're on the right track. In your code you are not actually creating the file on the SD card. If you need to create the file, then do this:
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() + appName + "/" + fileName);
directory.mkdirs();
file.createNewFile()
This is notional only. It would be much better to actually separate your fileName into a separate subfolder and the actual file and handle them separately.
Try this out:
In this I am creating a text file (.txt file) of a string.
public void createFileFromString(String text)
{
File logFile = new File("sdcard/xmlresponseiphone.txt");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Test this, and see what are you missing :)
Try with something like this. In this case I'm saving an image!
For creating the directory:
File directory = new File(Environment.getExternalStorageDirectory()
+ File.separator + appName);
directory.mkdirs();
And for saving into it
public void save(Bitmap graph, Context context, String name, String time, boolean now) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
graph.compress(Bitmap.CompressFormat.PNG, 100, bytes);
// you can create a new file name "test.jpg" in sdcard folder.
String fileName = "";
if (now){
fileName = getDateTime()+"_00"+".png";
}
else {
fileName = time.replace(".txt", ".png");
}
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "appName/" + fileName);
f.createNewFile(); // write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
}
I think the trick is in File.separator!