-2

I'm trying to develop an android app android studio 3.2. When app crashes imageView.setImageBitmap(bitmap); stopped the app. This is my code to get an image in drawable

       public class MainActivity extends AppCompatActivity {
        Button button;
        ImageView imageView;
        TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.imageView=(ImageView)findViewById(R.id.image_view);
        textView=(TextView)findViewById(R.id.text_view);
        button=(Button)findViewById(R.id.button_click);

        try {
            this.imageView.setImageResource(R.drawable.helloworld);

        }catch (Exception e){
            Log.d("error_msg", ""+e);
            System.out.println(">>>>>>>>>>>>>>>>>"+e);

        }
//
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

and also i used this

implementation 'com.google.android.gms:play-services-vision:16.2.0'

How to solve this issue?

D/error_msg: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference

This is the error i got when Catch the error

RUC...
  • 133
  • 10

2 Answers2

1

You can set image resource to ImageView by using setImageResource

imageView.setImageResource(R.drawable.helloworld);

If you specifically want to add bitmap then try to debug and check the error which leads to crash.

Uma Achanta
  • 3,669
  • 4
  • 22
  • 49
1

Move the calls super.onCreate() and setContentView() to the top of OnCreate() method. Like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.imageView=(ImageView)findViewById(R.id.image_view);
    textView=(TextView)findViewById(R.id.text_view);
    button=(Button)findViewById(R.id.button_click);

    try {
        this.imageView.setImageResource(R.drawable.helloworld);

    } catch (Exception e){
        Log.d("error_msg", ""+e);
        System.out.println(">>>>>>>>>>>>>>>>>"+e);
    }
}

The layout has to be set before calling findViewById().

Charan M
  • 489
  • 3
  • 7