Search code examples
javaandroidlistviewarraylistandroid-arrayadapter

ArrayAdapter using ArrayList


I have problems with ArrayAdapter because I am using ArrayList of messages and I want to display messages data.

I have problem in getView because I am not sure how to go through ArrayList and show data correctly.

I did like this:

In Activity i have this:

        ArrayAdapterItem arrayAdapter = new ArrayAdapterItem(DashboardActivity.this,
                R.layout.list_view_row_item, result);
        listViewItems.setAdapter(arrayAdapter);

and in class ArrayAdapterItem I have:

public class ArrayAdapterItem extends ArrayAdapter<Message> {

ArrayList<Message> message = new ArrayList<Message>();  
Context mcontext;
int layout;
int messageNumber;


public ArrayAdapterItem(Context mcontext, int resource, ArrayList<Message> message) {
    super(mcontext, resource);
    this.message = message;
    this.mcontext = mcontext;
    this.layout = resource;
}


@Override
public View getView(int position, View convertView, ViewGroup parent ){

    ViewHolderItem viewHolder;


    if(convertView==null){
        LayoutInflater inflater = ((Activity) mcontext).getLayoutInflater();
        convertView = inflater.inflate(layout, parent, false);

        viewHolder = new ViewHolderItem();
        viewHolder.textViewItem = (TextView) convertView.findViewById(R.id.textViewItem); //ovde ih dodajem

        convertView.setTag(viewHolder);
    }else {
        viewHolder = (ViewHolderItem) convertView.getTag();
    }

    if(message!=null){

        while(messageNumber>0){
        messageNumber--;
        viewHolder.textViewItem.setText(message.get(messageNumber).getMessageText());
        Log.d("Lista AUTORA: ", message.get(messageNumber).getMessageText() + "");
        }
    }


    return convertView;


}

@Override
public int getCount() {

    messageNumber = message.size();
    return messageNumber;
}


static class ViewHolderItem {
    TextView textViewItem;
}

}

I have 3 message texts to display and it does BUT only first one have ok value, and other two has string from the TextView (It's not set). In log everything is fine, all 3 values of messages are ok.

Any ides what I did wrong?


Solution

  • I'm not completely clear on what your problem is. If your ArrayList has three elements, and you're trying to display a list with three entries, the above code won't do it. getView is called once for each list entry. The position parameter tells the method which list entry the method is supposed to fill. You're not using position at all; instead, you're looping through the entire list, but that won't work. Instead, try removing the while loop and using something like

    viewHolder.textViewItem.setText(message.get(position).getMessageText());
    //                                          ^^^^^^^^
    

    Like I said, I'm not entirely sure what you're trying to do, but I think you'll need to do something similar to this.