how to open a file on android - java

I am new to android and programming. I am using the android touchpaint api, and using the following code to save a drawing, but obviously saving is useless without being able to open the file.
I was wondering if anyone could help me with some code for it.
// Function saves image to file
public String save(Bitmap mBitmap, boolean showMsg) {
String filename;
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
filename = sdf.format(date);
try {
String path = Environment.getExternalStorageDirectory().toString() + "/modTouchPaint/";
File file1 = new File(path);
file1.mkdirs();
OutputStream fOut = null;
File file = new File(path, filename + ".jpg");
fOut = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
if (showMsg)
Toast.makeText(this, "Picture saved to " + path + filename + ".jpg", 9000).show();
return path + filename + ".jpg";
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Please make sure that SD card is installed", 5000).show();
return null;
}
}

Bitmap bitmap = BitmapFactory.decodeFile(pathToFile);
See the documentation for more information.

Related

How To Copy File From SD to Local Storage on Android

I know with Kit Kat you can only write to your applications package specific directory on SD Cards. I was however under the impression you could still copy files from an SD card to local storage with the:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am simply testing if I can copy one file. If I am able to do that I will add the code to search the entire SD card DCIM folder. For now I have the following code (please forgive the messiness of the code, I have written C# and vb.net but java is still very new to me):
String dirPath = getFilesDir().getAbsolutePath() + File.separator + "TCM";
File projDir = new File(dirPath);
if (!projDir.exists())
projDir.mkdirs();
String CamPath = projDir + File.separator + tv2.getText();
File projDir2 = new File(CamPath);
if (!projDir2.exists())
projDir2.mkdirs();
File LocalBuck = new File(projDir2 + File.separator );
String imageInSD = Environment.getExternalStorageDirectory().getAbsolutePath();
File directory1 = new File (sdCard.getAbsolutePath() + "/DCIM");
File directory = new File(directory1 + "/100SDCIM");
File Buckfile = new File(directory, "/BigBuck.jpg");
try {
exportFile(Buckfile, LocalBuck);
} catch (IOException e) {
e.printStackTrace();
}
Here is my code for the export function/application:
private File exportFile(File src, File dst) throws IOException {
//if folder does not exist
if (!dst.exists()) {
if (!dst.mkdir()) {
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HHmmss").format(new Date());
File expFile = new File(dst.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
//Straight to Error Handler
inChannel = new FileInputStream(src).getChannel();
outChannel = new FileOutputStream(expFile).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
return expFile;
}
Here is what my emulator looks like:
Looking for: Debug of SD Location
Should Find It?: EmulatorShowingSd
Question: Am I even able to copy a file from the SD card to local storage after KitKat; if so what is wrong in the code causing the exception to be thrown when it tries to access the SD card file?

Saving a sound bite as a ringtone

I am trying to set a .wav file as a ringtone on Android devices. The code below is able to create directories, and the sound file, but seems to have issues actually setting the file as a ringtone, let alone the selected ringtone. After the method ends, I go to ringtones on the device, and the selected ringtone defaults to "None". Any idea what's going on here? I am using the WRITE_EXTERNAL_STORAGE permission in my manifest. Also, the format of the sound bite doesn't matter to me, I don't mind converting anything that needs converted.
Thanks!!
private String saveAs(String fileName) {
int resSound = getContext().getResources().getIdentifier(fileName, "raw", getContext().getPackageName());
// Resolve save path and ensure we can read and write to it
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/media/audio/ringtones/";
File dir = new File(path);
fileName += ".wav";
if (!dir.exists()) {
dir.mkdirs();
}
if(!dir.canRead() || !dir.canWrite()) {
return "Unable to save ringtone.";
}
// Load the audio into a buffer
byte[] buffer;
InputStream fIn = this.context.getBaseContext().getResources().openRawResource(resSound);
int size;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
}
catch (IOException e) {
return "Error opening sound file";
}
File file = new File(dir, fileName);
FileOutputStream save;
try {
save = new FileOutputStream(file);
save.write(buffer);
save.flush();
save.close();
}
catch (FileNotFoundException e) {
return "Error loading sound file.";
}
catch (IOException e) {
return "Unable to save ringtone.";
}
// Register the sound byte with the OS and set its properties
this.context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path + fileName)));
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, getSoundTitle(fileName));
values.put(MediaStore.MediaColumns.SIZE, size);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
values.put(MediaStore.Audio.Media.ARTIST, "Sound Clip");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
Uri uri = this.context.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath()), values);
RingtoneManager.setActualDefaultRingtoneUri(this.context, RingtoneManager.TYPE_RINGTONE, uri);
return "Successfully set ringtone.";
}
For anyone else who runs into this, I figured it out. It's this line.
this.context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path + fileName)));
If anyone happens to know why this is, I'd be very interested to know. Thanks!

Image gets overwritten when saving to sdcard android

I want to save multiple images in a folder on sdcard but when saving new image, previous ones gets overwritten. How can I save multiple images in my folder?
File mydirectory = new File(Environment.getExternalStorageDirectory() + "/AppFolder");
if(!mydirectory.exists()){
mydirectory.mkdir();
}
if(mydirectory.exists()){
try {
File root = new File(Environment.getExternalStorageDirectory() +"/AppFolder");
File sdImageMainDirectory = new File(root , "pic.png");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
startCameraActivity();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Error occured. Please try again later.",Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void startCameraActivity() {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, 101);
}
You are saving each file with name as pic.png.
You need to change the file name each time.
Edit:
In addition to answer by #David Xu, if you want to have unique name each time, you can just append a unix timestamp at the end of the file name as follows
dImageMainDirectory = new File(root, "pic_" + (System.currentTimeMillis() / 1000L) + ".png");
change
File sdImageMainDirectory = new File(root , "pic.png");
to
File sdImageMainDirectory = null;
int i = 0;
do {
sdImageMainDirectory = new File(root, "pic-" + i + ".png");
i++;
} while (sdImageMainDirectory.exists());
Every file you create has the same name. Here's a quick and dirty solution:
try{
File root = new File(Environment.getExternalStorageDirectory() +"/AppFolder");
int i = 0;
File sdImageMainDirectory = new File(root , "pic.png");
while(sdImageMainDirectory.exists()){
i++
sdImageMainDirectory = new File(root , "pic" +i+ ".png");
}
outputFileUri = Uri.fromFile(sdImageMainDirectory);
startCameraActivity();
} catch (Exception e) {
You are using the same name for every picture which is why it is getting overwritten
File sdImageMainDirectory = new File(root , "pic.png");
you are naming them all pic.png
Try developing a naming convention like pic1.png, pic2.png or you can save the png as the name of the current timestamp like this:
//get timestamp into string
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
String timeStamp = df.format(today);
File sdImageMainDirectory = new File(root , timeStamp + ".png");

storage/emulated/0/ open faild:ENOENT (no such file or directory)?

i have below code that work in some phone and dont work in some other phone.
my code is for saving an image.
String path = Environment.getExternalStorageDirectory().toString();
path += "/";
File fff=new File(path + "/xalopex/Mobile/");
if (!fff.exists())
fff.mkdirs();
path += "xalopex/Mobile/";
path += "lg";
File filename;
try {
filename = new File(path + ".jpg");
FileOutputStream out = new FileOutputStream(filename);
MyImageBitMap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
filename.getAbsolutePath(), filename.getName(),
filename.getName());
} catch (Exception e) {
e.printStackTrace();
//this part will run
// e is storage/emulated/0/xalopex/Mobile/lg.jpg open faild:ENOENT (no such file or directory)
}
where i am wrong ?
How i can fix it?
I would hazard a guess and say its because you need to be accessing /storage/emulated/legacy instead of /storage/emulated/0
I could be wrong.. but I see there are no accepted answers so I'll give this a try :)

Android writing bitmap to sdcard

I'm trying to write a bitmap to an sdcard on android, and I get the error message of
/mnt/sdcard/PhysicsSketchpad/sketchpad145.png (No such file or directory).
I declared the android.permission.WRITE_EXTERNAL_STORAGE permission in the manifest, and this is my code:
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PhysicsSketchpad/";
File dir = new File(file_path);
dir.mkdirs();
File file = new File(dir, "sketchpad" + pad.t_id + ".png");
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
What's going on?
UPDATE
It seems as though when I try to write to an existing directory, I get an permission denied error,
08-11 09:55:23.796: WARN/Physics Sketchpad(8881): Error when saving: IOException /mnt/sdcard/download/sketchpad54.png (Permission denied)
and when I try to save in a new directory I get a no such file or directory error, 08-11 09:59:20.175: WARN/Physics Sketchpad(9040): Error when saving: IOException /mnt/sdcard/PhysicsSketchpad/sketchpad55.png (No such file or directory)
In addition, File.mkdirs() returns a boolean based on if it succeeded or not, and it returned false.
try this code.
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PhysicsSketchpad";
File dir = new File(file_path);
if(!dir.exists)
dir.mkdirs();
File file = new File(dir, "sketchpad" + pad.t_id + ".png");
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
try this code. This has worked for me.
public void saveBitmap(Bitmap bm)
{
try
{
String mBaseFolderPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera/";
String mFilePath = mBaseFolderPath + "abcd.jpg";
FileOutputStream stream = new FileOutputStream(mFilePath);
bm.compress(CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
}
catch(Exception e)
{
Log.e("Could not save", e.toString());
}
}
Shash
you getting the absolute path check into the error what you getting the path
/mnt/sdcard/AppName/appname145.png
and you set the
Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PhysicsSketchpad/";
where as "PhysicsSketchpad" dir not getting in above path
try this
Environment.getExternalStorageDirectory().toString()+ "/PhysicsSketchpad/";

Categories