How to create folder in gallery and save file - android

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();

Related

I am not able to display image from my local storage in android

I have 20k image files in a folder inside my local storage, I need to display the image by its file name from local storage. How to do it? I attached my code here:
if (Environment.getExternalStorageState()
.equals(Environment.DIRECTORY_PICTURES)) {
String filePath = File.separator + "sdcard" + File.separator + "Android" + File.separator + "obb" + File.separator + "convertMp3ToDb" + File.separator + "ldoce6pics" + File.separator + fileName;
try {
FileInputStream fis = new FileInputStream(filePath);
String entry = null;
while ((entry = fis.toString()) != null) {
if (!entry.toString().isEmpty()) {
File Mytemp = File.createTempFile("TCL", "jpg", getContext().getCacheDir());
Mytemp.deleteOnExit();
FileOutputStream fos = new FileOutputStream(Mytemp);
for (int c = fis.read(); c != -1; c = fis.read()) {
try {
fos.write(c);
} catch (IOException e) {
e.printStackTrace();
}
}
fos.close();
FileInputStream MyFile = new FileInputStream(Mytemp);
final Bitmap bit = BitmapFactory.decodeStream(MyFile);
imageView.setImageBitmap(bit);
}
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (Environment.getExternalStorageState()
.equals(Environment.DIRECTORY_PICTURES)) {
String filePath = File.separator + "sdcard" + File.separator + "Android" + File.separator + "obb" + File.separator + "convertMp3ToDb" + File.separator + "ldoce6pics" + File.separator + fileName;
File f = new File(filePath);
if(f.exits()){
Bitmap bm = BitmapFactory.decodeFile(f.getAbsolutePath());
imageView.setImageBitmap(bm);
}else{
// invalid path
}
}
}
Update Section:
if (Environment.getExternalStorageState()
.equals(Environment.DIRECTORY_PICTURES)) {
// this never be true see below image
}
You have to do like this
File file = new File(Environment.getExternalStorageState()+"/Android/obb/convertMp3ToDb/ldoce6pics/"+fileName);
if (file.exists()) {
// your condition should ne likr this.
}

how to use BitmapFactory.decodeFile() to get the Bitmap

i am trying to download image from internet in original quality. then trying to BitmapFactory.decodeFile() to get the Bitmap
to perform this task i tried this but i am getting this error:
The method decodeFile(String) in the type BitmapFactory is not applicable for the arguments (FileOutputStream)
code:
public void saveImageToSDCard(Bitmap bitmap) {
String dirname = "/Amazing Wallpapers/";
File myDir = new File(Environment.getExternalStorageDirectory()
.getPath() + dirname);
myDir.mkdirs();
String str = currentUrl.substring(currentUrl.lastIndexOf('/') + 1,
currentUrl.length());
String fname = "Wallpaper-" + str + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap = BitmapFactory.decodeFile(out);
out.flush();
out.close();
Toast.makeText(
_context,
_context.getString(R.string.toast_saved).replace("#",
"\"" + pref.getGalleryName() + "\""),
Toast.LENGTH_SHORT).show();
Log.d(TAG, "Wallpaper saved to:" + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(_context,
_context.getString(R.string.toast_saved_failed),
Toast.LENGTH_SHORT).show();
}
}
You should pass the file name to the function BitmapFactory.decodeFile()instead of the output stream

Failed in creating a directory

I'm having problems with regards to creating a directory from an external storage, here is the method that I'm using.
public String createDir(String npath,String ndir,String file)
{
String[] paths = new String[] { npath, npath + ndir };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return "ERROR: Creation of directory " + path + " on sdcard failed";
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
if (!(new File(npath + ndir + file)).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open(ndir + file);
OutputStream out = new FileOutputStream(npath + ndir + file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copied " + file);
return "Copied " + file;
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + file + e.toString());
return "Unable to copy " + file + e.toString();
}
}
else
return "Error!";
}
But I always get "ERROR: Creation of directory " + path + " on sdcard failed". Not to mention this is already installed in an android device. I tried looking for the directory of my application, but it is nowhere to be found, that supposedly, should be creating its folder automatically after the installation of my APK. Anyone who can resolve this?

Save Images, Display in Gallery App

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);

Create log file on SendSms and Receive SMS

I am working on an Android version 2.3.3 application which depends on SMS for SMS dealing. I have written two classes SendSMS and ReceiveSMS. I want to create a log file which logs each SMS that it is sent or received. For creating log file I have written code but does not work.
Following is my code,
public void WriteOnLog()
{
File exportDir = Environment.getExternalStorageDirectory();
if (!exportDir.exists()) {
exportDir.mkdirs();
}
String fileName;
fileName = "log" + ".txt";
File file = new File(exportDir,fileName);
String txt=null ;
try {
if(!file.exists()){
file.createNewFile();
FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);
txt = "Date Time |" + " Send/Receive |" + " Controller No |" +" msg";
}
FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);
String dd=null,mm=null,yy=null,hh=null,min=null,ss=null,dt=null;
SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));
yy = newtime.substring(2, 4);
mm = newtime.substring(5, 7);
dd = newtime.substring(8, 10);
hh = newtime.substring(11, 13);
min = newtime.substring(14, 16);
ss = newtime.substring(17);
dt = dd+"-"+mm+"-"+yy +" " + hh + ":" + min +":"+ ss;
txt = dt + " |" +" Send " + "| " + phoneNumber + " | " + message.toUpperCase();
out.write(txt + "\n");
}
catch(IOException sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
}
}
I have used the OutputStreamWriter (instead of FileWriter) Approach. I have it working in my dev environment and tested on device (android 2.3.6). try this out:
try {
File directory;
if(isSDCard){
directory = new File(Environment.getExternalStorageDirectory().toString()+"/"+folderNameOrPath+"/");
}
else{
directory = new File(folderNameOrPath);
}
boolean fileReturnVal = directory.mkdirs();
if(fileReturnVal){
Log.d("Storage", "Write in SD Card: " + folderNameOrPath + " folder Created successfully");
}
else{
Log.d("Storage", "Write in SD Card: " + folderNameOrPath + " folder either already exists or creation failed");
}
File file = new File(directory, fileNameWithExtention);
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//Write the string to the file
osw.write(text);
osw.flush();
osw.close();
//file saved
Toast.makeText(context, "Text saved in SD Card", Toast.LENGTH_SHORT).show();
return true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("Storage", "Write in SD Card: File Not Found ERROR: " + e.toString());
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Storage", "Write in SD Card: IOException ERROR: " + e.toString());
return false;
} catch (Exception e) {
Log.e("Storage", "Write in SD Card: ERROR: " + e.toString());
return false;
}
you can set append mode for you task. The variables isSDCard, folderName, fileNameWithExtn. etc. are method level variables. I am passing those as parameters.

Categories

Resources