Do you know good practices to avoid memory leaks ?
I am currently working on an app which has few memory leaks, that I struggle to fix, mainly because I don't know the habits that I need to take to be able to avoid them.
For instance, at the moment I get this issue
Fatal Exception: java.lang.OutOfMemoryError
Failed to allocate a 1627572 byte allocation with 1293760 free bytes and 1263KB until OOM
Raw Text
dalvik.system.VMRuntime.newNonMovableArray (VMRuntime.java)
android.view.LayoutInflater.inflate (LayoutInflater.java:429)
com.XX.Dialog.PopupDialog.onCreateView (PopupDialog.java:50)
Which comes from the inflater.inflate(R.layout.dialog_popup, container, false); in the onCreateView !
Here is the DialogFragment concerned :
public final class PopupDialog extends DialogFragment {
public PopupDialog()
{
}
#Override
public void onSaveInstanceState(Bundle outState) {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
View view = inflater.inflate(R.layout.dialog_popup, container, false);
return view;
}
The layout is quite long, but basically it got 5 ImageViews . Here is an sample :
<ImageView
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="#+id/popup_top_bg_iv"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="false"
android:layout_alignParentStart="false"
android:src="#drawable/popup_top_bg"
android:scaleType="fitXY"
android:background="#color/transparent" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/popup_top_bg_iv"
android:background="#ffffff"
android:layout_alignBottom="#+id/popup_bottom_ll" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/popup_top_iv"
android:src="#drawable/popup_0_top"
android:scaleType="fitCenter"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
....
So .... I was wondering if you know :
1. What could lead to this memory leak error from this dialogFragment ?
2. Any good practices in android to avoid memory leaks ?
For instance for that file, should I call
imageView.setImageDrawable(null);
On every Imageview when the popup is closed / Activity is closed (R.drawable.* ) ? Or just when I load an image from an URL (with Glide for instance) dynamically ?
Should I always resize an image to the dimension of my Imageview ?
What exactly do I need to clean after the Fragment/Activity is closed ?
What do you think ?
After a bit of digging I came with these solutions :
you can use Leak canary to track your memory leak (https://github.com/square/leakcanary)
Or the Memory monitor of Android studio : https://developer.android.com/studio/profile/am-memory.html
Use a library to load your images such as Picasso or Glide. Personally I prefer Glide.
https://medium.com/#multidots/glide-vs-picasso-930eed42b81d
Never keep references of Activity of context in static. NEVER!
Otherwise your references might still be there even if you need it.
Avoid keeping references of ImageViews. Recycle / Clear the bitmap inside when your destroy the view.
If you need to have a reference of the context, please use context.getApplicationContext();
Don't use context.getApplicationContext(); for LayoutInflater.from(context); but directly the context.
(in case if you need to inflate a view or need a context for something).
If you use the context.getApplicationContext() it can lead to some design issues if you create views dynamically.
If you get some OutOfMemory error, think to compress your images ! It actually saves me lot of OutOfMemory error. You can use https://tinypng.com/.
Don't put by default your images into the folder drawable-xhdpi but drawable-mdpi instead as drawable-mdpi is the default one.
So for my issue I just need to compress the images and put them back in the drawable-mdpi folder ! All good now !
I'm trying to make a game like a "click & kill" and I'm trying to make a health bar for the character to kill.
I'm using a simple image (a red rectangle) and I would like to reduce the health bar after one click. What I tryed works but the problem is not just the with decrease, the height too. So the result is really horrible. To begin, this is my XML (I only show one for example):
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="33">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFF00"
android:id="#+id/hole4"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/healthBar4"
android:src="#drawable/health_bar"/>
</RelativeLayout>
So here nothing bad (I think) I leave android:adjustViewBounds="true" because I thought the problem came from here.
Next is my Activity :
final int healthBarHeightInitial = healthBar4.getLayoutParams().height;
final int healthBarWidthInitial = healthBar4.getLayoutParams().width;
healthBar4.requestLayout();
//ivHole4 is my ImageView I get the click to leave some life to the character
ivHole4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//If character die (works great).
if(choixAction.ChoixAction(CharaHole4,outil)){
Log.d("Perso","Character is die");
mAvancement +=1;
ivHole4.setImageResource(0);
CharaHole4 = null;
placeChara.setHole4(true);
healthBar4.setVisibility(View.GONE);
healthBar4.getLayoutParams().height = healthBarHeightInitial;
healthBar4.getLayoutParams().width = healthWidthInitial;
}
//if character don't die (here is the problem !)
else {
healthBar4.getLayoutParams().width = healthBar4.getWidth()/2; //This is works great
healthBar4.getLayoutParams().height = healthBarHeightInitial; //This is do nothing, the height is /2 too.
healthBar4.requestLayout();
}
}
});
I hope someone know how to change the image size not proportionally.
Thank's advance.
Your ImageView in the XML Layout needs to set the scale type to fitXY to allow it to expand without keeping proportions.
android:scaleType="fitXY"
Use Picasso Library and set Crop Center.
I am loading 400x200 images in RecyclerView, but scrolling is laggy on 2k devices. I am using Picasso for loading images from resource.
As you can see in the demo images are blurry on 2k screen, but if I load higher resolution images the situation gets worse.
How to fix this, I am not even loading large image, its 400x200 ?
Demo
Here is my code
card_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
card_view:cardPreventCornerOverlap="false"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
card_view:cardCornerRadius="2dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/rel">
<ImageView
android:id="#+id/cardimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="#drawable/p7"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="title"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="24dp"
android:textStyle="bold"
android:textSize="24sp"
android:id="#+id/cardtitle"
android:layout_gravity="center_vertical"/>
</LinearLayout>
</android.support.v7.widget.CardView>
Myadapter Code
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private Context mContext;
List<Flower> list = new ArrayList<>();
public CardAdapter(Context mContext, List<Flower> list) {
this.mContext = mContext;
this.list = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.Flower=getItem(position);
holder.cardtitle.setText(list.get(position).name);
Picasso.with(mContext)
.load(list.get(position).id)
.placeholder(R.drawable.ic_launcher)
.into(holder.cardimage);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return list.size();
}
public Flower getItem(int i) {
return list.get(i);
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView cardimage;
TextView cardtitle;
Flower Flower;
public ViewHolder(View itemView) {
super(itemView);
cardimage = (ImageView) itemView.findViewById(R.id.cardimage);
cardtitle = (TextView) itemView.findViewById(R.id.cardtitle);
}
}
}
UPDATE: I am loading images from resource, I am not downloading nothing
Here is my array
private void initializeData() {
flowers = new ArrayList<>();
flowers.add(new Flower("Flower 1", R.drawable.p8));
flowers.add(new Flower("Flower 2", R.drawable.p10));
flowers.add(new Flower("Flower 3", R.drawable.p11));
flowers.add(new Flower("Flower 4", R.drawable.p8));
flowers.add(new Flower("Flower 5", R.drawable.photo2));
flowers.add(new Flower("Flower 6", R.drawable.photo6));
flowers.add(new Flower("Flower 7", R.drawable.p12));
flowers.add(new Flower("Flower 8", R.drawable.p9));
flowers.add(new Flower("Flower 9", R.drawable.p8));
flowers.add(new Flower("Flower 10", R.drawable.p8));
flowers.add(new Flower("Flower 11", R.drawable.p8));
flowers.add(new Flower("Flower 12", R.drawable.p10));
}
UPDATE 2 : Guys I fixed most of the lag by setting adapter.setHasStableIds(true) , but app is still laggy on the first scroll while images are not loaded yet, how to fix that ?
UPDATE 3: I just tried loading images from web and everything seems smooth, probably there is some problem with loading images from resource .
Ok, thank you guys, I am gonna load my images from web.
if you are using two or more recycler views like (RecyclerView and NestedView)
try this
recyclerView.setNestedScrollingEnabled(false);
Source : Recyclerview inside Nested Scrollview scroll but does not fast scroll like normal Recyclerview or Nested Scrollview
Is RecyclerView.setHasFixedSize() set to true? I'm not able to reproduce this lag...can you please post the whole project on git? Check this out, maybe it can help you: http://antonioleiva.com/recyclerview/
I Believe that sometimes you may piss off when only trying some static images in drawable to display your recycler view. And it happens extremely lagging.
Why? You may not get this issue when using some library to load an image from url (Picasso, Glide, ...), but what happens with the same image, the same size, and it's right in your drawable (not need to download at all). And after a while, I figure out, android did some trick to resize an image in drawable for us to get a proper image in different resolution devices. So my suggestion is to use drawable-nodpi to store your image in order for android not to interfere with our images.
This is because the image is taking time to load.
Firstly, change your code for loading image as the below one...
Picasso.get().load(list.get(position).id).fit().centerCrop()
.placeholder(R.drawable.ic_launcher)
.into(holder.cardimage);
Then, before setting the adapter on recyclerview to the instance of CardAdapter inside MainActivity add this line..
yourAdapter_name.setHasStableIds(true);
One more tip...If anyone is using large drawables (xxxhdpi, xxhdpi ), first convert them into mdpi or ldpi . This will also improve the performance a lot and also reduces the apk size.You can use this website NativeScript Image Builder
This could be because of Picasso taking time to load the image. Use the below snapshot and adjust accordingly.
Picasso.with (context)
.load (url).fit().centerCrop()
.error (R.drawable.UserImage)
.into (imageView);
Use fit() and centerCrop() to avoid legginess.
You need to be getting the images asynchronously. As it is now, it stalls to actually download the image.
Leave the imageview blank when it's created, but have some sort of listener to set the image when it's been downloaded.
if you use Recyclerview in vertical mode and your activity contains other item that you have ScrollView then you must use NestedScrollView instead of ScrollView.
as described in google documentation NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. Nested scrolling is enabled by default.
I had laggy recyclerView issue when one of the textView within the recyclerView was receiving null values. I fix this and my recyclerView stopped lagging.
It might be late, but maybe somebody will find it useful. Had the same problem, problem was at line:
Picasso.get().load(image).into(holder.imageView);
so I added fit().centerCrop() like this:
Picasso.get().load(image).fit().centerCrop().into(holder.imageView);
That solved my problem
I am bit late but this can be fixed bu using thumbnail with Glide.
Glide.with(context)
.load(URL)
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.thumbnail(0.5f)
.centerCrop()
.into(imageView);
In my case, bitmap creation was making delay for scroll. So I put bitmap creation in background thread and set to image in UI thread. This way, UI is not blocked for bitmap creation
new Thread(new Runnable() {
#Override
public void run() {
Bitmap myBitmap = BitmapFactory.decodeFile(filepath);
activity.runOnUiThread(new Runnable() {
public void run() {
vItem.imgProfile.setImageBitmap(myBitmap);
}
});
}
}).start();
from my experience with recyclerview what i found the possible cause could be is the image size.
beside that adding property ( setNestedScrollingEnabled(false); ) to the recyclerview and ( setHasStableIds) to the adapter does help to make recyclerview work smoothly.
So, bottom line is, if your recyclerview has image to load from network make sure to override their size or use thumbnail property(in glide).
this tricked saved my life and i hope it might save others life as well.
Happy coding :)
A bit late but I found leveraging Kotlin Coroutines as an effective way to make your onBindViewHolder() calls cheap, by offloading your image loading on to a background thread. I use Glide to load 384x384 images and the scrolling is smooth for upto a couple of thousand images.
// Here, defaultScope = CoroutineScope(Dispatchers.Default + SupervisiorJob())
// Key idea is to launch the Glide call on a background thread.
defaultScope.launch(exceptionHandler) {
Glide.with(view)
.load(uri)
.also {
// When Glide is done preparing the resource,
// use Main thread to load into ImageView.
withContext(Dispatchers.Main) {
it.into(view)
}
}
}
For Picasso, it will be a similar thing (though I haven't tried it personally), where into() must be invoked from the Main thread and the preparation on the background thread.
I think the reason is that Picasso caches your images but since you have a list of drawables that you bundle together with your app, you do not in theory need to cache your images. Caching is only useful when you are downloading the image from the internet and you don't want the app to redownload the images each time you swipe up or down on the recyclerview.
I would adjust the way picasso works by changing the memorypolicy so try this instead :
Picasso.with(getContext()).load(data.get(pos).getFeed_thumb_image()).memoryPolicy(MemoryPolicy.NO_CACHE).into(image);
This question comes up quite often, however in all examples i have found, the image src is defined in the XML. e.g android:src="..."
My code doesn't specificy the src untill the activity, using ImageButton.setImageResource() as it is a single button, performing play/stop
How do i fill the ImageButton with the src, when src is defined later?
I tryed ImageButton.setScaleType="fitXY", however sdk doesn't like it using string...
UPDATE: After trying to use the suggested below, the problem still occurs. here is more explanation to help
<ImageButton
android:id="#+id/imgStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
public class MainActivity extends Activity{
private ImageButton player;
protected void onCreate(){
player = (ImageButton) findViewById(R.id.imgStart);
...
if(isPlaying){
player.setImageResource(bitmap image);
}
else{
player.setImageResource(different bitmap image);
}
...
}
Use ScaleType.CENTER_CROP instead
player .setScaleType(ImageView.ScaleType.CENTER_CROP);
It seems CENTER_CROP works as fit_xy.
but, it's not sure why it does..
Please try below code to set ScaleType programatically
ImageButton object".setScaleType(ScaleType.FIT_XY)
"ImageButton object" should be object of class ImageButton
(that you defined probably in xml).
Do it this way
ImageButton object.setScaleType(ScaleType.FIT_XY)
Use ScaleType.FIT_XY instead of fitXY in your code
ImageButton.setScaleType="fitXY"
yes this will not work, because you have to use it properly using below code also should setAdjustViewBounds to true.like this:
player.setAdjustViewBounds(true);
player.setScaleType(ScaleType.FIT_XY);
This will definitely work!
I have problems with lagg when scrolling and space between listItems. If anybody could give me a hint on what's wrong with my code I would be really greatfull.
When my app starts I download all thumbnails from my server and save them like this:
FileOutputStream fos = openFileOutput(uniqueName, Context.MODE_PRIVATE);
fos.write(bytes);
fos.close();
All the images are 100px x 75px
ListItem:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/pic"
android:layout_width="100dp"
android:layout_height="75dp">
</ImageView>
</RelativeLayout>
I then load the images with asyncTask like this:
private Drawable d;
#Override
protected Integer doInBackground(String... arg0) {
File filePath = ctx.getFileStreamPath(fileName);
if (filePath.exists()) {
d = Drawable.createFromPath(filePath.toString());
return 1;
}
return 0;
}
#Override
protected void onPostExecute(Integer success) {
if (success == 1) {
listener.onCacheThumbCompleted(d);
}
}
Finally add the image to imageView in listItem:
public void onCacheThumbCompleted(Drawable drawable) {
iv.setImageDrawable(drawable);
}
But it's not smooth at all when scrolling. Also it seems that the image does not fill the imageView completely. It's a space between the listItems even if I set the dividerHeight to 0.
Same problem and he solved it by resizing his images, but do I need to resize/scale my images to fix my problems?
Smooth ListView can be quite complex on Android. The best example I've found is Shelves by Romain Guy. It features a lot of complex patterns and can be hard to digest but if you do digest everything you'll be a lot smarter when you come out on the other side :)
To list some of most important enhancements:
Lazy load of images
ViewHolder
Resizing of images
You could also search for these enhancement features and implement them yourself.
Try using LAZYLIST/ LAZY-LOADING if you have a lot of images.