0

I was thinking to use a infinite list using either (Recyclerview or Listview) and the data to be provided by an ArrayList. (Object- a model class)

So for infinite list Arraylist size will increase and so is the memory occupied by list also increases. So how will the app behave, will it not create out of memory exception or will it not hang.

I just want to know the concept that works on this, and if it creates Exception- let me know how can we handle that to.

Rahul
  • 395
  • 5
  • 20
  • 1
    just to be precise, in the case of `ArrayList` infinite means `Integer.MAX_VALUE - 8` – Blackbelt Nov 16 '16 at 09:44
  • If you use a Collection without a limit (see Blackbeld comment), infinite will always cause a `OutOfMemoryError` since the memory is finite. You will need to clear some unused/unseen values. – AxelH Nov 16 '16 at 09:50

2 Answers2

0

Your app very likely will throw an OOM exception, and the way to handle it is the following:

try {
    // fill your infinite list as you want
} catch (OutOfMemoryError E) {
    //release some/all objects from your list, f.e., the first 100 ones or so
}

I hope it helps.

kelmi92
  • 394
  • 2
  • 8
  • This would probably not be enough since this might cause other error. `Error` are not suppose to be catched – AxelH Nov 16 '16 at 09:51
  • It is enough, trust me, and it is very easy to try it, create an ArrayList of any type and add it values inside a while(true) – kelmi92 Nov 16 '16 at 09:56
  • Yep, in a simple program like this. Other threads of this app might be impacted since the will share memory. So a lot could crash. Never try to recover from an Error (exception some cases). [Some reading](http://stackoverflow.com/a/8729011/4391450) – AxelH Nov 16 '16 at 10:00
0

Check that the list taken memory is smaller than the available memory before attempting to load it in recycler view. So the most efficient way to handle OutOfMemoryException is to architecture your application in such a way that it never attempts to load lots of data into memory in order to avoid the exception.

I don't thing list which you are using have items more than 500 or 1000. so you don't have to worry because it will be in your in memory cache. but the actual problem occure when you are loading images inside recycler view and that time you need to recycler your views continuously.

Also in application class you are getting callback when you don't have enough memory

@Override
public void onLowMemory() {
    super.onLowMemory();
}

please let me know if you still have any questions.

Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147