loading high amounts of views programmatically in android? - android

I have a for loop within a for loop within a for loop (3 for loops). Each for loop loads at least one view in them some load more than 1. All of the views(textviews, imageviews) are loaded into a relative layout or a linear layout and those layouts are all loaded into one linear layout and all of that is in a scrollview.
I know confusing and probably the worst way to do this. I have looked up different things most of them are listview related such as the endless adapter or lazy loading. I don't think listview will work for what i am trying to do. I have memory problems doing it this way.
So I guess what my question is will ListView be the right direction to go? Will i still be able to use my for-for-for loops?
Consider each block to represent a layout (each of layout consist of textviews, only the black boxes have imageviews and textviews) and also consider each color to represent a for loop. The black borders represent the linear layout that all of these views and other layouts get shoved into. Keep in mind it's not always going to be the same amount of black boxes beneath the red and blue boxes

i don't know if i really got what you want do here but in my opinion u should use an Adapter.
Doing this with layouts as you stated cause memory problems because you are loading a complex hierarchy of views, android is drawing all the views (even the ones that are not visible yet) and none of your views are reused.
Using a ListView and defining different types of AdapterView you should be able to do what you need.
For instance lets say each red box is one AdapterView. So from your scheme you'll have 2 AdapterView, lets call them "ViewOneBlueTwoBlack" and "ViewOneBlueThreeBlack". Also lets say you have more types of AdapterViews "ViewTwoBlueTwoBlack", "ViewTwoBlueFiveBlack", etc...
Now what you need to do is handle in your Adapter the conditions to know when each type of AdapterView should be load.
Or even better if you consider that the redboxes are sections and then the blue boxes become your AdapterViews.
You can find a nice tutorial on ListViews and Adapter here : http://www.vogella.com/tutorials/AndroidListView/article.html
Also your scheme looks a lot like a ExpandableListView check it out just in case.

You should definitly used a ListView and an adpater.
You can have diffenet view type in your ListView. To do so you should have an adapter like this :
public class YourAdapter extends BaseAdapter {
private static int HEADER_TYPE = 0;
private static int CONTENT_TYPE_1 = 1;
private static int CONTENT_TYPE_2 = 2;
#Override
public int getViewTypeCount() {
return 3;
}
#Override
public int getItemViewType(int position) {
if (header)
return HEADER_TYPE;
else if (content_type_1)
return CONTENT_TYPE_1;
else
return CONTENT_TYPE_2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position) == HEADER_TYPE) {
//make header view
} else if (getItemViewType(position) == CONTENT_TYPE_1 {
//make content view
//be careful position is the position in the list view
} else {
//make content view
//be careful position is the position in the list view
return convertView;
}
}
You should be careful when accessing your datas in getView, the postion is the position in the ListView.

I would suggest you to use a table layout for this. Declare a table layout in your xml file, and add views dynamically.
I gave a similar answer here, you can customize the solution to have only one view in row and align accordingly.

"So I guess what my question is will ListView be the right direction to go? Will i still be able to use my for-for-for loops?"
Answer is, right direction depends upon your scenario if your objective can be achieved with both then see which method has least views or widgets in your case there are many layouts but if you use ListView there might be one. Bt in developing the best way is any way which fullfil customer's requirements..

Related

Avoid recycling of the items in the Recyclerview

I have a recycler view which contains different types of views. There are only 8 items in the recycler view and i don't want to recycle those views on scrolling. How to disable the recycling feature of the recycler view?
Or is there any better method to approach this?
Have you considered using ScrollView instead? You could include the different layout types you want to use inside the ScrollView, and there you would not get recycling behavior.
If that is not good enough, than I would sudgest to stick with recycler view, and not worry about views getting recycled, because it is not much of a big deal.
But if you are still convinced that you need a recycler view without the recycling behavior, you could try viewHolder.setIsRecyclable(false); on every viewholder instantiation, that way they won't get recycled.
Set the below line in your activity
recyclerView.getRecycledViewPool().setMaxRecycledViews(1,0);
set Below Code in RecyclerViewAdapter class
#Override
public int getItemViewType(int position) {
return 1;
}

Reuse dynamic views within a ListView item

In Android, the ListView and RecyclerView reuses view objects when the user scrolls to improve efficiency by not inflating / creating the view objects over and over again.
This is straight forward for any simple lists, but my use case is a bit different. Each item in the list has another list of other items, you can think of it as a list of posts and each post has a list of tags. It can be visualized as follows:
-------------
Post 1
<Tag1> <Tag2> <Tag3>
-------------
Post 2
<Tag4>
-------------
Post 3
<Tag5> <Tag6>
-------------
Since each post has a variable number of tags, it is not as trivial if we want to reuse a set tag view objects across different ListView item.
My current approach to this problem is that there is an implementation of ReusableViewPool which acts as a pool of reusable tag view objects in the above case where each ListView item can get view object from the pool and return unused view object back to the pool. The interface is like:
public interface ReusableViewPool {
View get();
void recycle(View v);
}
In the ListAdapter or RecyclerView.Adapter, it works like:
public View getView(int position, View convertView, ViewGroup parent) {
// return extra tag views to the pool
// add missing tag views from the pool
// update the tag views
}
The approach works fine, but I think this is quite troublesome for a common problem.
So the question is, what approach will you guys take to solve the problem? Do you have any elegant solution in mind?
Thanks.
I have used this technique in the past, I think it's a valid design.
In your case, I might consider a different approach: having a single TextView and making a single SpannableString containing all the tag names, marked up to give the proper look. A lot of it depends on your implementation, though:
Layout/Overflow -- does the tag section have a sort of flow layout or do you have a horizontal scroll to keep all the tags on a single line?
Graphics -- do you have icons interspersed between the names? Do they have different colors or shapes depending on the tag type?
Typography -- do the tag names have different styles or colors depending on the tag type?
If you update your question with some details and preferable some images/screenshots, I can add some sample code.

change color of item in listview (without click)

I've tried to change the background color of specific items in a ListView.
first, catch it from database:
ListAdapter adapter = new ArrayAdapter(getApplicationContext(),
android.R.layout.simple_list_item_1, db.getAllApps());
final ListView list = (ListView) findViewById(R.id.ListViewApps);
list.setAdapter(adapter);
then I will set all apps in different color, if they have the tag activated
// if app is activated in db --> set another colour in ListView
private void setAppCheck(ListView list) {
List<String> apps = db.getAllApps();
for (int i = 0; i < list.getCount(); i++) {
if (db.appActivated(apps.get(i)).equals("activated")) {
list.setBackgroundColor(0xffaaaaaa); // it changes ALL items...
} else {
// do nothing
}
}
}
And there is Problem, with list.setItemChecked(i, true) I can change it with a specific position, but how do I change the Background color of the specific Item in the ListView?
Hope you can help me.
The cleanest way to do what you're trying to do is writing your own CursorAdapter supporting two view types: activated apps and deactivated apps. Then in your getView method, when you're inflating your views, you can set the background color accordingly.
Having two item types will make the Android framework automatically pass only convert views of the correct type to getView, so the only time you need to check for the type is during creation.
You may find this answer helpful.
Adapter basics
In Android, Adapters are used to translate your data (in your case from an SQLite database) into Views that can be displayed in listviews, spinners, etc. (AdapterView to be specific). One of the most commonly used ones is the CursorAdapter which has basic infrastructure necessary when the associated data is supposed to be read from a cursor.
You will mainly need three methods in your adapter:
- getViewTypeCount which will tell the framework how many types of views your adapter knows. For you this will be two: activated and deactivated apps.
getItemViewType which, when passed a specific position in the data (here: the cursor), is able to decide which of those types that position falls into. For this, you will likely be able to reuse your db.appActivated code, at least in large parts.
getView, which, when passed a position, can turn the data associated with that position into a View for display. Let's look at that last part in more depth.
Android does some very nifty stuff to make sure your app is fast and slick and responsive. One of those things is, it will only keep enough views around for all positions in the list that are displayed. So, if you have a list that can display 10 items at a time, but your data holds a million records, it will still only keep 10 views around (well, actually, a few more from when stuff is scrolled off screen, but definitely not the one million it would require for every data record).
When the time comes to actually turn data into visible representations - getView - it will pass an old, previously visible but now off screen view (a recycled view) in as the convertView parameter for you to try adapting it to display the data that's been requeusted. This is because inflating new views is comparatively more expensive than just taking an existing one and changing its texts or images or whatever. The view types you have told it about will help it to only pass the type of convert view into getView that is appropriate for the position that's been requested.
This way, you need to only inflate a new view if the passed convert view is inappropriate somehow. And inappropriate, in this case, usually only means "if it is null". So, usually, what you end up with is something very close to this:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = // inflate a new view
}
// bind the convert view to the data, i.e. set its text views, images, and - in your case - background color
}
A video says more than a thousand words
You may want to watch this Google I/O keynote for a more comprehensive explanation of how it all ties together.

Cancelling ListView's recycler and/or clearing the recycler?

I have a ListView in my app that is used to show a list with 2 types of items. The way it is currently implemented is that I have two different XML layouts for each of the item types, my adapter correctly reports the type and in the getView() method I inflate the appropriate XML according the the type in the specified position.
The problem is that in the vast majority of cases the structure of the list of items is that most of the type 1 items are in the beginning and most of the type 2 items are in the end, so usually at first you see mostly type 1 items, you scroll down and at some point you start seeing type 2 items, and they continue until the end of the list.
All works fine while I scroll until I hit that midpoint. Around that point all the calls to getView() get null passed as the convertView parameter. This makes sense obviously. The problem is that is seems like ListView stores all the previous type 1 views in the recycler, and I will not use them as long as I keep scrolling down since from now on most of the views will be type 2 views.
The views are pretty complex, with custom background and bitmaps on top of it, so I end up with lots of views in memory that I will probably never use.
My question is twofold:
Should I even worry about it? right now I am not in the point where I get OOM exceptions, but will I ever get there or is ListView smart enough to "let go" of some of those views when resources get tight?
If I do need to worry about it, is there a way to explicitly tell ListView to clear up it's recycler, or even disable it somehow?
A possible solution is to use the same XML for both layouts, have two ViewGroups in there and just set the visibility of one of them to GONE, but it seems like a waste to have a fairly complex view hierarchy if I am never going to show it.
Should I even worry about it?
No, as the user is perfectly capable of scrolling up, thereby returning to type 1 rows.
right now I am not in the point where I get OOM exceptions, but will I ever get there or is ListView smart enough to "let go" of some of those views when resources get tight?
Once you start getting OutOfMemoryError messages, this ListView will not be your problem. You only have so many row View structures, and all should be really cheap from a memory consumption standpoint.
One suggestion to deal with two different type of child view in Adapter is using getViewTypeCount method and let the adapter know actually you use two different type of view.
The listView maintains each recycler per each view type (in your case, the number will be 2), so you don't worry to any OOM exceptions and don't need to tell ListView to clear up it's recycler.
For more detailed description,
Check: getViewTypeCount and getItemViewType methods of ArrayAdapter
Code snippet for implementation:
public class SampleAdapter extends ArrayAdapter<String> {
...
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
//the result must be in the range 0 to getViewTypeCount() - 1.
if( position < 10 )
return 0;
else
return 1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
switch( getItemViewType(position) ){
case 0:
//do something for type1 view.
break;
case 1:
//do something for type2 view.
break;
}
return convertView;
}
}
I would not worry too much when having only 2 view types.
If you want to optimize it, I suggest not having a very complex layouts and instead use custom View and do drawing of the Bitmaps yourself. A bit more complex task, but will bring better UX when going through midpoint.

How to use a ListView inside a ExpandableList?

I've been working with a custom ExpandableList (see example picture below) where each item always has one child. This child consists of three parts. Each part has a header (red bars) and below that an Empty item OR a list of items. The length of this list will vary.
The first way I tried to do this is by adding a ViewStub below the empty item, which I inflated with a custom view, which also contained a ViewStub at the end which I inflated in turn for the next item, thus adding items recursively to create this sort of list of items. Sadly this resulted in StackOverflowError's when the list became too long (With short lists this worked perfectly).
So on my second try I tried using a ListView with a custom adapter instead. Sadly this list only used a small part of my screen and the rest of the items where occluded behind the header of the next part (This mini list looked scrollable as a second scrollbar appeared next to it, but it did not scroll. Not that I would consider this scrolling inside a scrolling list to be a good solution, but just wanted to mention this).
Can anyone tell me how I can tell this list of items to not be scrollable and take up all the room that it needs (does it know what size it is going to be when the child node is created??) or help me with a alternative solution to my problem? (Ooh, and I have considered putting an unholy amount of ViewStubs inside my layout, but that just seems idiotic and really bad practice. Correct me if I'm wrong)
If I understood you correctly, then why don't you just take an ExpandableList + Adapter that implements ExpandableListAdapter? It's a somewhat ugly approach but it works and isn't much hassle.
MyAdapter implements ExpandableListAdapter
#Override
public View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent) {
}
In this method you could simply figure out if the current childPosition would be one of the headers or one of the children and inflate the appropriate View from xml.

Categories

Resources