How to upload/add images on SD CARD in Android? - android

I am having approx 300-400 images with the size of 320x480 pixels in jpg format. I have to add this images on the SD Card. Currently I am putting this images in the Drawable folder in my project. Now I want to move this images on sd card and through that i wish to use this images for animation purpose. I also want to check that SD Card is mounted or not when my application starts first. I am not having any idea of programming of SD CARD in android so please anyone is having any idea or links for beginner kindly let me know.
CODE
ImageView imgAssets;
String path="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
path = Environment.getExternalStorageDirectory().toString();
try {
copyFromAsstesToSDCard();
readFromSDCard();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void readFromSDCard() {
// TODO Auto-generated method stub
File dir = Environment.getExternalStorageDirectory();
//File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
//Get the text file
File file = new File(dir.getAbsolutePath()+ "/cat_angry10.jpg");
// i have kept text.txt in the sd-card
//System.out.println(file.toString());
if(file.exists()) // check if file exist
{
try {
Bitmap bitMap = BitmapFactory.decodeFile(Environment.getExternalStorageState() + "/cat_angry10.jpg");
//imgAssets.setImageBitmap(bitMap);
imgAssets.setBackgroundDrawable(new BitmapDrawable(bitMap));
}
catch (Exception e) {
//You'll need to add proper error handling here
e.printStackTrace();
}
}
else
{
System.out.println("Sorry file doesn't exist!!");
}
}
public void copyFromAsstesToSDCard() {
// TODO Auto-generated method stub
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("Images");
} catch (IOException e) {
Log.e("tag", e.getMessage());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("Images/"+filename); // if files resides inside the "Files" directory itself
out = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/" + filename);
System.out.println(out.toString());
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) {
// TODO Auto-generated method stub
byte[] buffer = new byte[1024];
int read;
try {
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am getting NullPointerException when reading image from SD CARD.
Thanks
Keyur

Here are some links - if you have a problem using these, post your code and I'll try to help further.
Android write to sd card folder
http://androidgps.blogspot.com/2008/09/writing-to-sd-card-in-android.html
https://sites.google.com/site/androidhowto/how-to-1/save-file-to-sd-card

Related

Copying file from asset folder to sdcard doesn't seem to work

I am trying to copy an image from the asset folder to the sdcard but doesn't seem to copy it on first launch. It creates the folder okay but doesn't copy the file over.
prefs = getPreferences(Context.MODE_PRIVATE);
if (prefs.getBoolean("firstLaunch", true)) {
prefs.edit().putBoolean("firstLaunch", false).commit();
File nfile=new File(Environment.getExternalStorageDirectory()+"/My Images");
nfile.mkdir();
}
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("middle.jpg");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory()+ "/My Images" + filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
private void copyFile(InputStream in, OutputStream out) {
// TODO Auto-generated method stub
}
middle.jpg is the file i want to copy over. Can any one tell me what i am doing wrong?
PS i have WRITE_EXTERNAL_STORAGE in my manifest.
Thanks
You forgot to add / in the end of /My images while constructing the path
File outFile = new File(Environment.getExternalStorageDirectory()+ "/My Images/" + filename);
out = new FileOutputStream(outFile);
because the filename would be MyImages+Filename so it wouldn't exists for copying.

ImagePager save images to sd card?

I have implemented a save button in my ImagePagerActivity however it crashes when i click the save button.
Please point out any errors I might be causing unaware or if there's another way of saving the images more effectively to the sd card. I am still a newbie to coding so please double check my work.
ImagePagerActivity.java
.....
Button isave;
isave = (Button) findViewById(R.id.save);
isave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bitmap mSaveBit = imageLoader.getMemoryCache().get(Constants.IMAGES[pager.getCurrentItem()]);
File imageFile = null;
if (null == mSaveBit) {
imageFile = imageLoader.getDiscCache().get(Constants.IMAGES[pager.getCurrentItem()]);
}
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/HD GOSPEL LOCKSCREENS");
if (!f.exists()) {
f.mkdirs();
}
f = new File(f.getAbsolutePath(),
String.valueOf(System.currentTimeMillis()) + "HDGL.PNG");
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
mSaveBit.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(f));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(ImagePagerActivity.this, "Image Successfully Saved", Toast.LENGTH_LONG).show();
}
});
.....

Concatenate two audio files and play resulting file

I am really facing problem from last couple of days but I am not able to find the exact solution please help me.
I want to merge two .mp3 or any audio file and play final single one mp3 file. But when I am combine two file the final file size is ok but when I am trying to play it just play first file, I have tried this with SequenceInputStream or byte array but I am not able to get exact result please help me.
My code is the following:
public class MerginFileHere extends Activity {
public ArrayList<String> audNames;
byte fileContent[];
byte fileContent1[];
FileInputStream ins,ins1;
FileOutputStream fos = null;
String combined_file_stored_path = Environment
.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/final.mp3";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audNames = new ArrayList<String>();
String file1 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/one.mp3";
String file2 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/two.mp3";
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/AudioRecorder/" + "final.mp3");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
audNames.add(file1);
audNames.add(file2);
Button btn = (Button) findViewById(R.id.clickme);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
createCombineRecFile();
}
});
}
public void createCombineRecFile() {
// String combined_file_stored_path = // File path in String to store
// recorded audio
try {
fos = new FileOutputStream(combined_file_stored_path, true);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
File f = new File(audNames.get(0));
File f1 = new File(audNames.get(1));
Log.i("Record Message", "File Length=========>>>" + f.length()+"------------->"+f1.length());
fileContent = new byte[(int) f.length()];
ins = new FileInputStream(audNames.get(0));
int r = ins.read(fileContent);// Reads the file content as byte
fileContent1 = new byte[(int) f1.length()];
ins1 = new FileInputStream(audNames.get(1));
int r1 = ins1.read(fileContent1);// Reads the file content as byte
// from the list.
Log.i("Record Message", "Number Of Bytes Readed=====>>>" + r);
//fos.write(fileContent1);// Write the byte into the combine file.
byte[] combined = new byte[fileContent.length + fileContent1.length];
for (int i = 0; i < combined.length; ++i)
{
combined[i] = i < fileContent.length ? fileContent[i] : fileContent1[i - fileContent.length];
}
fos.write(combined);
//fos.write(fileContent1);*
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
Log.v("Record Message", "===== Combine File Closed =====");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I already published an app with this function... try my method using SequenceInputStream, in my app I just merge 17 MP3 files in one and play it using the JNI Library MPG123, but I tested the file using MediaPlayer without problems.
This code isn't the best, but it works...
private void mergeSongs(File mergedFile,File...mp3Files){
FileInputStream fisToFinal = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mergedFile);
fisToFinal = new FileInputStream(mergedFile);
for(File mp3File:mp3Files){
if(!mp3File.exists())
continue;
FileInputStream fisSong = new FileInputStream(mp3File);
SequenceInputStream sis = new SequenceInputStream(fisToFinal, fisSong);
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fisSong.read(buf)) != -1;)
fos.write(buf, 0, readNum);
} finally {
if(fisSong!=null){
fisSong.close();
}
if(sis!=null){
sis.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos!=null){
fos.flush();
fos.close();
}
if(fisToFinal!=null){
fisToFinal.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Mp3 files are some frames.
You can concatenate these files by appending the streams to each other if and only if the bit rate and sample rate of your files are same.
If not, the first file plays because it has truly true encoding but the second file can not decode to an true mp3 file.
Suggestion: convert your files with some specific bit rate and sample rate, then use your function.

displaying downloaded images in my phone gallery

I'm trying to tell my app to make some images which are already downloaded appear in the gallery of my phone.
the images are well download and displayed in my app, they have no extension, their names are only a md5.
here is how i'm trying to do so:
public static void makePhotoAppearOnGallery(Activity activity, String md5) {
final String extStorageDirectory = Environment
.getExternalStorageDirectory().toString();
final String festivalDirectory_path = extStorageDirectory
+ Constants.IMAGES_STORAGE_PATH;
File imageOutputFile = new File(festivalDirectory_path, "/");
if (imageOutputFile.exists() == false) {
imageOutputFile.mkdirs();
}
File imageFile = new File(imageOutputFile, md5);
Bitmap bm = decodeFile(imageFile.getAbsoluteFile());
OutputStream outStream = null;
try {
outStream = new FileOutputStream(imageFile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
MediaStore.Images.Media.insertImage(activity.getContentResolver(), festivalDirectory_path, festivalDirectory_path+"/"+md5, "myDownloadedPics");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scanFile(imageFile,activity);
}
public static void scanFile(File downloadedFile, Context mContext){
Uri contentUri = Uri.fromFile(downloadedFile);
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
mediaScanIntent.setData(contentUri);
mContext.sendBroadcast(mediaScanIntent);
}
the app crashes on this line:
MediaStore.Images.Media.insertImage(activity.getContentResolver(), festivalDirectory_path, festivalDirectory_path+"/"+md5, "myDownloadedPics");
with this message:
java.io.FileNotFoundException: /mnt/sdcard/data/com.example.app/images: open failed: EISDIR (Is a directory)
Does anyone know from what it comes?
I had the same problem. It turns out this error happens when there is a folder with the same file name. For example I had a folder named "log.txt".

When i move a file from raw folder to SD card in android, the file won't move

I used the following code to move the audio file form res/raw folder to SD card, when i execute this code, the file won't move. why it will happens, in which line i made mistake.
MoveAudio.java
public class MoveAudioextends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button a = (Button) findViewById(R.id.Button01);
a.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
byte[] buffer = null;
InputStream fIn = getBaseContext().getResources()
.openRawResource(R.raw.song);
int size = 0;
System.out.println("<<<<<<<SIZE>>>>>>>>>>>>>>>>>>>>" + fIn);
try {
size = fIn.available();
System.out
.println("<<<<<<<SIZE>>>>>>>>>>>>>>>>>>>>" + size);
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
String path = "/sdcard/media/audio/ringtones/";
String filename = "examplefile" + ".ogg";
boolean exists = (new File(path)).exists();
if (!exists) {
System.out
.println("<<<<<<<FALSE SO INSIDE THE CONDITION>>>>>>>>>>>>>>>>>>>>");
new File(path).mkdirs();
}
FileOutputStream save;
try {
save = new FileOutputStream(path + filename);
System.out
.println("<<<<<<<SAVE>>>>>>>>>>>>>>>>>>>>" + save);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://" + path + filename)));
File k = new File(path, filename);
System.out.println("<<<<<<<SAVE>>>>>>>>>>>>>>>>>>>>" + k);
}
});
}
}
In my xml file i had sing button, when i click that button the file will move. This code executes without error but the file won't move.
Instead of having empty catch blocks, try instead to write those out.
e.printStackTrace();
// I believe it is.
Additionally, have you permissions to write to the SD Card?
permission.WRITE_EXTERNAL_STORAGE
What is the filename of the song in your resource folder? The reason i ask is that there is a max file size that can be read back for a file that is compressed. Your file, if named with a .ogg extension shouldn't be compressed and thus not constrained to this limit. However if you named it something else that gets compressed it may have this problem.
A good way to log errors is to use androids Log methods. Do so like this:
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e(TAG, "FileNotFoundException", e);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "IOException", e);
}
You may be getting a "Data exceeds UNCOMPRESS_DATA_MAX (1290892 vs 1048576)" message.
The only way to tell for sure though is to log your error. It is also possible the SD card is out of space or you don't have permissions to write to it.
In this example, my raw file is "test.pdf"
We will use "Download" folder in our phone.
"test.pdf" in raw folder will be moved to "Download/test_filemove" folder as "example.pdf"
Make the new "raw" folder in "res" folder.
Copy "test.pdf" to "raw" folder.
Surely you should make Button01 in your layout.
Don't forget to give permission in your manifest file as below
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
I just modify your example a little bit.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button a = (Button) findViewById(R.id.Button01);
a.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
byte[] buffer = null;
InputStream fIn = getBaseContext().getResources()
.openRawResource(R.raw.test);
int size = 0;
System.out.println("<<<<<<<SIZE>>>>>>>>>>>>>>>>>>>>" + fIn);
try {
size = fIn.available();
System.out
.println("<<<<<<<SIZE>>>>>>>>>>>>>>>>>>>>" + size);
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/test_filemove/";
String filename = "example" + ".pdf";
boolean exists = (new File(path)).exists();
if (!exists) {
System.out
.println("<<<<<<<FALSE SO INSIDE THE CONDITION>>>>>>>>>>>>>>>>>>>>");
new File(path).mkdirs();
}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
System.out
.println("<<<<<<<SAVE>>>>>>>>>>>>>>>>>>>>" + save);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
I hope this help you out.

Categories

Resources