In my app i want to store camera images taken by the user in a folder.So for that i have created a folder ,but when erer i open my sd-card i cannot find that folder.Whats wrong with my code.
Create FIle
protected void createFile(Context context, String mainName, String subName) {
file = new File(Environment.getExternalStorageDirectory() + "/" + mainName + "/" + subName);
if (!file.exists()) {
file.mkdirs();
Toast.makeText(getActivity(), "File created" + file.toString(), Toast.LENGTH_LONG).show();
}
}
Class where i am user the above method
public void onClick(View view) {
setUp();
createFile(getActivity(),"pocketDocs","Camera");
switch (view.getId()) {
case R.id.bt_choose_file:
displayPopup(getActivity(), "Choose File", chooseDocumentArray, btChooseDoc, false, new GetNamePosition() {
#Override
public void getName(String name) {
userSelection = name;
if (userSelection.equals("Camera")) {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
btChooseDoc.setText("Choose File");
}
Use
file = new File(Environment.getExternalStorageDirectory() + "/" + mainName
+ "/" + subName + "/");
Instead of
file = new File(Environment.getExternalStorageDirectory() + "/" + mainName
+ "/" + subName);
Without the trailing separator (in your case /), Android (which is based on UNIX), interprets this as a file (not a directory). This is due to the File class in Java representing files and directories. And you simply cannot create directories inside a file.
Also add WRITE_EXTERNAL_STORAGE permission in your manifest.
Related
Now I copy mp4 file from external storage folder and save copy file in gallery with folder. But My gallery app doesn't have folder I code. Surely, File too. But In File Browser, There are exists correctly in DCIM folder.
So, How can I save file in gallery with folder that I code. Please let me know If you can solve this issue.
private void saveToGallery(String recVideoPath) {
progressdialog = new CNetProgressdialog(this);
progressdialog.show();
String folderName = "DuetStar";
String fromPath = recVideoPath;
String toPath = Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DCIM;
File toPathDir = new File(toPath + "/" + folderName);
final File fromPathFile = new File(fromPath);
File toPathFile = new File(toPath + "/" + folderName, recVideoPath.substring(recVideoPath.lastIndexOf("/") + 1, recVideoPath.length()));
Log.d(TAG, "saveToGallery: " + RecordActivity.currentCreateFileName);
Log.d(TAG, "saveToGallery: " + toPathDir.toString());
Log.d(TAG, "saveToGallery: " + fromPath.toString());
Log.d(TAG, "saveToGallery: " + toPath.toString());
if (!toPathDir.exists()) {
toPathDir.mkdir();
} else {
}
FileInputStream fis = null;
FileOutputStream fos = null;
try {
if (toPathDir.exists()) {
fis = new FileInputStream(fromPathFile);
fos = new FileOutputStream(toPathFile);
byte[] byteArray = new byte[1024];
int readInt = 0;
while ((readInt = fis.read(byteArray)) > 0) {
fos.write(byteArray, 0, readInt);
}
Log.d(TAG, "saveToGallery: " + readInt);
fis.close();
fos.close();
Log.d(TAG, "saveToGallery: " + "Seucceful");
} else {
Toast.makeText(this, "There is no directory", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.getMessage();
}
progressdialog.dismiss();
}
You can save in specific folder as you wish see this code snippet for idea
String extStorageDirectory;
extStorageDirectory = Environment.getExternalStorageDirectory().toString() + "/Video Folder name/";
//making the folder
new File(extStorageDirectory).mkdirs();
I created an encrypted OBB file from the JOBB tool and I am trying to access the files inside of it, there are some images "image1.jpg, image2.jpg" etc. So far I am able to successfully mount it with:
public void mountExpansion() {
final StorageManager storageManager = (StorageManager) this.getSystemService(Context.STORAGE_SERVICE);
String packageName = "com.nick.app";
String filePath = Environment.getExternalStorageDirectory()
+ "/Android/obb/" + packageName + "/" + "main."
+ getString(R.string.apk_expansion_version) + "." + packageName + ".obb";
final File mainFile = new File(filePath);
if (mainFile.exists()) {
Log.d("STORAGE", "FILE: " + filePath + " Exists");
} else {
Log.d("STORAGE", "FILE: " + filePath + " DOESNT EXIST");
}
String key = "123456";
if (!storageManager.isObbMounted(mainFile.getAbsolutePath())) {
if (mainFile.exists()) {
if(storageManager.mountObb(mainFile.getAbsolutePath(), key,
new OnObbStateChangeListener() {
#Override
public void onObbStateChange(String path, int state) {
super.onObbStateChange(path, state);
Log.d("PATH = ",path);
Log.d("STATE = ", state+"");
expansionFilePath = storageManager.getMountedObbPath(path);
if (state == OnObbStateChangeListener.MOUNTED) {
expansionFilePath = storageManager
.getMountedObbPath(path);
Log.d("STORAGE","-->MOUNTED");
Log.d("NICK","length()"+mainFile.length());
Log.d("NICK","getAbsolutePath()"+mainFile.getAbsolutePath());
Log.d("NICK","isDirectory()"+mainFile.isDirectory());
}
else {
Log.d("##", "Path: " + path + "; state: " + state);
}
}
}))
{
Log.d("STORAGE_MNT","SUCCESSFULLY QUEUED");
}
else
{
Log.d("STORAGE_MNT","FAILED");
}
} else {
Log.d("STORAGE", "Patch file not found");
}
}
}
And in my log I see the state "1" returned from OnObbStateChangeListener indicating the encrypted OBB file is successfully mounted. However at this point I am at a loss for how I can access the files inside of it and make use of them. For example load them into an ImageView etc. Any suggestions for what I am missing here?
storageManager.mountObb(main.getPath(), null, new OnObbStateChangeListener() {
#Override
public void onObbStateChange(String path, int state) {
super.onObbStateChange(path, state);
if (state == MOUNTED) {
Toast.makeText(MainActivity.this, "obb mounted", Toast.LENGTH_LONG).show();
File file = new File(storageManager.getMountedObbPath(path));
} else
Toast.makeText(MainActivity.this, "mount fail :" + path, Toast.LENGTH_LONG).show();
}
});
The file object is directory to all your files in obb.
To access those you may call listFiles() on it.
public void onClick(View v) {
// Writing data to file
FileWriter fw;
try {
fw = new FileWriter(Environment.getExternalStorageDirectory()+"/DataLog.csv", true);
BufferedWriter br = new BufferedWriter(fw);
br.append(formattedDate + String.valueOf(location.getLatitude()) +
";" + String.valueOf(location.getLongitude()) +
";" + String.valueOf(location.getSpeed()) +
";" + String.valueOf(location.getBearing()) +
";" + String.valueOf(location.getAltitude()) +
";" + String.valueOf(location.getAccuracy()));
br.append("\r\n");
br.close();
fw.close();
// MediaScanner scans the file
MediaScannerConnection.scanFile(MainActivity.this, new String[] {fw.toString()} , null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Toast t = Toast.makeText(MainActivity.this, "Scan comlete", Toast.LENGTH_LONG);
t.show();
}
} );
} catch (IOException e) {
e.printStackTrace();
}
}
I tried a code to write data to a DataLog.csv file in the sd root. The code creates the file with the data but i cannot see the file in windows when browsing the sdcard.
I saw this video and followed the instructions but it is not working for me. Maybe the fw variable is not good to define the file?
File csv = new File (Environment.getExternalStorageDirectory(), "DataLog.csv");
MediaScannerConnection.scanFile(
MainActivity.this,
new String[] {csv.getAbsolutePath()},
null, null);
I tried your advice like this but it still doing nothing.
toString() on FileWriter does not return the path to the file, which you are assuming it does, in the second parameter you pass to scanFile().
I am capturing image by camera app and want to store in Specific folder but image not storing in folder here is my code :
File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/" + "my_data");
try {
if (!dir.exists())
if (dir.mkdir()) {
System.out.println("Directory created");
Toast.makeText(Add.this, "created dir",
Toast.LENGTH_LONG).show();
}
image_path = Environment.getExternalStorageDirectory().getPath() + "/my_data/" + aa + "_image.jpg";
File file = new File(dir,image_path);
uriImage = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriImage);
startActivityForResult(intent,CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
EDIT
This should work, if not please post logcat output.
String folderPath = Environment.getExternalStorageDirectory().toString()
+ java.io.File.separator + "my_data"
);
File dir = new File(folderPath);
if(!dir.exists){
dir.mkdirs();
}
imagePath = folderPath+java.io.File.separator+aa+"_image.jpg";
I'm currently working on an App that receives multiple images via socket. To save them, I wrote the following methods:
public static boolean saveTempImageToGallery(Context c) {
try {
FileInputStream fis = c.openFileInput(Settings.TEMP_PHOTO_STORAGE);
// create name of file: [date]-[time]-baby
final String tFilename = new SimpleDateFormat("dd-MM-yyyy_hh-mm-ss")
.format(new Date()) + ".png";
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.d(TAG, "External storage available.");
// sd card available
File dir = getExternalStorageDir("Photos");
if (dir.mkdirs() || dir.isDirectory()) {
Log.i(TAG, "Directory: "+dir.getAbsolutePath());
File newImage = new File(dir, tFilename);
if (newImage.createNewFile() && newImage.isFile()) {
Log.i(TAG, "Saving image to "+newImage.getAbsolutePath());
final Bitmap bmp = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// compress image to png
bmp.compress(Bitmap.CompressFormat.PNG, 40, baos);
FileOutputStream fo = new FileOutputStream(newImage);
fo.write(baos.toByteArray());
fo.close();
Log.i(TAG, "Image saved!");
return true;
}
} else {
Log.d(TAG, "Could not create directory.");
}
} else {
Log.d(TAG, "External storage not available.");
}
} catch (Exception e) {
}
return false;
}
public static File getExternalStorageDir() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/"
+ Settings.EXT_STORAGE_DIRECTORY);
return dir;
}
public static File getExternalStorageDir(String subdir) {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/"
+ Settings.EXT_STORAGE_DIRECTORY + "/" + subdir);
return dir;
}
After saving them, I'd like to offer the user the possibility to view them in the default gallery app. After reading some post, I adapted the following code:
MediaScannerConnectionClient mScanClient = new MediaScannerConnectionClient() {
#Override
public void onScanCompleted(String path, Uri uri) {
try {
Log.d("onScanCompleted", uri + "success");
if (uri != null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} finally {
if (mScanCon != null)
mScanCon.disconnect();
mScanCon = null;
}
}
#Override
public void onMediaScannerConnected() {
Log.i(TAG, "Media Scan Connected.");
String[] files = Support.getExternalStorageDir("Photos")
.list();
Log.i(TAG,
Support.getExternalStorageDir("Photos").list().length
+ " elements in dir.");
if (files.length > 0) {
for (String cur : files) {
if (cur.equals(".") || cur.equals(".."))
continue;
Log.i(TAG, "Using "
+ cur
+ " to scan stuff. "
+ Support.getExternalStorageDir("Photos")
.getAbsolutePath() + "/" + cur);
Log.i(TAG, "Not using "
+ cur
+ " to scan stuff. "
+ Support.getExternalStorageDir("Photos")
.toString() + "/" + cur);
mScanCon.scanFile(
Support.getExternalStorageDir("Photos")
.getAbsolutePath() + "/" + cur,
"image/*");
break;
}
} else {
Toast.makeText(getApplicationContext(),
"No images available.", Toast.LENGTH_LONG)
.show();
}
}
};
if (mScanCon != null)
mScanCon.disconnect();
mScanCon = new MediaScannerConnection(getApplicationContext(),
mScanClient);
mScanCon.connect();
Weird thing: Seems like onMediaScannerConnected is never fired - anyone has an idea? I've been searching the web and stackoverflow for the last hour..
Thank you.
You really don't have to connect to the media scanner to start a scan, you can use this static method instead.
MediaScannerConnection.scanFile(context, new String[] {dir.getAbsolutePath()}, null, null);
edit:
Uri uri = Uri.parse(filePath);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(uri, "image/*");
startActivity(i);