简体   繁体   中英

Get value from different class in android/java

I want to get a return value from a function From CLass A in class B. But i do not want to create a new instance of class A in Class B. Since all the variable value in class a are null if i create a new instance. I also cannot use static in the function because i dont get access to non static varible. I have tried using aync task/ handler to but cannot find any way to return value from handle message>

public class ClassA(){
     List<String> stringlist;

    public List<String> getStringlist() {
    //code  
    return stringlist;
     }
}

public class ClassB(){

    public void getValueFromCLassA {
        ClassA classA = new ClassA();
        List<string> string = classA.getStingList();
    }
}

You have 2 ways to do this...

  1. you can send data between activities using parcelable or
  2. you can use Global variables over the hole application.

for the 1st one check my answer here : for the 2nd one: check my answer here :

the 2nd option looks like what you are looking for....

Create your reference to ClassA outside of the getValueFromClassA method. There is no way around "making an instance of class A" to GET a member from class A, unless that member is shared in a different class higher in hierarchy. It's part of the fundamentals of OOP. You can, however, SET ClassB's list by creating a setter method in ClassB and forcing ClassA to send its list to ClassB. The only difference here is now ClassA needs a reference to ClassB and Class *doesn't need a reference to ClassA.

public class ClassA()
{
    List<String> stringList;

    public List<String> getStringlist()
    {
        //code  
        return stringList;
    }
}

public class ClassB()
{
    ClassA classA = new ClassA();
    List<string> stringListB;    

    public void getValueFromClassA()
    {
       stringListB = classA.getStringList();
    }
}

Just save the variables that you need as a global variable. I recommend you having something like this:

public class Environment extends Application {

    public String globar_var = null;
}

//Manifest

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:name=".Environment">  <---------- where the magic happens



After this, you can access the var like this from anywhere in your app:

((Environment) getApplicationContext()).globar_var == "It should work!!"

Hope it helped, let me know how it went :)

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