Scrolling through ListView of ProgressBars - android

I'm working on an Android app that utilizes a ListView, in which each row is comprised of a text view and a progress bar. Things work smoothly unless the user has to scroll through a long list.
ProgressBars start taking on the progress of other ProgressBars not currently visible on the screen.
I understand that this is a common issue that stems from the implementation of GetView, but I'm wondering what the best course of action is to take with ProgressBars.
GetView:
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
ViewWrapper wrapper;
ProgressBar myProgressBar;
int initProgress = myData.get(position).getProgress();
if (row == null){
LayoutInflater inflater = context.getLayoutInflater();
row = inflater.inflate(R.layout.row, null);
wrapper = new ViewWrapper(row);
row.setTag(wrapper);
}
else{
wrapper = (ViewWrapper)row.getTag();
}
RowModel model = getModel(position);
wrapper.getPid().setText(model.toString());
myProgressBar = wrapper.getProgressBar();
myProgressBar.setProgress(initProgress);
myProgressBar.setMax(100);
myProgressBar.setTag(new Integer(position));
return row;
}
ViewWrapper:
public class ViewWrapper {
View base;
TextView pid = null;
ProgressBar pb= null;
ViewWrapper(View base){
this.base = base;
}
TextView getPid(){
if(pid == null){
pid = (TextView)base.findViewById(R.id.pid);
}
return(pid);
}
ProgressBar getProgressBar(){
if(pb== null){
pb= (ProgressBar)base.findViewById(R.id.progressbar);
}
return(pb);
}
}
It seems that the issue is related to:
myProgressBar = wrapper.getProgressBar();
because that ProgressBar starts getting the behavior of a recycled ProgressBar. However, I want it to have its own behavior.
What's the best way to alleviate this? Thanks.

You may need to inflate the layout each time and not re-use the convertView that's passed in. This shouldn't be a problem unless you have A LOT of rows.

I had to implement a similar feature , here is what I did . I implemented the following outside getview
OnTouchListener - to listen to seekbar touch events
OnKeyListener - to listen to dpad and trakball event for the seekbar
I set these listeners for the seekbars from getView
Whenever the listeners were called , I would find the seekbars parent , then do the findviewbyid from the parent to the textview.
So now I have the textview which I have to update, and the seekbar. All I need to do was set the text from the array.
here is some code to help you.
private OnTouchListener touchListener = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
View parent = (View) v.getParent();
TextView textView = (TextView) parent
.findViewById(R.id.id_grade_tooltip);
if (textView == null) {
} else {
SeekBar seekBar = (SeekBar) v;
textView.setText(String.valueOf(seekBar.getProgress())
+ "%");
}
return false;
}
};

Related

Android Listview scroll lag with view holder

I have noticed that a ListView in my application has started to stutter quite badly all of a sudden.
I am using Volley to load images for my listview items - downloading and caching the images are fine and scroll smooth as butter.
However I currently have a spinner that sits on top of the NetworkImageView while I wait for the image to load. The lag comes in once the image has successfully loaded - I set the spinner to be invisible and the image to visible. Changing the visibility of these items seems to be the source of the lag.
I am currently using the View Holder pattern, my onResponseLoad looks like the following:
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
if (response.getBitmap() != null){ //Check that the image is not null
ProgressBar progress = holder.getProgress(); //Find Spinner - this doesnt cause lag
progress.setVisibility(View.GONE); //Hide spinner (This causes lag)
img.setVisibility(View.VISIBLE); //Image is a network image from the holder (This causes lag)
}
}
(Note that commenting out those two offending lines results in buttery smooth scrolling again)
The other strange thing is that I haven't touched this part of the application in some time and in my current live version, as well as previous commits there is no lag. Comparing my current code base to previous non-lagging versions show that there has been 0 change to the code surrounding this aspect of the application. Furthermore other lists that I have implemented using almost the exact same technique have not experienced this issue.
The only thing I can think of that could be different is that I am now using the latest version of Gradle - although I don't think that should have an impact at run-time.
I am at a total loss as to what is going on, would appreciate any insight on what I should be doing to achieve smooth ListView scrolling (or what may have lead to my implementation's degradation)
EDIT: Posting code of getView() as requested
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View placeSelectorView = convertView;
PlaceViewHolder placeSelectorHolder = null;
if(placeSelectorView == null){ //If we are creating the row for the first time
LayoutInflater inflater = (LayoutInflater) mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //Inflate the view
placeSelectorView = inflater.inflate(R.layout.place_selector, parent, false); //Get the view
placeSelectorHolder = new PlaceViewHolder(placeSelectorView); //Create holder object
placeSelectorView.setTag(placeSelectorHolder); //Attach reference to the view
}else{
placeSelectorHolder = (PlaceViewHolder) placeSelectorView.getTag(); //Load holder from memory
if(!placeSelectorHolder.isHasImage()){ //Need to optimise this
placeSelectorHolder.getLayout().addView(placeSelectorHolder.getrLayoutThumbnail(), 0);
placeSelectorHolder.setHasImage(true);
}
if(!placeSelectorHolder.isSpinnerVisible()){
placeSelectorHolder.getProgressBar().setVisibility(View.VISIBLE);
placeSelectorHolder.getPlaceImg().setVisibility(View.GONE);
placeSelectorHolder.setSpinnerVisible(true);
}
}
POI place = (values.get(position)); //Get POI object for the place
POI parentPlace = getParent(place); //Get parent POI for place
placeSelectorHolder.getPlaceName().setText(place.getName());
if(parentPlace != null){ //If place has a parent POI
placeSelectorHolder.getParentPlaceName().setText(parentPlace.getName());
}else{ //We don't want the parent text in the view
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) placeSelectorHolder.getParentPlaceName().getLayoutParams();
layoutParams.weight = 0; //Setting weight to 0 will remove it from the LinearLayout
placeSelectorHolder.getParentPlaceName().setLayoutParams(layoutParams);
}
final PlaceViewHolder holder = placeSelectorHolder;
loadThumbnail(holder, place);
return placeSelectorView;
}
public void loadThumbnail(final PlaceViewHolder placeSelectorHolder, POI place){
RealmList<poiPhoto> photos = place.getPhotos();
String mUrl;
if(!photos.isEmpty()){
mUrl = photos.get(0).getSmall();
}else{
mUrl = "";
}
final NetworkImageView placeImg = placeSelectorHolder.getPlaceImg();
if(!mUrl.equals("")){ //If there is an Image Available
ImageLoader imageLoader = ServerSingleton.getInstance(getContext()).getImageLoader(); //Get volley imageloader from Singleton
imageLoader.get(mUrl, new ImageLoader.ImageListener() { //Custom get so we can use override onResponse and OnErrorResponse
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
if (response.getBitmap() != null){ //Check that the image is not null
ProgressBar progressBar = placeSelectorHolder.getProgressBar(); //Find Spinner
placeImg.setVisibility(View.VISIBLE);
if(progressBar != null) progressBar.setVisibility(View.GONE); //Make the spinner invisible
placeSelectorHolder.setSpinnerVisible(false);
}
}
#Override
public void onErrorResponse(VolleyError error) {
//TO-DO: Get an error image
}
});
placeImg.setImageUrl(mUrl, imageLoader); //Send the request
placeSelectorHolder.setHasImage(true);
}else{ //There is no image
LinearLayout layout = placeSelectorHolder.getLayout(); //Find the horizontal layout
layout.removeView(placeSelectorHolder.getrLayoutThumbnail()); //Remove the Thumbnail layout
placeSelectorHolder.setHasImage(false);
}
}

Android force Invisible or gone Listview items in update row

I have ListView with some widgets into each row and i can update single row from Service. update row work fine but I can not INVISIBLE or GONE listview's row items.
for example my row have ImageView and ProgressBar. I can not INVISIBLE this widgets in this code
private void updateView(int download_item_id, int position, int percent, final String stream_filename, final String thumb_path) {
Log.e("receive: thumb_path: ", thumb_path);
View v = UI.lv_message_content.getChildAt(position - UI.lv_message_content.getFirstVisiblePosition());
UI.lv_message_content.getAdapter().getView(position, v, UI.lv_message_content);
UI.lv_message_content.invalidateViews();
if (v == null) return;
ImageView imgv_image_item = (ImageView) v.findViewById(R.id.imgv_image_item);
NumberProgressBar numberProgressBar = (NumberProgressBar) v.findViewById(R.id.npb_progressbar);
ImageView iv_download_icon = (ImageView) v.findViewById(R.id.iv_download_icon);
numberProgressBar.setProgress(percent);
if (percent == 100) {
numberProgressBar.setVisibility(View.GONE);
iv_download_icon.setVisibility(View.GONE);
}
}
in this code View.GONE for numberProgressBar and iv_download_icon doesnt work if percent equals with 100. i'm testing and debuging code nested if work but Gone not set to widgets
I think you missed notifyDatasetChnaged()
if (percent == 100) {
numberProgressBar.setVisibility(View.GONE);
iv_download_icon.setVisibility(View.GONE);
notifyDatasetChanged()
}
I'm remove this line and my problem is solved:
invalidateViews();

Listview style Each Row

this is the code in my custom adapter (THE CODE IN BROWN COLOR) when initially list is build proper margin is applied to valid items when i scroll down and again scroll up all the rows in list shifts the margin left by 20 what i'm doing wrong please reply soon
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
// getting data
final ViewMovieDetailsModel_ViewComments movies = getItem(position);
if (convertView == null)
{
convertView = View.inflate(context, R.layout.comment_row, null);
holder = new ViewHolder();
//getting handles
holder.comments_linearLayout = (LinearLayout) convertView.findViewById(R.id.comments_linearLayout);
holder.commenter_textView = (TextView) convertView.findViewById(R.id.comment_row_commenter);
holder.commented_on_textView = (TextView) convertView.findViewById(R.id.comment_row_comment_time);
holder.comment_text_textView = (TextView) convertView.findViewById(R.id.comment_row_comment_text);
holder.reply_button = (Button) convertView.findViewById(R.id.comment_row_reply_button);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
if (movies != null)
{
if (((movies.getParent_comment_id()).toString().equals("null")) && session.isLoggedIn()==true) {
holder.reply_button.setVisibility(View.VISIBLE);
}else{
holder.reply_button.setVisibility(View.INVISIBLE);
}
`if (!((movies.getParent_comment_id()).toString().equals("null")))
{
LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
params.setMargins(20, 0, 0, 0);
holder.comments_linearLayout.setLayoutParams(params);
}`
holder.commenter_textView.setText(movies.getUsername_commentor());
holder.commenter_textView.setTag(movies.getUser_id_commentor());
return convertView;
}
because you are setting margins (the brown font) in 'if' statement:
if (movies != null)
just take it out of this if block (for example put it just before the return point)
Right now this code is probably not executed at the first view load, since the movie is null. When the getView is called second time, the movie is not null, and the marigin is set according to your 'brown' code.
if this is not the solution - maybe the inside if statement condition is not true (the one that is in first 'brown' row). so.. your own logic prevents the marigins to be set as you want :)
Please let me know if it helps.
One way you could go about solving this problem is instead of using LayoutParams.setMargins(20, 0, 0, 0), you could create an empty TextView whose width is 20 dp by default and whose position will be to the left of your rows contents. It will be View.GONE by default, but when if (!((movies.getParent_comment_id()).toString().equals("null"))) happens, you can set that to View.VISIBLE

Animate group expansion at every time that I expand the group

I am trying to imlpement some animation to be played every time that I expand a group of an ExpandableListView. So far I do the following the getChildView of my custom adapter (based on BaseExpandableListAdapter):
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view,
ViewGroup parent) {
// Auto-generated method stub
ExpandListChild child = (ExpandListChild) getChild(groupPosition,childPosition);
if (view == null)
{
LayoutInflater inflater =
(LayoutInflater) m_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=inflater.inflate(R.layout.expandlist_child_item, null);
AnimatorSet anim = (AnimatorSet) AnimatorInflater.loadAnimator(m_context,
R.animator.expand_list_animation);
anim.setInterpolator(new OvershootInterpolator());
anim.start();
}
TextView tv = (TextView) view.findViewById(R.id.tvChild);
tv.setText(child.getName());
tv.setTag(child.getTag());
CheckBox cb = (CheckBox) view.findViewById(R.id.checkBox1);
cb.setChecked(child.getState());
return view;
}
The problem is that because I am applying the animation only when creating a new view, this only works the first time that the group is expanded. I also tried to apply it in any case (not only when view==null) but the problem is that the animation is played for all expanded children (even those of other groups that are already expanded).
I have been trying a lot to get this to work and I cannot figure out how. Your help is appreciated.

Android: ListView with a Custom ArrayAdapter acting up on long lists -- Timing issue!

HI all,
I have this "search results" ListView.
The search results can be of different "kinds" (different sections, call it).
To separate the "kinds" I add a row with a title. (I know about the expandable list, but can't use it for other reasons).
In my getView(), I check for a property, and if it's set, I change the background color of the row.
The problem: when I run a query that returns just a few rows (say 15), everything is fine. But when I run another that returns, say 600 rows, something goes wacko and it changes the background randomly, at a somewhat regular interval. Same thing happens when I'm running in debug mode and stop things in the middle.
So, it's definitely a timing issue.
I'm thinking this might be due to having to re-render the big list as the on-screen keyboard closes.
So, is the Adapter to blame? Is there any solution for this?
If the keyboard is the problem, is there a mechanism to tell the list "wait until the thing closes" before start rendering? (Not sure I like that, but it's better than getting a cute little rainbow...)
Thanks!
Llappall
--
Here's the adapter and the element layout (below):
private class ElementAdapter extends ArrayAdapter<Element> {
private ArrayList<Element> rows;
private Element.typeEnum type;
public ElementAdapter(Context context, int textViewResourceId, ArrayList<Element> rows) {
super(context, textViewResourceId, rows);
this.rows = rows;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.element, null);
}
Element row = rows.get(position);
if (row == null) {
return v;
}
v.setTag(row);
type = row.getType();
boolean isSectionType = type == Element.typeEnum.DIV118SECTION || type == Element.typeEnum.APPASECT ||
type == Element.typeEnum.APPBSECT || type == Element.typeEnum.AZSECT;
TextView title = (TextView) v.findViewById(R.id.title);
TextView body = (TextView) v.findViewById(R.id.body);
if (isSectionType) {
body.setMaxLines(5000);
}
title.setText(row.getTitle());
if (row.getBody() != null) {
body.setText(row.getBody());
}
if (type == Element.typeEnum.SEARCHLISTHEADER) {
v.setBackgroundColor(Color.rgb(230, 230, 250));
title.setBackgroundColor(Color.rgb(230, 230, 250));
body.setBackgroundColor(Color.rgb(230, 230, 250));
star.setBackgroundColor(Color.rgb(230, 230, 250));
}
return v;
}
}
==ELEMENT LAYOUT==
<TextView
android:id="#+id/body"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
style="#style/ListItemSubTitle" />
</LinearLayout>
It would be much easier if you would post a getView() method here.
From what I can tell, you might be using recycled views wrong.
Check if background is changed to something if property is not set.
For example:
if (peoperty.isSet()) {
changeBackGround();
}
Just by itself will be wrong if you are reusing convertView, since the background will stay the same color how it was, when this view was used for a different row.
must be something like:
if (peoperty.isSet()) {
changeBackGround();
} else {
changeBackgroundToSomethingNeutral()
}
I took a liberty to rewrite that code for you, since you make too much weird stuff. Here's what I think is a optimized working code for your situation (didn't test any of it, but should work):
private class ElementAdapter extends ArrayAdapter<Element> {
public ElementAdapter(Context context, int textViewResourceId, ArrayList<Element> rows) {
super(context, textViewResourceId, rows);
this.rows = rows;
}
private final ArrayList<Element> rows;
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewsHolder holder = null;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.element, parent, false);
holder = new ViewsHolder();
holder.title = (TextView) v.findViewById(R.id.title);
holder.body = (TextView) v.findViewById(R.id.body);
convertView.setTag(holder);
} else {
holder = (ViewsHolder) convertView.getTag();
}
final Element row = rows.get(position);
final Element.typeEnum type = row.getType();
if (type.equals(Element.typeEnum.DIV118SECTION) || type.equals(Element.typeEnum.APPASECT) ||
type.equals(Element.typeEnum.APPBSECT) || type.equals(Element.typeEnum.AZSECT)) {
body.setMaxLines(5000);
}
holder.title.setText(row.getTitle());
if (row.getBody() != null) {
holder.body.setText(row.getBody());
} else {
holder.body.setText("");
}
if (type == Element.typeEnum.SEARCHLISTHEADER) {
convertView.setBackgroundColor(Color.rgb(230, 230, 250));
holder.title.setBackgroundColor(Color.rgb(230, 230, 250));
holder.body.setBackgroundColor(Color.rgb(230, 230, 250));
//star.setBackgroundColor(Color.rgb(230, 230, 250)); // Where did that come from?
}
return convertView;
}
private final class ViewsHolder {
public TextView title;
public TextView body;
}
}
Couple of notes on the original code:
if (row == null) {
return v;
}
is wrong. You shouldn't have any null elements in your list for any position in the list. Even if you have, you shouldn't just throw some random view for the row. What you are doing here, is returning "v", that can very well be (and probably will be) some recycled old row, that still displays old data, and that's going to confuse the user. I made an assumption that you won't have any empty elements when wrote the code.
if (row.getBody() != null) {
body.setText(row.getBody());
}
Is almost ok, but again, if you are reusing convertView (which is some random previous row that isn't displayed anymore), then if body is actually null you will just be displaying the old data, which again will confuse the user. If body is null, just set the string empty.
P.S.
I recommend you to watch this for tips and tricks about how to work with ListView: The world of ListView

Categories

Resources