I'm developing music player and I use picture from audio files to display it in UI of my app, if I change music very fast (previous, next button) then I can get java.lang.RuntimeException: Canvas: trying to use a recycled bitmap, but popular players from Play market doesn't have this problem if I change music very fast. How can I avoid this error as well as in other music apps?
Similar question with the same error didn't help me
MediaService class
MediaMetadataRetriever mMetaRetriever = new MediaMetadataRetriever();
mMetaRetriever.setDataSource(songPath);
byte[] art = mMetaRetriever.getEmbeddedPicture();
Bitmap iconUrl = null;
try {
if (art != null) {
iconUrl = BitmapFactory.decodeByteArray(art, 0, art.length);
}
} catch (Exception e) {
}
UI class
try {
// with or without it error happens anyway
/*if (mBitmap != null && !mBitmap.isRecycled()) {
mBitmap.recycle();
mBitmap = null;
mLogo.setImageBitmap(null);
}*/
mBitmap = metadata.getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART);
mLogo.setImageBitmap(mBitmap);
} catch (Exception e) {
}
I just decided to use AsyncTask and cancel execution (mImageViewAsync.cancel(true);) for current instance when a new instance is created and executed, so in this case onPostExecute is triggered less then doInBackground, so now it be difficult for app to crash (but it still can in some cases, but it's not important so)
private ImageViewAsync mImageViewAsync;
private void updateMetaData(MediaMetadataCompat metadata) {
//...
mLogo.setImageBitmap(null);
if (mImageViewAsync != null) {
mImageViewAsync.cancel(true);
}
mImageViewAsync = new ImageViewAsync();
mImageViewAsync.execute(metadata);
}
private class ImageViewAsync extends AsyncTask<MediaMetadataCompat,Void,Bitmap> {
#Override
protected Bitmap doInBackground(MediaMetadataCompat... meta) {
return meta[0].getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
mLogo.setImageBitmap(bitmap);
}
}
Related
I am using WallpaperService to set the live wallpaper on homescreen. I am able to set 10 pics from resources and rotate them,
based on static frequency using thread. I want user to give the option of selecting multiple frequency. I tried to pass the thread sleep duration with user selected frequency. But the thread which is running is neither stopping or updating the values.
Its updating wallpaper with the previous selected frequency. Im stuck with this app from 3 weeks at various levels. I have tried wallpaper manager and setting bitmap with services, alarm manager but all are stopping to set the wallpaper after certain period of time. So finally using Wallpaper service. Help to overcome from this issue.
class WallpaperEngine extends Engine {
//frequency selected by user to update the wallpaper
private final int Wallpaper_DURATION = utils.getFrequency;
private int[] mImagesArray;
private int mImagesArrayIndex = 0;
private Thread mDrawWallpaper;
public WallpaperEngine() {
customWallpaperHelper = new CustomWallpaperHelper(getApplicationContext(), getResources());
mImagesArray = new int[] {R.drawable.one,R.drawable.two,R.drawable.three,R.drawable.four,R.drawable.five};
mDrawWallpaper = new Thread(new Runnable() {
#Override
public void run() {
try {
while (true) {
drawFrame();
incrementCounter();
Thread.sleep(Wallpaper_DURATION);
}
} catch (Exception e) {
//
}
}
});
mDrawWallpaper.start();
}
private void incrementCounter() {
mImagesArrayIndex++;
if (mImagesArrayIndex >= mImagesArray.length) {
mImagesArrayIndex = 0;
}
}
private void drawFrame() {
final SurfaceHolder holder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
drawImage(canvas);
}
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
}
private void drawImage(Canvas canvas)
{
Bitmap image = BitmapFactory.decodeResource(getResources(),
mImagesArray[mImagesArrayIndex]);
Bitmap b=Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), true);
canvas.drawBitmap(b, 0,0, null);
}
In my app i have started download service,it is working fine in background.During download my testing team doing force stop and clear data or Uninstall.But After uninstall or clear data still my Download service is running in background.During download i have installed the same app again but it is misbehaving some thing.While uninstall or clear data or force stop i have to cancel the download How?
public class FileDownloaderService extends IntentService {
private CarcarePreferences preferences;
public FileDownloaderService() {
super("FileDownloaderService");
}
#Override
public void onCreate() {
super.onCreate();
preferences = CarcarePreferences.getCarcarePreferencesObject(getApplicationContext());
DBHelper.getInstance(getApplicationContext()).open();
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
if (extras == null) {
return;
}
if (extras.containsKey("ResultReceiver")) {
resultReceiver = extras.getParcelable("ResultReceiver");
}
if (extras.containsKey("ContentToDownload")) {
contentToDownload = extras.getInt("ContentToDownload");
} else {
return;
}
if (contentToDownload != Carcare.ContentToDownload.IMAGES) {
isDefaultVehicle = extras.getBoolean("IsDefaultVehicle");
fetchVehicle();
}
switch (contentToDownload) {
case Carcare.ContentToDownload.HEADUNIT_IMAGES:
if (extras.containsKey("HeadUnits")) {
headUnits = (ArrayList<Unit>) extras.getSerializable("Units");
downloadHeadUnits();
resultReceiver.send(0, null);
}
break;
}
}
private void fetchVehicle() {
Object[] objects;
if (isDefaultVehicle) {
objects = DBAdapter.getAllVehicles(preferences.getDefaultModel(),
preferences.getDefaultYear(), isDefaultVehicle);
} else {
objects = DBAdapter.getAllVehicles(preferences.getCurrentModel(),
preferences.getCurrentYear(), isDefaultVehicle);
}
vehicle = (Vehicle) objects[0];
}
private void downloadHeadUnits() {
mHeadUnitDir = SdUtils.getDir(this);
//clearHeadUnits();
for (CUnit unit : Units) {
String fileName = mDir + "/" + unit.getGuid() + ".png";
InputStream stream = null;
final HttpGet httpRequest = new HttpGet(unit.getHuImageUrl());
httpRequest.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
try {
File file = new File(fileName);
if (!file.exists()) {
FileOutputStream out = new FileOutputStream(file); //openFileOutput(fileName);
stream = new DefaultHttpClient().execute(httpRequest).getEntity().getContent();
Bitmap bitmap = BitmapFactory.decodeStream(stream);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (IllegalStateException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void download() {
cancelDownload(Carcare.FileType.QRG, vehicle.getPath());
deleteDoc(vehicle.getQRGPath());
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(vehicle.getUrl()));
request.setDestinationUri(Uri.parse(vehicle.getPath()));
request.setTitle("Unit");
request.setDescription("Quick Reference Guide");
preferences.setDownloadID(Carcare.FileType.QRG, downloadManager.enqueue(request));
}
}
You must use a Service.
In the Service's onDestroy(), you can write the code to finish the DownloadManager.
The Service will be killed before the app is about to uninstall.
This way the Download will stop.
Take a look at the remove() method of the DownloadManager.
It says:
public int remove (long... ids) Added in API level 9
Cancel downloads and remove them from the download manager. Each
download will be stopped if it was running, and it will no longer be
accessible through the download manager. If there is a downloaded
file, partial or complete, it is deleted. Parameters ids the IDs of
the downloads to remove Returns
the number of downloads actually removed
Edit
To intercept your application uninstall take a look at this answer.
I am trying to display the images in galleryViews which are in ListView. I am downloading images from server to SDCard and then displaying it, first I am checking images in cache if image is not there then I am loading it from sdcard.
when the user starts the app for the first time I am downloading the images from server and saving them to sdcard in the mean time iam showing the activity with text only
I want if the image is not there in sdcard the after downloading the image it should display the image as soon as the image is download here is what I am doing.
public class AsyncImageLoader {
private boolean isImageView;
private final LinkedHashMap<String, Bitmap> cache =
new LinkedHashMap<String, Bitmap>(60, (float) 1.0, true);
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
LoadImageFromSdCard loadImage = (LoadImageFromSdCard) msg.obj;
if (isImageView) {
loadImage.imageView.setImage(loadImage.bmp);
} else {
Thread thread = new Thread(new LoadImageFromSdCard(loadImage.uri, loadImage.imageView));
try {
Log.i("AsyncImageLoader", "SECOND THREAD STARTED");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.start();
}
}
};
public Bitmap loadImage(String uri,
ImageTextComboControl imageView) {
if (cache.containsKey(uri)) {
return cache.get(uri);
} else {
handler.post(new LoadImageFromSdCard(uri, imageView));
}
return null;
}
private class LoadImageFromSdCard implements Runnable {
String uri;
ImageTextComboControl imageView;
ImageView image;
Bitmap bmp = null;
public LoadImageFromSdCard(String uri, ImageTextComboControl imageView) {
this.uri = uri;
this.imageView = imageView;
}
public void run() {
FileInputStream fis;
try {
fis = new FileInputStream(new File(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
bmp = BitmapFactory.decodeStream(fis);
if (imageView != null) {
isImageView = true;
cache.put(uri, bmp);
Message message = new Message();
message.obj = this;
handler.sendMessage(message);
}
}
}
}
Thanx
Is much better use Async Task class http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html (using AsyncTask section) and, important, take care about large bitmap
http://developer.android.com/training/displaying-bitmaps/index.html
I solved my problem using onContentChanged() method in adapter. I am saving images to sdCard and getting the sdCard path saving it into sqlite database so when ever the data is changing in sqlite database onContentChanged method is called because I am using Cursor Adapter.
My app is a Wifi chat app with which you can communicate between two Android units with text messages and snap camera pictures and send them. The pictures are stored to the SD-card.
I used to have an OutOfMemoryError thrown after a couple of sent images, but I solved that problem by sending the
options.inPurgeable = true;
and
options.inInputShareable = true;
to the BitmapFactory.decodeByteArray method. This makes the pixels "deallocatable" so new images can use the memory. Thus, the error no longer remains.
But, the internal memory is still full of images and the "Low on space: Phone storage space is getting low" warning appears. The app no longer crashes but there's no more memory on the phone after the app finishes. I have to manually clear the app's data in Settings > Applications > Manage Applications.
I tried recycling the bitmaps and even tried to explicitly empty the app's cache, but it doesn't seem to do what i expect.
This function receives the picture via a TCP socket, writes it to the SD-card and starts my custom Activity PictureView:
public void receivePicture(String fileName) {
try {
int fileSize = inStream.readInt();
Log.d("","fileSize:"+fileSize);
byte[] tempArray = new byte[200];
byte[] pictureByteArray = new byte[fileSize];
path = Prefs.getPath(this) + "/" + fileName;
File pictureFile = new File(path);
try {
if( !pictureFile.exists() ) {
pictureFile.getParentFile().mkdirs();
pictureFile.createNewFile();
}
} catch (IOException e) { Log.d("", "Recievepic - Kunde inte skapa fil.", e); }
int lastRead = 0, totalRead = 0;
while(lastRead != -1) {
if(totalRead >= fileSize - 200) {
lastRead = inStream.read(tempArray, 0, fileSize - totalRead);
System.arraycopy(tempArray, 0, pictureByteArray, totalRead, lastRead);
totalRead += lastRead;
break;
}
lastRead = inStream.read(tempArray);
System.arraycopy(tempArray, 0, pictureByteArray, totalRead, lastRead);
totalRead += lastRead;
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pictureFile));
bos.write(pictureByteArray, 0, totalRead);
bos.flush();
bos.close();
bos = null;
tempArray = null;
pictureByteArray = null;
setSentence("<"+fileName+">", READER);
Log.d("","path:"+path);
try {
startActivity(new Intent(this, PictureView.class).putExtra("path", path));
} catch(Exception e) { e.printStackTrace(); }
}
catch(IOException e) { Log.d("","IOException:"+e); }
catch(Exception e) { Log.d("","Exception:"+e); }
}
Here's PictureView. It creates a byte[ ] from the file on the SD-card, decodes the array to a Bitmap, compresses the Bitmap and writes it back to the SD-card. Lastly, in the Progress.onDismiss, the picture is set as the image of a full screen imageView:
public class PictureView extends Activity {
private String fileName;
private ProgressDialog progress;
public ImageView view;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
Log.d("","onCreate() PictureView");
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
view = new ImageView(this);
setContentView(view);
progress = ProgressDialog.show(this, "", "Laddar bild...");
progress.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
File file_ = getFileStreamPath(fileName);
Log.d("","SETIMAGE");
Uri uri = Uri.parse(file_.toString());
view.setImageURI(uri);
}
});
new Thread() { public void run() {
String path = getIntent().getStringExtra("path");
Log.d("","path:"+path);
File pictureFile = new File(path);
if(!pictureFile.exists())
finish();
fileName = path.substring(path.lastIndexOf('/') + 1);
Log.d("","fileName:"+fileName);
byte[] pictureArray = new byte[(int)pictureFile.length()];
try {
DataInputStream dis = new DataInputStream( new BufferedInputStream(
new FileInputStream(pictureFile)) );
for(int i=0; i < pictureArray.length; i++)
pictureArray[i] = dis.readByte();
} catch(Exception e) { Log.d("",""+e); e.printStackTrace(); }
/**
* Passing these options to decodeByteArray makes the pixels deallocatable
* if the memory runs out.
*/
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
options.inInputShareable = true;
Bitmap pictureBM =
BitmapFactory.decodeByteArray(pictureArray, 0, pictureArray.length, options);
OutputStream out = null;
try {
out = openFileOutput(fileName, MODE_PRIVATE);
/**
* COMPRESS !!!!!
**/
pictureBM.compress(CompressFormat.PNG, 100, out);
pictureBM = null;
progress.dismiss(); }
catch (IOException e) { Log.e("test", "Failed to write bitmap", e); }
finally {
if (out != null)
try { out.close(); out = null; }
catch (IOException e) { }
} }
}.start();
}
#Override
protected void onStop() {
super.onStop();
Log.d("","ONSTOP()");
Drawable oldDrawable = view.getDrawable();
if( oldDrawable != null) {
((BitmapDrawable)oldDrawable).getBitmap().recycle();
oldDrawable = null;
Log.d("","recycle");
}
Editor editor =
this.getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
}
}
When the user presses the back key, the picture isn't supposed to be available anymore from within the app. Just stored on the SD-card.
In onStop() I recycle the old Bitmap and even try to empty the app's data. Still the "Low on space" warning appears. How can I be sure the images won't allocate the memory anymore when they're not needed?
EDIT: It appears the problem is the compress method. If everything after compress is commented, the problem remains. If I delete compress, the problem disappears. Compress seems to allocate memory that's never released, and it's 2-3 MB per image.
Ok, I solved it. The problem was, I was passing an OutputStream to compress, which is a stream to a private file in the app's internal memory. That's what I set as the image later. This file is never allocated.
I didn't get that I had two files: one on the SD-card and one in the internal memory, both with the same name.
Now, I'm just setting the SD-card file as the ImageView's image. I never read the file into the internal memory as a byte[], thus never decoding the array to a bitmap, thus never compressing the bitmap into the internal memory.
This is the new PictureView:
public class PictureView extends Activity {
public ImageView view;
private String path;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
Log.d("","onCreate() PictureView");
path = getIntent().getStringExtra("path");
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
view = new ImageView(this);
setContentView(view);
Uri uri = Uri.parse( new File(path).toString() );
view.setImageURI(uri);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Log.d("","Back key pressed");
Drawable oldDrawable = view.getDrawable();
if( oldDrawable != null) {
((BitmapDrawable)oldDrawable).getBitmap().recycle();
oldDrawable = null;
Log.d("","recycle");
}
view = null;
}
return super.onKeyDown(keyCode, event);
}
}
Is it bad practice to put an external file as the image of an ImageView? Should I load it into internal memory first?
If you specifically want the image to be nullified from memory for sure when a user presses back you could override the back button and make your image clean up calls there. I do that in some of my apps and it seems to work. maybe something like this:
#Override
protected void onBackPressed() {
super.onBackPressed();
view.drawable = null;
jumpBackToPreviousActivity();
}
Im pretty sure there are some view methods that clear other caches and things like that. You can recycle the bitmap but that doesnt guarantee that it will be dumped right then but only at some point when the gc gets to it.....but Im sure you probably know that already :)
EDIT: You could also do the same thing in the onPause method. That one is guaranteed to get called. The other two may never get called according to the android docs.
http://developer.android.com/reference/android/app/Activity.html
I'm writing a livewallpaper that will pull images from flickr and make them the background, and change every so often. Right now i've stubbed/ignored/circumvented the flickr part, and am ignoring the timed changes as well. Still i'm having the same null pointer error over and over and i can't figure out what's causing it.
here is the few methods related to the error
#Override
public void onVisibilityChanged(boolean visible) {
mVisible = visible;
if (visible) {
setImage(getPic());//***NULLPOINTERERROR
} else {
mHandler.removeCallbacks(getFlickrPic);
}
}
public void setImage(Bitmap bm)
{
final SurfaceHolder holder = getSurfaceHolder();
Canvas c= null;
try{
c=holder.lockCanvas();
if (c != null) {
c.setBitmap(bm);
}
} finally { if (c != null) holder.unlockCanvasAndPost(c); }
}
public Bitmap getPic()
{
Bitmap bm = null;
bm = ((BitmapDrawable) LoadImageFromWebOperations("http://farm6.static.flickr.com/5102/5655314644_b7038a5438_z.jpg")).getBitmap();
while (bm==null)
{bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.no)).getBitmap();}
return bm;
}
private Drawable LoadImageFromWebOperations(String url)
{
try
{
InputStream is = (InputStream) new URL(url).openStream();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
I keep getting a NullPointerException for method getPic() in the OnVisibilityChanged(visible) method, noted with the *comment.
If any more information is necessary please ask. like i said i don't know why it's giving me this error so there's a possibility it's something from code i haven't included.
thanks!
Wow thats that for a construct?
while (bm==null) {
bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.no)).getBitmap();
}
That looks evil...
Anyway, your issue is the following line:
bm = ((BitmapDrawable) LoadImageFromWebOperations("http://farm6.static.flickr.com/5102/5655314644_b7038a5438_z.jpg")).getBitmap()
LoadImageFromWebOperations can return null. In that case you still call getBitmap() on a null reference...
LoadImageFromWebOperations returns null if an error occures. in getPic you try to call getBitmap() on the return value of LoadImageFromWebOperations - if the value returned is null
you are trying to call getBitmap() on a null-object, which will cause your NPE