Android app crashes when using rotate animation

Issue

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, and 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 crashes, please help me solve this.

The animation is a simple rotate:

<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.

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 become 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.

Answered By – z.g.y

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published