Why application with 300 images stops working? - android

I have created an app which consist 300 images. At the start of app it works snooth, no issue. but when i start the listactivity which load images, my app stop responding. Help me.
This is my MainActivity codes.
I copy image zip file from assets folder to internal storage and extract images in internal storage and then show them in gridview of mainactivity.
private void createDirs()
{
File zipFileLoc = new File(storagePath, zipLoc);
File unzipFileLoc = new File(storagePath, unzipLoc);
File aksFileLoc = new File(storagePath, aks);
if(zipFileLoc.exists() && unzipFileLoc.exists() && aksFileLoc.exists()){
getFromStorage();
}else{
zipFileLoc.mkdirs();
unzipFileLoc.mkdirs();
aksFileLoc.mkdirs();
copyAssets();
unzip();
getFromStorage();
}
}
private void copyAssets()
{
AssetManager assets = getAssets();
String[] files = null;
try{
files = assets.list("");
}catch(Exception e){
Toast.makeText(this, "Failed to load images, please restart app", Toast.LENGTH_LONG).show();
}
for(String fileName : files){
InputStream in = null;
OutputStream out = null;
try{
in = assets.open(fileName);
File zipOutFile = new File(storagePath + zipLoc, fileName);
out =new FileOutputStream(zipOutFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}catch(Exception e){
Toast.makeText(this, "Failed to load images, please restart app", Toast.LENGTH_LONG).show();
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
private void unzip()
{
pd = new ProgressDialog(this);
pd.setMessage("Please wait...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setCancelable(false);
pd.show();
new UnZipTask().execute(storagePath + zipLoc + "/AAGRIKOLISTATUS.zip", storagePath + aks);
}
private class UnZipTask extends AsyncTask<String, Void, Boolean>
{
#SuppressWarnings("rawtypes")
#Override
protected Boolean doInBackground(String[] p1)
{
String filePath = p1[0];
String destinationPath = p1[1];
File archive = new File(filePath);
try{
ZipFile zf = new ZipFile(archive);
for(Enumeration e = zf.entries(); e.hasMoreElements();){
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zf, entry, destinationPath);
}
UnzipUtil d = new UnzipUtil(storagePath + zipLoc + "/AAGRIKOLISTATUS.zip", storagePath + aks);
d.unzip();
}catch(Exception e){
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
pd.dismiss();
}
private void unzipEntry(ZipFile zf, ZipEntry entry, String destinationPath) throws IOException
{
if(entry.isDirectory()){
createDir(new File(destinationPath, entry.getName()));
return;
}
File outputFile = new File(destinationPath, entry.getName());
if(!outputFile.getParentFile().exists()){
createDir(outputFile.getParentFile());
}
BufferedInputStream inputs = new BufferedInputStream(zf.getInputStream(entry));
BufferedOutputStream outputs = new BufferedOutputStream(new FileOutputStream(outputFile));
try{
}finally{
outputs.flush();
outputs.close();
inputs.close();
}
}
private void createDir(File file)
{
if(file.exists()){
return;
}
if(!file.mkdirs()){
throw new RuntimeException("Cannot create file " + file);
}
}
}
private void getFromStorage()
{
File file = new File(storagePath, aks);
if(file.isDirectory()){
listfile= file.listFiles();
for(int i = 0; i < listfile.length; i++){
f.add(listfile[i].getAbsolutePath());
}
}
ad = new ImageAdapter(this);
gv.setAdapter(ad);
}
public class ImageAdapter extends BaseAdapter
{
Context context;
public ImageAdapter(Context cxt)
{
this.context = cxt;
}
#Override
public int getCount()
{
return f.size();
}
#Override
public Object getItem(int p1)
{
return p1;
}
#Override
public long getItemId(int p1)
{
return p1;
}
#Override
public View getView(int p1, View p2, ViewGroup p3)
{
ImageView iv = new ImageView(context);
Bitmap bm = BitmapFactory.decodeFile(f.get(p1));
iv.setImageBitmap(bm);
iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
iv.setLayoutParams(new GridView.LayoutParams(240, 240));
return iv;
}
}
Here's my main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp"
android:gravity="center"
android:background="#00ff85">
<GridView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/aagrikolistatusphotoGridView"
android:layout_above="#+id/aagrikolistatusphotocomgoogleandroidgmsadsAdView"
android:columnWidth="90dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:horizontalSpacing="5dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp"/>

Even though you unpack images on the background thread but you load them on main thread what causes UI crash. The solution is to use Glide or Picasso to load images on the background thread. Please read Google Documentation:
https://developer.android.com/topic/performance/graphics/load-bitmap#java
and try to use one of them:
Glide:
https://github.com/bumptech/glide
Picasso:
http://square.github.io/picasso/
That should help to solve your problem

Related

After Download Images are replacing in my gallery

I have recyclerview and in every recyclerview item, I have images. I also have a download button in every recyclerview item.
If the user will click on download button, images of that recyclerview item will download and store it.
Till here it works fine, now the issue is that, if a user is downloading an image of the first product, and the user will download another image for the next product, images in the gallery is being replaced.
public class DownloadImage extends AsyncTask<String, Void, Void> {
private Context context;
private DownloadImage(Context context) {
this.context = context;
}
#Override
protected Void doInBackground(String... params) {
int ii = 0;
for (int k=0;k<resellerProductLists.get(imgpos).getProductImageDtoList().size();k++) {
//Toast.makeText(context,resellerProductLists.get(0).getProductImageDtoList().get(k).getImageUrl(),Toast.LENGTH_SHORT).show();
Log.e("Image",resellerProductLists.get(imgpos).getProductImageDtoList().get(k).getImageUrl());
ii++;
String img = "IMG-";
String mPath = Environment.getExternalStorageDirectory().toString() + "/Temp/" + img + ii + ".jpg";
File Directory = new File(Environment.getExternalStorageDirectory().toString() + "/Temp");
Directory.mkdirs();
try {
File file = Glide.with(context)
.load(resellerProductLists.get(imgpos).getProductImageDtoList().get(k).getImageUrl())
.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
File imageFile = new File(mPath);
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
out = new BufferedOutputStream(new FileOutputStream(mPath));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
} catch (InterruptedException | ExecutionException | IOException e) {
hideLoading();
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void res) {
super.onPostExecute(res);
//prodImageUri1.addAll(prodImageUri);
// hideLoading();
Toast.makeText(context,"Download Complete Successfully", Toast.LENGTH_SHORT).show();
}
}
Can anyone assist me with this problem?
Image in the gallery is being replaced because both images have same name. This is because your variable 'ii' is initiliazed inside the 'doInBackgroud()' function hence name of image always become "../temp/IMG-1.jpg". To prevent replacing of old Images you can do either of the Following :
Make ' ii ' a Global Variable, so that ii is not initiliazed every time.
Replace int ii=0 with String ii = System.currentTimeMillis().toString(), This will gurantee that ii is unique every time .
Add this to your code and test again:
String timeStamp = new SimpleDateFormat("HHmmss", Locale.US).format(new Date());
String mPath = Environment.getExternalStorageDirectory().toString() + "/Temp/" + img + ii +timeStamp+ ".jpg";
timeStamp will generate unique time based name for every item you download. you can replace this time stamp with everything you want. but it must be unique for every item.
For example you can create a getter/setter in your model class and setImageName accordingly.
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
private String imageName;
And use it like this:
String uniqueName = resellerProductLists.get(imgpos).getProductImageDtoList().get(k).getImageName());

Android File Not Found Exception, though the image is saved

I am making an app which utilizes the camera, and has the ability to take a picture to use a simple image recognition API on it. I can use the gallery just fine to upload images, but straight from the camera is giving me massive issues. I have basically just copied the android dev documentation for most of the image creation, though may have needed to change some items here and there.
Here is the total code:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + "Image_for_Stack" + "_";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "Camera");
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = "file: " + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
try {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.v(TAG, "IO Exception " + ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(getContextOfApplication(),
BuildConfig.APPLICATION_ID + ".provider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, IMAGE_CAPTURE);
}
}
} catch (Exception e) {
Log.v(TAG, "Exception in dispatch " + e);
}
}
private void galleryAddPic() {
try {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getContextOfApplication().sendBroadcast(mediaScanIntent);
} catch (Exception e) {
Log.v(TAG, "Exception " + e);
}
}
And in a separate class, this is called:
public static byte[] getByteArrayFromIntentData(#NonNull Context context, #NonNull Intent data) {
InputStream inStream = null;
Bitmap bitmap = null;
try {
inStream = context.getContentResolver().openInputStream(data.getData());
Log.v(TAG, "Instream works");
bitmap = BitmapFactory.decodeStream(inStream);
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
return outStream.toByteArray();
} catch (FileNotFoundException e) {
Log.v("FileOP Debug", "Exception " + e);
return null;
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException ignored) {
}
}
if (bitmap != null) {
bitmap.recycle();
}
}
}
Now, the image is created without issue. I can go to the emulator, look through the photo's app, and get:
.
However, I get this error when the code gets to giving inStream a value:
java.io.FileNotFoundException: /file:
/storage/emulated/0/DCIM/Camera/JPEG_Image_for_Stack_3248071614992872091.jpg
(No such file or directory) .
I don't exactly understand how this could be. The item clearly exists, and is saved on the phone. The app does request and is given the permission to write to external storage, and I have checked in the emulator permissions that it is given. Write also comes with read, so that shouldn't be an issue as far as I'm aware either.
Edit
To show where this code is being called from.
else if (requestCode == IMAGE_CAPTURE) {
galleryAddPic();
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
final ProgressDialog progress = new ProgressDialog(getContextOfApplication());
progress.setTitle("Loading");
progress.setMessage("Identify your flower..");
progress.setCancelable(false);
progress.show();
if (!CheckNetworkConnection.isInternetAvailable(getContextOfApplication())) {
progress.dismiss();
Toast.makeText(getContextOfApplication(),
"Internet connection unavailable.",
Toast.LENGTH_SHORT).show();
return;
}
client = ClarifaiClientGenerator.generate(API_KEY);
final byte[] imageBytes = FileOp.getByteArrayFromIntentData(getContextOfApplication(), mediaScanIntent);
As of right now, imageBytes will be null as the the FileNotFound exception is thrown on that method call.
You can try this code...
public class Images extends Activity
{
private Uri[] mUrls;
String[] mFiles=null;
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.images);
File images = Environment.getDataDirectory();
File[] imagelist = images.listFiles(new FilenameFilter(){
#override
public boolean accept(File dir, String name)
{
return ((name.endsWith(".jpg"))||(name.endsWith(".png"))
}
});
mFiles = new String[imagelist.length];
for(int i= 0 ; i< imagelist.length; i++)
{
mFiles[i] = imagelist[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for(int i=0; i < mFiles.length; i++)
{
mUrls[i] = Uri.parse(mFiles[i]);
}
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setFadingEdgeLength(40);
}
public class ImageAdapter extends BaseAdapter{
int mGalleryItemBackground;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount(){
return mUrls.length;
}
public Object getItem(int position){
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView i = new ImageView(mContext);
i.setImageURI(mUrls[position]);
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setLayoutParams(new Gallery.LayoutParams(260, 210));
return i;
}
private Context mContext;
}
}

How to Save image into local storage loaded with Glide?

I have an ImageView in which I loaded a photo from server into it with Glide library.
I have a save button in which I want the image saved to gallery and internal storage when clicked after being loaded. I have tried several possibilities with no success as nothing seem to happen after I click the button.
public class ImagePreviewActivity extends AppCompatActivity {
ImageView imageView;
final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/SmartPhoto");
boolean success = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_preview);
imageView = findViewById(R.id.image_preview);
saveImage();
}
private void saveImage() {
TextView mSave = findViewById(R.id.save_img);
mSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
final String fname = "image" + n + ".png";
myDir.mkdirs();
File image = new File(myDir, fname);
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(),"Saved", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"not saved", Toast.LENGTH_LONG).show();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
final Uri contentUri = Uri.fromFile(image);
scanIntent.setData(contentUri);
sendBroadcast(scanIntent);
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://mnt/sdcard/" + Environment.getExternalStorageDirectory())));
}
}
});
}
}
Log Cat
02-24 14:40:41.288 1567-1575/? E/System: Uncaught exception thrown by finalizer
02-24 14:40:41.289 1567-1575/? E/System: java.lang.IllegalStateException: Binder has been finalized!
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:622)
at android.net.INetworkStatsSession$Stub$Proxy.close(INetworkStatsSession.java:476)
at android.app.usage.NetworkStats.close(NetworkStats.java:382)
at android.app.usage.NetworkStats.finalize(NetworkStats.java:118)
at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:223)
at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:210)
at java.lang.Thread.run(Thread.java:761)
AsyncTask, can be used to download Image .This proccess will be in background thread.
class DownloadImage extends AsyncTask<String,Integer,Long> {
String strFolderName;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="Name"+".rar";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+ "/"+downloadFolder+"/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onPostExecute(String result) {
}
}
You can call this class like this new DownloadImage().execute(“yoururl”);
Don't forget to add these permissions in manifest file
<uses-permission android:name="android.permission.INTERNET"> </uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
//out oncreate
final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/SmartPhoto");
boolean success = false;
//inside oncreate
mSave = (TextView) findViewById(R.id.save);
imageView = (ImageView) findViewById(R.id.header_cover_image);
mSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
saveImage();
}
});
public void saveImage()
{
final Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
final String fname = "image" + n + ".png";
myDir.mkdirs();
File image = new File(myDir, fname);
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(),"Saved", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"not saved", Toast.LENGTH_LONG).show();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
final Uri contentUri = Uri.fromFile(image);
scanIntent.setData(contentUri);
sendBroadcast(scanIntent);
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://mnt/sdcard/" + Environment.getExternalStorageDirectory())));
}
}

Building new directory and pushing files in Android

I have code that I know worked in another project of mine to create a new folder if it didn't already exist and place files from my project into it. But in my new project the code does nothing. What am i doing wrong?
File directory = new File(Environment.getExternalStorageDirectory()
+ File.separator + "testing");
directory.mkdirs();
File directory2 = new File(Environment.getExternalStorageDirectory()
+ File.separator + "CandooData" + File.separator + "Meds");
if (!(directory2.isDirectory())) {
directory2.mkdirs();
}
File directory3 = new File(Environment.getExternalStorageDirectory()
+ File.separator + "CandooData" + File.separator + "Meds");
String[] files;
if (directory3.isDirectory()) {
files = directory3.list();
if (files.length == 0) {
// directory is empty
CopyAssets("medsxml", "/Meds");
}
}
See the log via logcat.
It's possible that you've missed the WRITE_EXTERNAL_STORAGE permission.
mkdirs() will work just fine, not worse than mkdir().
Below is briefly example
File folder = new File(Environment.getExternalStorageDirectory()+"/Trip");
if(!folder.exists()){
folder.mkdir();
}
File newxmlfile = new File(Environment.getExternalStorageDirectory()+"/Trip/"+ RecordID +".xml");
try{
newxmlfile.createNewFile();
}catch(IOException e){
}
use this directory.mkdir(); instead of this directory.mkdirs();
I am using this below method to make directory and save the file in to it.
private static File APP_FILE_PATH = new File("/sdcard/SpeechTutor");
p_file_Side_Slow = new File("/sdcard/SpeechTutor/P_SideMovieSlow.mp4");
p_file_Side_Medium = new File("/sdcard/SpeechTutor/P_SideMovieMedium.mp4");
p_file_Side_Fast = new File("/sdcard/SpeechTutor/P_SideMovieFast.mp4");
p_file_Front_Slow = new File("/sdcard/SpeechTutor/P_FrontMovieSlow.mp4");
p_file_Front_Medium = new File("/sdcard/SpeechTutor/P_FrontMovieMedium.mp4");
p_file_Front_Fast = new File("/sdcard/SpeechTutor/P_FrontMovieFast.mp4");
if((!(p_file_Side_Slow.exists())) || (!(p_file_Side_Medium.exists())) || (!(p_file_Side_Fast.exists()))
|| (!(p_file_Front_Slow.exists()))|| (!(p_file_Front_Medium.exists()))||(!(p_file_Front_Fast.exists()))){
ArrayList<String> files = new ArrayList<String>();
files.add("P_SideMovieSlow.mp4");
files.add("P_SideMovieMedium.mp4");
files.add("P_SideMovieFast.mp4");
files.add("P_FrontMovieSlow.mp4");
files.add("P_FrontMovieMedium.mp4");
files.add("P_FrontMovieFast.mp4");
new myAsyncTask().execute(files);
}
// AsyncTass for the Progress Dialog and to do Background Process
private class myAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {
ArrayList<String> files;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MainScreenActivity.this, "Speech Tutor", "Loading...");
}
#Override
protected Void doInBackground(ArrayList<String>... params) {
files = params[0];
for (int i = 0; i < files.size(); i++) {
copyFileFromAssetsToSDCard(files.get(i));
} return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
// myVideoThumbnail.setImageBitmap((Bitmap)ThumbnailUtils.createVideoThumbnail(p_file_Side_Slow.getAbsolutePath(),MediaStore.Video.Thumbnails.MINI_KIND));
// myVideoView.setVideoURI(p_uri_Side_Medium);
setVideoURI(sideShow, frontshow, slowShow, mediumShow, fastShow);
}
}
// Function to copy file from Assets to the SDCard
public void copyFileFromAssetsToSDCard(String fileFromAssets){
AssetManager is = this.getAssets();
InputStream fis;
try {
fis = is.open(fileFromAssets);
FileOutputStream fos;
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/SpeechTutor",fileFromAssets));
byte[] b = new byte[8];
int i;
while ((i = fis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush();
fos.close();
fis.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
All Above code will save the file as background process.

png downloaded size different to server size?

My app downloads .png files to the sd card for later use. I kept getting OutOfMemoryErrors (if anyone could explain this too, that'd be great!) and so I took a look at the sizes of the images saved to the sd card, and they seem to be roughly double what they are on the server. Why is this, and how can I make them smaller?
public void onCreate(Bundle saved) {
setContentView(R.layout.namedrxnscreen);
TextView t1 = (TextView)findViewById(R.id.rxn_text1);
TextView t2 = (TextView)findViewById(R.id.rxn_text2);
TextView t3 = (TextView)findViewById(R.id.rxn_text3);
TextView t4 = (TextView)findViewById(R.id.rxn_text4);
iv = (ImageView) findViewById(R.id.rxn_image);
pb = (ProgressBar) findViewById(R.id.rxn_loading);
vs = (ViewSwitcher) findViewById(R.id.rxn_switch);
try {
super.onCreate(saved);
[ boring stuff here ]
BitmapDrawable image = getImage(c.getString(5));
if (image != null) {
iv.setImageDrawable(getImage(c.getString(5)));
iv.setBackgroundColor(Color.WHITE);
vs.setDisplayedChild(1);
}
else {
new DownloadTask().execute(c.getString(5));
}
}
catch (ArrayIndexOutOfBoundsException ea) {
error = "bah!";
showDialog(1);
}
catch (Exception ex) {
error = ex.getMessage();
showDialog(1);
}
}
protected class DownloadTask extends AsyncTask<String, Integer, Bitmap> {
#Override
protected Bitmap doInBackground(String... string) {
Bitmap d = null;
try {
DefaultHttpClient dhc = new DefaultHttpClient();
HttpGet request = new HttpGet(HTTP_BASE + string[0] + ".png");
HttpResponse response = dhc.execute(request);
BufferedInputStream webstream = new BufferedInputStream(response.getEntity().getContent());
d = writeToSd(string[0], webstream, d);
}
catch (Exception ex) { errorCatch(ex.getMessage()); }
return d;
}
private Bitmap writeToSd(String string, BufferedInputStream webstream, Bitmap d) {
try {
webstream.mark(3);
webstream.reset();
File f = new File(Environment.getExternalStorageDirectory() + SD_DIR);
f.mkdirs();
File f2 = new File(f, string + ".png");
f2.createNewFile();
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(f2));
int len;
byte[] buffer = new byte[1024];
while ((len = webstream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
webstream.close();
//fos.flush();
fos.close();
FileInputStream fis = new FileInputStream(new File(f, string + ".png"));
d = BitmapFactory.decodeStream(fis);
return d;
}
catch (Exception ex) {
errorCatch(ex.getMessage());
return null;
}
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
iv.setImageBitmap(result);
iv.setBackgroundColor(Color.WHITE);
vs.setDisplayedChild(1);
}
}
}
protected BitmapDrawable getImage(String name) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
//Gets the SD card file, whacks it in a stream
File f = new File(Environment.getExternalStorageDirectory() + SD_DIR, name + ".png");
if (f.exists()) {
InputStream s = new FileInputStream(f);
try {
//Return the decoded bitmap
BitmapDrawable d = new BitmapDrawable(getResources(),
BitmapFactory.decodeStream(s)); //gives an OutOfMemoryError if png > ~30KB
return d;
} catch (OutOfMemoryError ex) {
Toast.makeText(this, "An OutOfMemoryError occured and" +
" the image was loaded at a lower quality.", Toast.LENGTH_SHORT).show();
BitmapFactory.Options mOptions = new BitmapFactory.Options();
mOptions.inSampleSize = 4;
BitmapDrawable d = new BitmapDrawable(getResources(),
BitmapFactory.decodeStream(s, null, mOptions));
return d;
}
}
else return null;
}
catch (Exception ex) {
return null;
}
}
else {
Toast.makeText(this, "External storage not available. Downloading from internet.",
Toast.LENGTH_SHORT).show();
return null;
}
}
The picture downloaded from the server is done byte per byte and cannot be double sized magically...

Categories

Resources