简体   繁体   中英

Android Communicating between classes

I have a question about communicating between classes in java/android Studio.

I have four classes that pass information to eachother in this way:

MainActivity{

    Intent intent = new Intent (this, Main2Activity.class);
    intent.putStringArrayListExtra("addressesList", addressList);
    startActivity(intent);

}

Main2Activity{

    private ArrayList addressList = new ArrayList();
    addressList = getIntent().getStringArrayListExtra("addressesList");

    Calculate calulate = new Calculate(this);
    calulate.getTravelInformation();

}

Calculate{

    private ApiCall apiCall = new ApiCall(this);

    private ArrayList addressesList = new ArrayList();    

    private Main2Activity activity;

    public Calculate (Main2Activity a){
       activity = a;
       addressesList = activity.addressList;
    }

    protected void doSomething(){
    }

}

ApiCall{

    private Calculate calculate;

    protected ApiCall(Calculate a){
        calculate = a;
    }

    calculate.doSomething();

}

So my question is, are there better ways of doing this and is there any reason why I should not do it like this ?

Thank you in advance for the help.

First thing if you want to communicate between Activities, Intent is the option to communicate. In Calculate you are passing a main2Activity reference if you really need the activity reference you can use Activity class for re-usability in case if you are going to use this class in more than place. I don't know what you you going to write in doSomething() because depends on the method make the class more generic. The same will be applicable to ApiCall . Since you are creating a cyclic dependency between the classes

I understand what you are going through as I went through the same. Let's start with some concepts:

The concept behind the statement "communication between classes" is, in programming, classes never communicate with each other, Actually they are activities. So you have two Activities and two helper Classes. As you are using Intent, yeah Intent is the way by which you can make communication between activities (like sharing data etc.) and we feel like classes are communicating with each other. So you have used Intent Object to make communication, it's very correct way of doing that, no problem, you are going right and now, you have used two helper classes, and you are writing the methods in correct way keep going. Best of luck.

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