java – How can you display a picture by pressing a button?

Question:

I decided to write a program that displays a certain picture by pressing a certain button, but the application crashes when this button is pressed. How can this be fixed?

package com.example.fando.trenazher;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;



public class game1 extends AppCompatActivity {
Button buttonQ;
Button buttonW;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game1);
    buttonQ = (Button) findViewById(R.id.button4);
    buttonW = (Button) findViewById(R.id.button5);
    buttonQ.setOnClickListener(new View.OnClickListener() {
        public void onClick(View View) {
            ImageView imageView = (ImageView) findViewById(R.id.image);
            imageView.setImageResource(R.drawable.petuh);
        }
    });
    buttonW.setOnClickListener(new View.OnClickListener() {
        public void onClick(View View) {
            ImageView imageView = (ImageView) findViewById(R.id.image);
            imageView.setImageResource(R.drawable.lion);

        }
    });
        }} 

in the logs the error is described as follows

11-07 15:23:35.819 25682-25682/com.example.fando.trenazher       
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fando.trenazher, PID: 25682
java.lang.NullPointerException
at com.example.fando.trenazher.game1$2.onClick(game1.java:30)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run  (ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)

ZY Do not judge strictly, I am just learning (:

Answer:

Try So

// принять переменную ImageView

    private ImageView mImageView;

// Связать ImageView с идентификатором вашего XML в

    mImageView = (ImageView)findViewById(R.id.mImageView);

// Набор ресурсов для ImageView

mImageView.setImageResource(R.drawable.your_image_name);
Scroll to Top