Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Android app crashes when using rotate animation

So I’ve got this code, and tried to use rotate on my imageView, but it throws null when using findviewbyid, but I have it in the same class. I have a few separate activities in the same project, this is one of them, which opens from the main activity

package com.example.gyakorlozh;

ImageView kedvencEvszak;
TextView tw;
Animation anim;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_evszak);
    kedvencEvszak.findViewById(R.id.kedvencEvszak);
    tw.findViewById(R.id.textView);
    anim = AnimationUtils.loadAnimation(EvszakActivity.this, R.anim.kepanimacio);

    kedvencEvszak.startAnimation(anim);

}

And if I try to run it it crashes, please help me solve this.

The animation is a simple rotate:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<rotate android:pivotY="50%"
    android:pivotX="50%"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:duration = "2000"
    android:startOffset = "3000"/>

>Solution :

Assuming your XML and other things are properly configured.

Then both of these aren’t doing anything,

kedvencEvszak.findViewById(R.id.kedvencEvszak);
tw.findViewById(R.id.textView);

so when you do this

kedvencEvszak.startAnimation(anim);

kedvencEvszak is non-existent, thats why you’re getting an NPE exception.

Try doing this instead,

kedvencEvszak = findViewById(R.id.kedvencEvszak);
tw = findViewById(R.id.textView);

and afterwards, call the animation from kedvencEvszak

kedvencEvszak.startAnimation(anim);

which in turn your posted onCreate code will end up like this

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_evszak);
    kedvencEvszak = findViewById(R.id.kedvencEvszak);
    tw = findViewById(R.id.textView);
    anim = AnimationUtils.loadAnimation(EvszakActivity.this, R.anim.kepanimacio);

    kedvencEvszak.startAnimation(anim);

}

The TextView tw doesn’t have anything to do with kedvencEvszak throwing NullPointerException, but I added it to save you the headache just in case you decided to do something with it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading