user7436941
user7436941

Reputation:

I can't access a objects attribute

I have made a class named Point. I create an object of it named "A" on my MainActivity. Now I want some methods on the MainActivity which should read the attributes of "A" but it's not possible. Why I cant access my self made object "A" of class Point? For Example the method "addition" cant read the attribute "x" and "y" of the object "A". Why?

public class Point {

    public int x;
    public int y;
    public Map <String, Integer> paths = new HashMap<String, Integer>();

}

lll

public class MainActivity extends AppCompatActivity {

Point A, B, C, D;
int i;
TextView tv;


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

        tv = findViewById(R.id.tv);

        Point A = new Point();
        A.x = 1;
        A.y = 1;
        A.paths.put("B", 1);
        A.paths.put("C", 2);

        addition();

    }

    private void addition() {


    tv.setText(""+A.x);

    }
}

EDIT: tv.setText(""+A.x); gives me now a NullpointerExeption

 Caused by: java.lang.NullPointerException: Attempt to read from field 'int com.example.georg.pathfinding.Point.x' on a null object reference
        at com.example.georg.pathfinding.MainActivity.addition(MainActivity.java:57)
        at com.example.georg.pathfinding.MainActivity.onCreate(MainActivity.java:49)

Upvotes: 0

Views: 440

Answers (2)

AskNilesh
AskNilesh

Reputation: 69709

Try this declare your Point A as global

public class MainActivity extends AppCompatActivity {

        Point A, B, C, D;
        int i;
        TextView tv;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            tv = findViewById(R.id.tv);

             A = new Point();
            A.x = 1;
            A.y = 1;
            A.paths.put("B", 1);
            A.paths.put("C", 2);

            addition();

        }

        private void addition() {

             tv.setText(""+A.x);

        }

    }

Upvotes: 1

Raj
Raj

Reputation: 3001

Pass the values to your method:-

public class MainActivity extends AppCompatActivity {

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

        Point A = new Point();
        A.x = 1;
        A.y = 1;
        A.paths.put("B", 1);
        A.paths.put("C", 2);

        addition(A.x, A.y);

    }

    private void addition(int a, int b) {

         int i;
         i = a + b;

    }

}

Upvotes: 0

Related Questions