An application created with object orientation will fail at startup.

Asked 1 years ago, Updated 1 years ago, 86 views

If you run the following program on your smartphone, it will end as soon as it starts.There are no errors when coding, so I don't know where the problem is.If there is anyone who can tell us the cause, please take care of it.
MMonster is a class with instance fields of type String and type ImageView.

public class MainActivity extensions AppCompatActivity{
    @ Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    // image acquisition
    ImageView fImage= (ImageView) findViewById (R.id.fireI);
    ImageView = (ImageView) findViewById (R.id.leafI);
    ImageView wImage= (ImageView) findViewById (R.id.waterI);
    // constructor configuration
    Monster f = new Monster ("Human lizard", fImage);
    Monster = new Monster ("Fushigidane", lImage);
    Monster w = new Monster ("Zenigame", wImage);
}

android java android-studio

2022-09-29 21:34

1 Answers

findViewById() must not be done when declaring instance variables.
Modify the program to run in onCreate.

public class MainActivity extensions AppCompatActivity{
    @ Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // image acquisition
        ImageView fImage= (ImageView) findViewById (R.id.fireI);
        ImageView = (ImageView) findViewById (R.id.leafI);
        ImageView wImage= (ImageView) findViewById (R.id.waterI);

        // constructor configuration
        Monster f = new Monster ("Human lizard", fImage);
        Monster = new Monster ("Fushigidane", lImage);
        Monster w = new Monster ("Zenigame", wImage);
   }
}


2022-09-29 21:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.