Search code examples
androidnullpointerexceptionandroid-imageviewandroid-inflate

image won't show on inflated ImageView


I'm trying to inflate a photo that i took via camera on on ImageView but get NPE.

 public void onDescriptionClick(){

      RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.camap);
      View view = getLayoutInflater().inflate(R.layout.pic_check, mainLayout, false);
      RelativeLayout inflatedLayout = (RelativeLayout) findViewById(R.id.inflated);
      ImageView iv= (ImageView)findViewById(R.id.imgv);
      mainLayout.addView(inflatedLayout);

      inflatedLayout.addView(iv);

      iv.setImageBitmap(bitmap);//here i get NPE
}

help will be appreciated


Solution

  • You have the NPE because you're calling findViewById(R.id.imgv) and the ImageView is not yet added to your "activity layout", you must call findViewById from the "new inflated" view otherwise it will return a null object.

    muruga5000's answer is right, but the code is little messy. Here is my suggestion:

    public void onDescriptionClick(){
    
         RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.camap);
    
         View inflatedView = getLayoutInflater().inflate(R.layout.pic_check, mainLayout, false);
    
         ImageView iv= (ImageView) inflatedView.findViewById(R.id.imgv);
    
         iv.setImageBitmap(bitmap);
    
         mainLayout.addView(inflatedView);
    
    }