Arafat
Arafat

Reputation: 368

Can I access variables, methods of an Activity Class from a Non-Activity-Class?

I want to operate some functionality of my activity class from another class. Because my the number of codes in activity class is increasing and difficult to understand later.

This is the activity class

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private int number = 7;
    public String name = "arafat";

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

        printSomething();
    }

    private void printSomething() {
        System.out.println("Hello, World!");
    }
}

and here is the non-activity class

NonActivityClass.java

public class NonActivityClass {
    //can I access the variables and methods from here
}

How can I will be able to access the global or private fields of activity class from this non-activity class?

Upvotes: 1

Views: 1035

Answers (1)

Android Geek
Android Geek

Reputation: 9225

I have solved this problem,use oop concept and static keyword

I have use one java class and one Activity.I have create Java class object in Activity to call and access class methods and variables like this

This is my code:

public class NonActivityClass {
 String Myname = "demo";
static String  Myfullname = "";

public static void setName(String name) {
    Myfullname = name;
}

public  String getName() {
    Log.e("check_value","working");
}
public static String getFullName() {
    return Myfullname;
}
}

In this class i have create some static or not static variable and some method like getname(),setname()and getFullname();

MainActivity.java

import android.os.Bundle;
 import android.support.v7.app.AppCompatActivity;
 import android.util.Log;

 import static com.example.rdprojects.NonActivityClass.Myfullname;
 import static com.example.rdprojects.NonActivityClass.getFullName;


 public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

  //create NonActivityClass object
    NonActivityClass myclass = new NonActivityClass();

       myclass.getName();

    //call static variable
    Myfullname = "demo demo";
    String fullname = getFullName();

    Log.e("check_full_name", "" + fullname);

}


}

In this activity first of all i have create java class object and use this object to call variable and method . and some static method call directly . if you try to get data form any java class to in activity try this code.

Upvotes: 1

Related Questions