简体   繁体   中英

Setter/Getter method not working

Hi I am having a problem accessing variables/methods in my view class from my main activity. I just need to return the turns int from GameView.java and be able to access it in MainActivity and then insert it into my database. I try to use GameView mGameView = new GameView(getApplicationContext()); but this doesn't work and I can't access any methods from GameView with this.

My GameView class:

public class GameView extends View {


    int mcolumns = 5;
    int mrows = 5;
    private NetwalkGrid mGame = new NetwalkGrid(mcolumns, mrows);
    private GestureDetector mGestureDetector;
    Random rand = new Random();
    int sizeSqX;
    int sizeSqY;
    int sizeSq;

    int turns = 0;



    Paint bgPaint;


    public GameView(Context context) {
        super(context);
        init();
    }

    private void init() {



    bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        bgPaint.setStyle(Paint.Style.FILL);
        bgPaint.setColor(0xff0000ff);
    mGame.gridCopy();

        for (int col = 0; col < mGame.getColumns(); col++) {
            for (int row = 0; row < mGame.getRows(); row++) {

                int num = rand.nextInt(3) + 1;

                for (int turns = 1; turns < num; turns++) {
                    mGame.rotateRight(col, row);
                }
            }
        }



    }


    @Override
    protected void onDraw(Canvas canvas) {



        canvas.drawColor(Color.BLACK);

        sizeSqX = getWidth() / mcolumns;
        sizeSqY = getHeight() / mrows;

        if (sizeSqX < sizeSqY) {
            sizeSq = sizeSqX;
        }
        else {

            sizeSq = sizeSqY;
        }

        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
        int cellContent;

        int square = 140;
        for (int col = 0; col < mGame.getColumns(); col++) {
            for (int row = 0; row < mGame.getRows(); row++) {

                cellContent = mGame.getGridElem(col,row);
                if (cellContent == 1) {
                    b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down); // Image for down position
                    if (cellContent == 65 && mGame.checkWin()) {
                        b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down_connected);
                    }
                }
                else if (cellContent == 2) {
                    b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right); // Right position
                    if (mGame.checkWin()) {
                        b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right_connected);
                    }
                }
                else if (cellContent == 3) {
                    b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down); // Down right position WORKS
                    if (mGame.checkWin()) {
                        b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down_connected);
                    }
                }



                else {
                    b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder2); //
                }



                canvas.drawBitmap(b, null,new Rect(col * sizeSq, row * sizeSq,col*sizeSq+sizeSq, row*sizeSq+sizeSq), null);

                TextPaint tp = new TextPaint();
                tp.setColor(Color.GREEN);
                tp.setTextSize(70);
                tp.setTypeface(Typeface.create("Courier", Typeface.BOLD));
                canvas.drawText("Moves: " + String.valueOf(turns), 10, 1180, tp);


            }


        }



    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();

        int column = getColTouched(event.getX());
        int row = getRowTouched(event.getY());


        try {
            mGame.rotateRight(column, row);
            System.out.println(mcolumns);



            mGame.checkWin();

            if (mGame.checkWin()) {
                System.out.println("check win works");
                invalidate();




            }
            invalidate();




        }
        catch (ArrayIndexOutOfBoundsException err) {
            System.out.println("User has pressed outside game grid - exception caught");
        }

        turns++;

        return super.onTouchEvent(event);
    }

    public int getColTouched(float x) {
        return (int) (x / sizeSq);
    }

    public int getRowTouched(float y) {
        return (int) (y / sizeSq);
    }

    public int getTurns() {
        return turns;
    }


}

MainActivity:

public class MainActivity extends AppCompatActivity {
    private int mcolumns;
    private int mrows;

    DatabaseHelper myDb;

    String test = "test data";
    int turns;

    static Context appcon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        appcon = this;
        myDb = new DatabaseHelper(this);
    }

    public void runGame(View view){

        Intent intent = new Intent(this, GameViewActivity.class);

        startActivity(intent);
    }

    public void runInstructions(View view) {

        Intent intent = new Intent(this, InstructionsActivity.class);

        startActivity(intent);
    }


    public void setTurns() {
        GameView mGameView = new GameView(getApplicationContext());
        this.turns = mGameView.turns;
        System.out.println("Turns: " + Integer.toString(turns));
    }

    public void AddData() {
        boolean isInserted = myDb.insertData(Integer.toString(turns));
        if(isInserted == true) {
            System.out.println("Data inserted");
        }
        else {
            System.out.println("Data NOT inserted");
        }
    }
}

In MainAcivity , inside setTurns()

Replace this

this.turns = mGameView.turns; //you can't access this variable directly 

with

this.turns = mGameView.getTurns(); // Calling the public method getTurns()

please see this answer for explanation about Access modifiers in Java

There are two ways to fix this.

1. Preferred way:

Add a new Method in GameView class

public int getTurns() {
    return turns;
}

And use this method where you want to access turns like:

this.turns = mGameView.getTurns();

2. Bad way: Make turns variable public.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM