Home > Software engineering >  How to access array from different activity?
How to access array from different activity?

Time:09-30

Yes I'm really new to android and I'm wokring on a very simple app. On my mainActivity I'm creating and array, and want to access the array from a different activity.

public class Activity extends  {
    MyAreas[] myArea;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
         myArea= new MyAreas[2];
    
         myArea[0] = new MyAreas(33, 44, "Location ", "active");
         myArea[1] = new MyAreas(32, 434, "Location 2", "active");

Class

public class MyAreas{
    public double val;
    public double val2;
    public String name;
    public String status;

    public MyAreas(double val, double val2, String name, String status) {
        this.val= val;
        this.val2= val2;
        this.name = name;
        this.status = status;
    }

I'm trying to access myarea array from my activity2.java, I tried this but didn't work.

private ArrayList<MyAreas> mMyAreasList;

CodePudding user response:

Using Parcelable to pass data between Activity

Here is answer which should help.

CodePudding user response:

In regular Java you can use getters to obtain objects or any variable from a different class. Here is a good article on encapsulation.

In Android, there is a class called Intent that lets you start one activity from another and pass any necessary information to it. Take a look at the developer docs and this other answer which should help you.

CodePudding user response:

For your begginer level, rather than using intents, just set the array object public and static, like that:

public static MyAreas[] myArea;

By that way you can access it from any activity in your app..

Then, go to the activity2.java wherever you want to access it.

MyAreas area = Activity.myArea[0];

CodePudding user response:

The problem with this approach is that you do not have complete control when and in what order the activities are created or destroyed. Activities are sometimes destroyed and automatically restarted in response to some events. So it may happen that the second activity is started before the first activity, and the data is not initialized. For this reason it is not a good idea to use static variables initialized by another activity. The best approach is to pass the data via the intent. The intents are preserved across activity restarts, so the data will be preserved as well. Another approach is to have a static field to keep the data, and initialize the data in an Application instance.

  • Related