Chitra Nandpal
Chitra Nandpal

Reputation: 443

How to Store Each Coordinates into Two Dimensional Array Android

There is Method onTouchEvent() in Android. I get x and y Coordinates from this method. I want to store each Coordinates into Two Dimensional Array. How should I do it? Any Suggestions ??

Below is My Code

 @Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int) event.getX();
    int y = (int) event.getY();
    switch (event.getAction()){
        case MotionEvent.ACTION_DOWN:
            Log.e("TAG", "Action down :==>>"+ x + "," + y + "");
            return true;
        case MotionEvent.ACTION_MOVE:
            return true;
        case MotionEvent.ACTION_UP:
            Log.e("TAG", "Action up:==>>"+ x + "," + y + "");
            return true;
        case (MotionEvent.ACTION_CANCEL) :
            Log.d("TAG","Action was CANCEL");
            return true;
        case (MotionEvent.ACTION_OUTSIDE) :
            Log.d("TAG","Movement occurred outside bounds ");
            return true;
        default :
            return false;
    }
}

Upvotes: 0

Views: 368

Answers (2)

karan
karan

Reputation: 8853

Create POJO class for storing coordinates

public class CoordinatePoint {
    int x, y;

    public CoordinatePoint(int x, int y){
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
}

Now create ArrayList<CoordinatePoint> in your activity and you can create and store objects in it. You can either use the constructor or set values of x and y using setter methods to your CoordinatePoint Object. And get the assigned values using the getter methods.

Edit As suggested by @pskink you can also use Point / PointF class to achieve functionality you want without creating a separate class. check the documentation here and here.

Upvotes: 2

DemiDust
DemiDust

Reputation: 333

Why should you use 2D array?

You can declare Coordinates class which contains X and Y

then make a List

After that just keep adding it list.add(coordinates), much simpler than 2D array

Upvotes: 1

Related Questions