Search code examples
javaandroid-studionullpointerexceptionimageview

How to create ImageView from another class


I want to create ImageVIew from my class but i've got some exeptions and dont know why. Please help me. Here is my class

public class Card {

Bitmap bitmap;

 public Card( Bitmap bitmap, LinearLayout linearLayout,Context context){
    ImageView imageView=new ImageView(context);
    imageView.setImageBitmap(bitmap);
    imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
             ViewGroup.LayoutParams.WRAP_CONTENT));
     linearLayout.addView(imageView);
} 

and

public class MainActivity extends AppCompatActivity {
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.jpg);
Card card;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout linearLayout=findViewById(R.id.ll);
    card=new Card(bitmap,linearLayout,this);

    setContentView(R.layout.activity_main);

Solution

  • Move the

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.jpg);
    

    definition in the onCreate method. And this should solve the NullPointerException because the context is not defined yet.

    So it should look as follow:

    public class MainActivity extends AppCompatActivity {
    Bitmap bitmap;
    Card card;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.jpg);
        LinearLayout linearLayout=findViewById(R.id.ll);
        card=new Card(bitmap,linearLayout,this);
        ....