This document provides steps to manage data and save files to external memory on an Android device. It involves adding permissions to the manifest, creating an image view in the XML layout, copying an image from the raw folder to external storage, and displaying the image. The key steps are to copy an image from raw resources to external storage, get the image URI, and set it to the image view to display the saved file from external memory.
1 of 2
Download to read offline
More Related Content
3. file external memory
1. Data Management, External Memory
Note: you must have SD card
Note: write an ¡°android.permission.WRITE_EXTERNAL_STORAGE
¡± in your manifest file
Step1. Create a newAndroidProject.
Step2. Add the followingcode toyouractivityxml file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image"
android:contentDescription="@string/android_painter_desc"
android:layout_centerInParent="true"/>
</RelativeLayout>
Step3. Add the followingcode intoyour¡°values.xml file
<string name="android_painter_desc">Android Painter</string>
Step4. Add a raw folderandcopy a png image inthe raw folder
Step5. Add the followingcode inOncreate methodof yourmainactivity
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
File outFile = new File(
2. getExternalFilesDir(Environment.DIRECTORY_PICTURES),
fileName);
if (!outFile.exists())
copyImageToMemory(outFile);
ImageView imageview = (ImageView) findViewById(R.id.image);
imageview.setImageURI(Uri.parse("file://" + outFile.getAbsolutePath()));
}
Step6. Add The followingfunctionsinyourmainactivity
private void copyImageToMemory(File outFile) {
try {
BufferedOutputStream os = new BufferedOutputStream(
new FileOutputStream(outFile));
BufferedInputStream is = new BufferedInputStream(getResources()
.openRawResource(R.raw.painter));
copy(is, os);
} catch (FileNotFoundException e) {
Log.e(TAG, "FileNotFoundException");
}
}
private void copy(InputStream is, OutputStream os) {
final byte[] buf = new byte[1024];
int numBytes;
try {
while (-1 != (numBytes = is.read(buf))) {
os.write(buf, 0, numBytes);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
os.close();
} catch (IOException e) {
Log.e(TAG, "IOException");
}
}
}
Step7. Done.