Skip to content Skip to sidebar Skip to footer

In Android How To Prevent Updating Existing Items On Notifydatasetchanged()

I have chat app In custom array adapter. I set random colors to usernames for each message with this code: String[] array = context.getResources().getStringArray(R.array.username_c

Solution 1:

You should keep color in the data class, for example in the Message class, or keep Map in the adapter, that maps Message to Color. Then randomly create a color, when it doesn't present in the map. or use the color, if it present in the map. Using a map is good solution than keeping in the data class, when the color doesn't related to message, when it is not a message property, so in that case, a good solution is a keeping it in the adapter class, in the map, for example

private Map<Message, String> colorsMap = new HashMap<Message, String>();

privatevoid colorUsername(ViewHolder holder, Message message, String userName) {
    String randomColor;
    if(colorsMap.contains(message)) {
        randomColor = colorsMap.get(message);
    }
    else {
        if (userName.equals(USERNAME_ME)){
            randomColor = "#000000";
        }elseif (message.getUserId()!=prevMsgUserID) {
            do {
                String[] array = context.getResources().getStringArray(R.array.username_colors);
                randomColor = array[new Random().nextInt(array.length)];
            }while (prevColor.equals(randomColor));

        }
        colorsMap.put(message, randomColor);
    }        
    holder.nameTextView.setTextColor(Color.parseColor(randomColor));
}

Solution 2:

Basically you have to create a Collection of user data model.

Like ArrayList<UserModel> arr = new ArrayList<UserModel>();

User Model can contain-> userId,userColor,groupId(if group chat supported) and map this model with you DB.

Means you have to make a column in db and add userBgColor in user table and map it with the model and this model in array list and supply the array list to your custom adapter .

Your can use ORMLite for rational mapping .

Then in getView()

{

UserModelmodel= arr.get(position);

Stringcolor= user.getUserColor();

} 

Post a Comment for "In Android How To Prevent Updating Existing Items On Notifydatasetchanged()"