skip to Main Content

Doing a little test in Java:
In a class called A, I created a simple variable called name, setting "John" as value:

String name = "John";

In class B, I want this variable to be identified. So even writing the complete package import from class A in class B, and even writing in class B:

A.name;

The IDE is unable to identify the variable name in the class A.

The IDE is Android Studio, and it’s an Android application that already has the AppCompatActivity extends, and doesn’t allow multiple inheritance.

2

Answers


  1. Chosen as BEST ANSWER

    I created an object of the Intent class called receiverIntent, to receive a variable from the previous class.

    Intent receiverIntent = getIntent();
    

    Then I created a variable called completeName, to receive a variable called "name", through an Intent:

        String completeName = receiverIntent.getStringExtra("name");
    

    But I want to send this completeName variable to another class without needing to use Intent. For that I tried using public static. But error happens.
    It Displays the following error in the receiverIntent object: "Non-static field receiverIntent cannot be referenced from a static context":

    enter image description here

    Please, how can I make the completeName variable as being public and static so that another class can recognize this variable called completeName without an error?


  2. For that to work, to you need to declare the variable as

    • static so that you can access it without an instance of A (which is what you are trying to do)
    • public in case that B is in a different package

    …making the line look like this:

    public static String name = "John";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search