javaandroidnullpointerexceptionobjectanimator

Why does my android app keep stopping in the Android Studio emulator?


I tried fixing everything, but I can't seem to find the problem. Here is my MainActivity.java file :

package com.weebly.chesslearners.firstgame;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.renderscript.Sampler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.view.animation.TranslateAnimation;
import static android.content.ContentValues.TAG;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(new GamePanel(this));

    final TextView player = (TextView) findViewById(R.id.textView);
    final Button mover = (Button) findViewById(R.id.btnmove);

    final ObjectAnimator animation = ObjectAnimator.ofFloat(player,"y",300, 500);
    mover.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            animation.setDuration(2000);
            animation.setRepeatCount(1);
            animation.setRepeatMode(ValueAnimator.REVERSE);
            animation.start();
        }
    });



    setContentView(R.layout.activity_main);
    Log.i(TAG, "Build Successful");

}

}

I added all of the imports too. The Build Output says the error is on the line "mover.setOnclick...", but I can't find whats causing the error.


Solution

  • I think the problem is in the line setContentView(new GamePanel(this));

    Once you set the view the compiler is trying to find your textViews and button in GamePanel() class and I guess its not there.

    You can resolve it by adding setContentView(R.layout.activity_main); before final TextView player = (TextView) findViewById(R.id.textView);

    and set dynamic UI component later.