Search code examples
android-imageview

Problem with getting the id's of image view in Android?


I am implementing an application displaying images and messages obtained from .net server. For that I'm adding LinearLayout's with TextView and ImageView dynamically by using for loop. At first I am getting messages and I'm adding them to the TextView with dummy images placed in ImageView:

for(int i = 0; i < messages.size(); i++) { 
    FrameLayout f1 = new FrameLayout(this);
    LinearLayout l1 = new LinearLayout(this);
    LinearLayout l2 = new LinearLayout(this);
    im = new ImageView(this);
    TextView tv = new TextView(this);
    tv.setText(messages.get(i).getmessage());

    im.setImageResource(R.drawable.person);
    l1.addView(tv);
    l2.addView(im);
    f1.addView(l1);
    f1.addView(l2);

    ((LinearLayout)findViewById(R.id.LinearlayoutMessage)).addView(f1);
}

After some time I am getting original images. My intention is to replace the dummy images with original ones. To achieve this I'm using imageview.getid() unfortunately I'm getting last id of the imageview. But I need to get each individual imageview id's.

What is the best way of changing dummy images with real ones?


Solution

  • Looks like you need to store each imageView id in a map from each message -> imageView like so:

    Map<Message, Long> messageMapping = new HashMap<Message, Long>();
    
    for(int i = 0; i < messages.size(); i++) { 
        FrameLayout f1 = new FrameLayout(this);
        LinearLayout l1 = new LinearLayout(this);
        LinearLayout l2 = new LinearLayout(this);
        im = new ImageView(this);
        TextView tv = new TextView(this);
    
        //add mapping
        messageMapping.put(messages.get(i), im.getId());
    
        tv.setText(messages.get(i).getmessage());
    
        im.setImageResource(R.drawable.person);
        l1.addView(tv);
        l2.addView(im);
        f1.addView(l1);
        f1.addView(l2);
    
        ((LinearLayout)findViewById(R.id.LinearlayoutMessage)).addView(f1);
    }
    

    Then when it comes time to lazy load your images into the existing imageViews you simply need to look up the imageView id reference by message mapping:

    (Total guess of what your code could look like)

    for(int i = 0; i < messages.size(); i++){
        Image image = queryServerForImage(messages.get(i).getImageId());
        ImageView imageView = ((ImageView)findViewById(messageMapping.get(messages.get(i))));
        //some conversion & seteup may be needed to get image into proper format
        imageView.setImageBitmap(image);
    }
    

    You may be able to do something similar with async tasks. You could span each one in the message ImageView creation loop with the associated resource id and having each asyc task update the ui from the network response.