Reputation: 487
I have a custom ArrayAdapter for a listView in an adroid chat application. I enter some text in my editText component and then i submit the text when i push a button.
The problem is that when the getView method in my custom Adapter is called the entire list is refresh and each row in my list become identically with the last information submitted.
Does someone knows how can i add a row in listView using a custom ArrayAdapter and other rows to have the original text?
This is how i call the adapter:
m_discussionThread = new ArrayList<String>();
m_discussionThreadAdapter = new ChatListAdapter(this, m_discussionThread);
list.setAdapter(m_discussionThreadAdapter);
Button send = (Button) this.findViewById(R.id.send);
send.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
String text = message.getText().toString();
Message msg = new Message(to, Message.Type.chat);
msg.setBody(text);
m_connection.sendPacket(msg);
m_discussionThread.add(text);
runOnUiThread(new Runnable() {
@Override
public void run() {
m_discussionThreadAdapter.notifyDataSetChanged();
}
});
}
});
This is the adapter:
public ChatListAdapter(Context context, ArrayList<String> chatValue) {
super(context,R.layout.list_row_layout_even, chatValue);
this.context = context;
this.chatValue = chatValue;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_row_layout_even, parent, false);
TextView chatText = (TextView) rowView.findViewById(R.id.chat_message);
chatText.setText(chatValue.get(chatValue.size()-1).toString());
return rowView;
Upvotes: 0
Views: 824
Reputation: 2090
Near the bottom, you're getting data element chatValue.size()-1
. That means that every View loaded through getView() will have the properties of the last data element. You should instead use position
. Example:
private Context mContext;
private LayoutInflater mInflater = null;
private ArrayList<String> mChatValue;
public ChatListAdapter(Context context, ArrayList<String> chatValue) {
super(context,R.layout.list_row_layout_even, chatValue);
mContext = context;
mChatValue = chatValue;
}
private LayoutInflater getInflater(){
if(mInflater == null)
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return mInflater;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
if(convertView == null) // Only inflating if necessary is great for performance
rowView = getInflater().inflate(R.layout.list_row_layout_even, parent, false);
else
rowView = convertView;
TextView chatText = (TextView) rowView.findViewById(R.id.chat_message);
chatText.setText(mChatValue.get(position));
return rowView;
}
Upvotes: 1