0

Im trying to convert a bitmap that has been drawn to the screen to an imageView so that I can enable the drag & drop method on it.. This is the only way that I think I can implement this.

I Attempt to load the loaded bitmap (hazardCard) into an imageview named cardImage1.

Code:

public class PlayScreen extends GameScreen {


   // /////////////////////////////////////////////////////////////////////////
    // Properties
    // /////////////////////////////////////////////////////////////////////////
    private Rect backButtonBound;
    private Rect hazardCardBound;

    private Music screenClickMusic;


    /**
     * Width and height of the level
     */
   // private final float LEVEL_WIDTH = 1000.0f;
    //private final float LEVEL_HEIGHT = 1000.0f;

    /**
     * Define viewports for this layer and the associated screen projection
     */
    private ScreenViewport mScreenViewport;
    private LayerViewport mLayerViewport;

    private Bitmap backgroundBitmap;
    private Bitmap backButton;
    private Bitmap PlayScreenTitle;
    private Bitmap hazardCard;
    private Rect frontLayerBound;
    private Rect playScreenTitleBound;

    private ImageView cardImage1;
    private ViewGroup rootLayout;
    private int _xDelta;
    private int _yDelta;
    public View view;

    /**
     * User input controls for managing the player and the game
     */
   // protected InputControl pauseButton

    // /////////////////////////////////////////////////////////////////////////
    // Constructors
    // /////////////////////////////////////////////////////////////////////////

    /**
     * Create a game
     *
     * @param game
     *            Game to which this screen belongs */

    public PlayScreen(Game game) {
        super("PlayScreen", game);

        //Define the rects what will be used to 'hold' the images
        int spacingX = game.getScreenWidth() / 8;
        int spacingY = game.getScreenHeight() / 8;
        int padding = spacingY / 10;    //padding between each button
        int line = 1;   //each button is on a new 'line' (under each other)


        // Load in the assets used by the demo
        AssetStore assetManager = game.getAssetManager();
        assetManager.loadAndAddBitmap("pitch", "img/pitch.png");
        assetManager.loadAndAddBitmap("backButton", "img/back_button.png");
        assetManager.loadAndAddBitmap("hazardCard", "img/hazard_card.jpg");


        // Define Rectangles for Bitmaps
       // playScreenTitleBound = new Rect(spacingX * 2, spacingY * 0, spacingX * 6, spacingY * 1);

        this.backgroundBitmap = assetManager.getBitmap("pitch");
        this.backButton = assetManager.getBitmap("backButton");
        this.hazardCard = assetManager.getBitmap("hazardCard");

        //load in sounds
        assetManager.loadAndAddMusic("screenClickMusic", "music/buttonPress.mp3");

        //initialise
        this.screenClickMusic = assetManager.getMusic("screenClickMusic");

    }

    // /////////////////////////////////////////////////////////////////////////
    // Support methods
    // /////////////////////////////////////////////////////////////////////////

    // /////////////////////////////////////////////////////////////////////////
    // Update and Draw methods
    // /////////////////////////////////////////////////////////////////////////

    @Override
    public void update(ElapsedTime elapsedTime) {

        //process any touch events occurring since the update
        Input input = game.getInput();
        List<TouchEvent> touchEvents = input.getTouchEvents();

        if (touchEvents.size() > 0) {

            //Just check the first touch event that occurred in the frame.
            //It means pressing the screen with several fingers may not
            //trigger a 'button'.
            TouchEvent touchEvent = touchEvents.get(0);
            if (backButtonBound.contains((int) touchEvent.x, (int) touchEvent.y)
                    && touchEvent.type == TouchEvent.TOUCH_UP) {
                // If the play game area has been touched then swap screens
                game.getScreenManager().removeScreen(this.getName());
                MenuScreen menuScreen = new MenuScreen(game);
                if (Settings.soundEnabled) {
                    screenClickMusic.play();
                }
                // As it's the only added screen it will become active.
                game.getScreenManager().addScreen(menuScreen);
            } /*else if (hazardCardBound.contains((int) touchEvent.x, (int) touchEvent.y)
                    && touchEvent.type == TouchEvent.TOUCH_DOWN) {
                RelativeLayout.LayoutParams lparams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                _xDelta = X - lparams.leftMargin;
                _yDelta = Y - lparams.topMargin;

            }*/
        }
    }
    @Override
    public void draw(ElapsedTime elapsedTime, IGraphics2D graphics2D) {
    //  load hazard playing card
        /*ImageView hazardCardImageView = (ImageView) view.findViewById(R.id.hazardCardImageView);
        if (hazardCard != null) {
            hazardCardImageView.setImageBitmap(hazardCard);
        }

        cardImage1 = (ImageView) rootLayout.findViewById(R.id.hazardCardImageView);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(500, 150);
        cardImage1.setLayoutParams(layoutParams);
        cardImage1.setOnTouchListener(new ChoiceTouchListener());*/

        // Get and draw the bitmaps into the defined rectangles
        Bitmap backButton = game.getAssetManager().getBitmap("backButton");

        // Create the screen to black and define a clip based on the viewport
        graphics2D.clear(Color.BLACK);
        //graphics2D.clipRect(mScreenViewport.toRect());
        // Define the rects what will be used to 'hold' the images
        int spacingX = game.getScreenWidth() / 8;
        int spacingY = game.getScreenHeight() / 8;
        int padding = spacingY / 10;    //padding between each button
        int line = 1;   //each button is on a new 'line' (under each other)

        hazardCardBound = new Rect(spacingX, spacingY * 2 + padding, spacingX * 7, spacingY * 3);

        if (frontLayerBound == null) {
            frontLayerBound = new Rect(0, 0, graphics2D.getSurfaceWidth(),
                    graphics2D.getSurfaceHeight());
        }

        if (backButtonBound == null) {
            int left = 10;
            int bottom = (graphics2D.getSurfaceHeight() - 120);

            backButtonBound = new Rect(left, bottom, left + 100, bottom + 120);
        }

//code added cardImage1 =(ImageView)rootLayout.findViewById(R.id.hazardCardImageView);

        cardImage1.setLayoutParams(layoutParams);
        cardImage1.setOnTouchListener(new ChoiceTouchListener());
        cardImage1.setOnTouchListener(new ChoiceTouchListener());
        cardImage1.setImageBitmap(hazardCard);*/

        //draw bitmaps with relative bounds
        graphics2D.drawBitmap(backgroundBitmap, null, frontLayerBound,null);
        graphics2D.drawBitmap(backButton, null, backButtonBound, null);
        graphics2D.drawBitmap(hazardCard,null, hazardCardBound, null);


        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(500, 150);
        cardImage1.setLayoutParams(layoutParams);
        cardImage1.setImageBitmap(hazardCard);
        cardImage1.setOnTouchListener(new ChoiceTouchListener());

  }

    private final class ChoiceTouchListener implements View.OnTouchListener {
        public boolean onTouch(View view, MotionEvent event) {
            final int X = (int) event.getRawX();
            final int Y = (int) event.getRawY();
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    RelativeLayout.LayoutParams lparams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    _xDelta = X - lparams.leftMargin;
                    _yDelta = Y - lparams.topMargin;
                    break;
                case MotionEvent.ACTION_UP:
                    break;
                case MotionEvent.ACTION_POINTER_DOWN:
                    break;
                case MotionEvent.ACTION_POINTER_UP:
                    break;
                case MotionEvent.ACTION_MOVE:
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    layoutParams.leftMargin = X - _xDelta;
                    layoutParams.topMargin = Y - _yDelta;
                    layoutParams.rightMargin = 0b11111111111111111111111100000110;
                    layoutParams.bottomMargin = 0b11111111111111111111111100000110;
                    view.setLayoutParams(layoutParams);
                    break;
            }
            rootLayout.invalidate();
            return true;
        }
    }

Edit Note: I added in the line of code to initialise the imageView..

Edit: Main activity Class:

import android.app.Activity;
import android.app.FragmentManager;
import android.graphics.PointF;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.example.llave_000.shootout.world.DemoGame;
import android.view.GestureDetector;
import android.widget.ImageView;

public class MainActivity extends Activity implements View.OnTouchListener {

    private float mScaleFactor = 1.0f;
    private float mRotationDegrees = 0.f;
    private float mFocusX = 0.f;
    private float mFocusY = 0.f;
    private ImageView cardImage1;
    private ViewGroup rootLayout;



    /**
     * Game fragment instance
     */
    private Game mGame;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);


        cardImage1 = (ImageView) rootLayout.findViewById(R.id.hazardCardImageView);

        // Setup Gesture Detectors
        mScaleDetector = new ScaleGestureDetector(getApplicationContext(), new ScaleListener());
        /*mRotateDetector = new RotationGestureDetector(getApplicationContext(), new RotateListener());
        mMoveDetector = new MoveGestureDetector(getApplicationContext(), new MoveListener());*/


        // Setup the window as suitable for a game, namely: full screen
        // with no title and a request to keep the screen on. The changes
        // are made before any content is inflated.
        Window window = getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        // Set the content view to use a simple frame layout
        setContentView(R.layout.activity_main);

        // Add in the main game fragment..
        FragmentManager fm = getFragmentManager();
       // MenuScreen menuScreen = (MenuScreen)fm.findFragmentById(R.id.activity_main_id);
        mGame = (Game)fm.findFragmentById(R.id.activity_main_id);

        if (mGame == null) {
            mGame = new DemoGame(); //not sure if correct
            fm.beginTransaction().add(R.id.activity_main_id, mGame)
                    .commit();
        }


    }



    @Override
    public void onBackPressed() {
        // If the fragment does not consume the back event then
        // trigger the default behaviour
        if(!mGame.onBackPressed())
            super.onBackPressed();
    }

   /* public boolean onTouchEvent(MotionEvent me) {
        if (me.getAction() == MotionEvent.ACTION_DOWN) {
            //code in here to take me to new screen with match attax background
            //with new screen displaying a card. then work on being able to move that card.

            //playButtonY -= 20;

        }*/
       // playButton.setY(playButtonY);
        //code in here to take me to new screen with match attax background
        //with new screen displaying a card. then work on being able to move that card.

        //return true;
    }

New Error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.llave_000.shootout/com.example.llave_000.shootout.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
    at com.example.llave_000.shootout.MainActivity.onCreate(MainActivity.java:42)
    at android.app.Activity.performCreate(Activity.java:6662)

Edit:: GameScreen Class:

import com.example.llave_000.shootout.Game;
import com.example.llave_000.shootout.engine.ElapsedTime;
import com.example.llave_000.shootout.engine.graphics.IGraphics2D;
import com.example.llave_000.shootout.util.ILifeCycle;

/**
 * GameScreen - represents a type of Screen in the Game.
 * methods
 * 
 */
public abstract class GameScreen {

    /**
     * Name that is given to this game screen
     */
    protected final String name;

    /**
     * Return the name of this game screen
     * 
     * @return Name of this game screen
     */
    public String getName() {
        return name;
    }

    /**
     * Game to which game screen belongs
     */
    protected final Game game;

    /**
     * Return the game to which this game screen is attached
     * 
     * @return Game to which screen is attached
     */
    public Game getGame() {
        return game;
    }

    /**
     * Create a new game screen associated with the specified game instance
     * 
     * @param game
     *            Game instance to which the game screen belongs
     */
    public GameScreen(String name, Game game) {
        this.name = name;
        this.game = game;
    }

    /**
     * Update the game screen. Invoked automatically from the game.
     * 
     * NOTE: If the update is multi-threaded control should not be returned from
     * the update call until all update processes have completed.
     * 
     * @param elapsedTime
     *            Elapsed time information for the frame
     */
    public abstract void update(ElapsedTime elapsedTime);

    /**
     * Draw the game screen. Invoked automatically from the game.
     * 
     * @param elapsedTime
     *            Elapsed time information for the frame
     * @param graphics2D
     *            Graphics instance used to draw the screen
     */
    public abstract void draw(ElapsedTime elapsedTime, IGraphics2D graphics2D);

    /**
     * Invoked automatically by the game whenever the app is paused.
     */
    public void pause() {
    }
    /**
     * Invoked automatically by the game whenever the app is resumed.
     */
    public void resume() {
    }

    /**
     * Invoked automatically by the game whenever the app is disposed.
     */
    public void dispose() {
    }
}
Sufian
  • 6,405
  • 16
  • 66
  • 120
Liam
  • 429
  • 1
  • 13
  • 33
  • 4
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – QBrute Apr 19 '17 at 13:20

1 Answers1

0

Your cardImage1 is not initialized. You are setting layout params on a null imageview. That is why it's getting NullPointerException. If it solves your problem then it's good otherwise update your question and the error log.

Malwinder Singh
  • 6,644
  • 14
  • 65
  • 103
  • I added a line of code to initialise it. but not sure if it is appropriate.. How do I initialise an imageView to a bitmap that is already loaded? – Liam Apr 19 '17 at 13:27
  • Your details are not complete, 1. What is `GameScreen` a widget or an activity or a fragment? (i suppose a widget as i can't see OnCreate() method) 2. If it's a widget, then you cannot initialize `cardview1` there, as it can be done in activity or fragment only that's why you are getting the said error. – Malwinder Singh Apr 19 '17 at 13:40
  • I put this line of code: cardImage1 = (ImageView) rootLayout.findViewById(R.id.hazardCardImageView); in to my MainActivity class, in the onCreate method. Error now :java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.llave_000.shootout/com.example.llave_000.shootout.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference Caused by: java.lang.NullPointerException: at com.example.llave_000.shootout.MainActivity.onCreate(MainActivity.java:42) – Liam Apr 19 '17 at 14:29
  • do not use rootlayout.findviewbyid() in activity but only findviewbyid(). You use rootlayout in fragment – Malwinder Singh Apr 19 '17 at 14:33
  • seems like this method for dragging and dropping loaded bitmaps will not work as I do not use fragments.. the bitmaps are loaded in each screen, how will initialising an imageview in the mainactivity java class work for the gamescreens. Just keep getting NullPointerException – Liam Apr 19 '17 at 14:47
  • I'm sorry buddy, i don't do game development. I don't know what type of widget does your `GameScreen` is. – Malwinder Singh Apr 19 '17 at 15:32
  • I included my gamescreen class in the main post. – Liam Apr 19 '17 at 16:01