ImagePager save images to sd card? - android

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

Related

Android save to file.txt appending

I admittedly am still learning and would consider myself a novice (at best) regarding programming. I am having trouble with appending a file in android. Whenever I save, it will rewrite over the file, and I am having trouble understanding how to keep the file that is already there and only add a new line. Hoping for some clarity/advice. Here is how I am saving to the file (which rewrites the file each time I save).
public void saveText(View view){
try {
//open file for writing
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
//write information to file
EditText text = (EditText)findViewById(R.id.editText1);
String text2 = text.getText().toString();
out.write(text2);
out.write('\n');
//close file
out.close();
Toast.makeText(this,"Text Saved",Toast.LENGTH_LONG).show();
} catch (java.io.IOException e) {
//if caught
Toast.makeText(this, "Text Could not be added",Toast.LENGTH_LONG).show();
}
}
Change this,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
to,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", Context.MODE_APPEND));
This will append your new contents to the already existing file.
I Hope it helps!
Use this method, pass filename and the value to be added in the file
public void writeFile(String mValue) {
try {
String filename = Environment.getExternalStorageDirectory()
.getAbsolutePath() + mFileName;
FileWriter fw = new FileWriter("ENTER_YOUR_FILENAME", true);
fw.write(mValue + "\n\n");
fw.close();
} catch (IOException ioe) {
}
}
To display the content of the saved file with the line breaks with a button click use:
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileInputStream fin = openFileInput(fileTitle);
int c;
String temp = "";
while ((c = fin.read()) != -1) {
temp = temp + Character.toString((char) c);
}
tv.setText(temp);
Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
});
To Delete content of existing file whist retaining the filename you can use:
deleteOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_PRIVATE);
// fOut.write(data.getBytes());
dataTitle = "";
fOut.write(data.getBytes());
fOut.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
This worked for me. Takes content of a TextEdit called textTitle. Writes it to file called dataTitle. Then writes a new line with fOut.write("\n"). The next text entered into TextEdit is added to the file with a line break.
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_APPEND);
fOut.write(dataTitle.getBytes());
fOut.write('\n');
fOut.close();
Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

Write file to sdcard in android

I want to create a file on sdcard. Here I can create file and read/write it to the application, but what I want here is, the file should be saved on specific folder of sdcard. How can I do that using FileOutputStream?
// create file
public void createfile(String name)
{
try
{
new FileOutputStream(filename, true).close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// write to file
public void appendToFile(String dataAppend, String nameOfFile) throws IOException
{
fosAppend = openFileOutput(nameOfFile, Context.MODE_APPEND);
fosAppend.write(dataAppend.getBytes());
fosAppend.write(System.getProperty("line.separator").getBytes());
fosAppend.flush();
fosAppend.close();
}
Here's an example from my code:
try {
String filename = "abc.txt";
File myFile = new File(Environment
.getExternalStorageDirectory(), filename);
if (!myFile.exists())
myFile.createNewFile();
FileOutputStream fos;
byte[] data = string.getBytes();
try {
fos = new FileOutputStream(myFile);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
And don't forget the:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Try like this,
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
try {
File file = new File(newFolder, "MyTest" + ".txt");
file.createNewFile();
} catch (Exception ex) {
System.out.println("ex: " + ex);
}
} catch (Exception e) {
System.out.println("e: " + e);
}
It's pretty easy to create folder and write file on sd card in android
Code snippet
String ext_storage_state = Environment.getExternalStorageState();
File mediaStorage = new File(Environment.getExternalStorageDirectory()
+ "/Folder name");
if (ext_storage_state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
if (!mediaStorage.exists()) {
mediaStorage.mkdirs();
}
//write file writing code..
try {
FileOutputStream fos=new FileOutputStream(file name);
try {
fos.write(filename.toByteArray());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
//Toast message sd card not found..
}
Note: 'getExternalStorageDirectory()'
actually gives you a path to /storage/emulated/0 and not the actual sdcard
'String path = Syst.envr("SECONDARY_STORAGE");' gives you a path to the sd card

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.

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.

How to upload/add images on SD CARD in 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

Categories

Resources