Home > Mobile >  Android app crashes when using rotate animation
Android app crashes when using rotate animation

Time:10-23

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:

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

CodePudding user response:

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.

  • Related