简体   繁体   中英

How can I use an array which is in a different class?

I have a 2D array set up in an activity and I want to call it into a fragment so I can use its contents. The array is called "Names". I do not understand the steps involved to do this.

You may want to do some reading up on the Singleton Design Pattern . But in the mean time, I'll get you started.

Create a class "MyData" which will hold all of your variables/arrays that you want to share. Then you simply need a getter method to call the class. Once this is done, you'll be able to access all your shared variables. :)

Example MyData Class:

public class MyData
{
    private static MyData _instance; 

    /* <Shared variables go here> */

    public String sharedVariable = "yay this is shared!";
    public String sharedVariable2 = "this is also shared!";
    public String myArray[][];

    /* </Variables> */

    public static MyData getMyData()
    {
        if(_instance == null)
            _instance = new MyData();

        return _instance;
    }
}

Example activity/fragment where you want to set the data:

MyData data = MyData.getMyData();

data.myArray[0][0] = "test";

Example activity/fragment where you want to GET the data you set:

MyData data = MyData.getMyData();

String result = "";
result = data.myArray[0][0];

// result will now = "test"

By using this structure, if the MyData class is being called for the first time, it will create the instance, and if it HAS been called already, then it will simply return _instance which will contain all the variables you've set.

DISCLAIMER: When your app is minimized or left idle for a while, the android OS will clear all the variables in your class. You have three options to avoid this:

  1. Store the data in a local file and load it back into the class in onResume()
  2. Call the data from your database and reload the class in onResume()
  3. Store your data using SharedPreferences. Then refresh the values of all your variables in the MyData class with the values from your SharedPreferences in onResume()

I usually go with option 3 as it usually fits my needs best.

Good luck!

make your array public, then call from your fragment like

OtherActivity.array[]

You can perform all other operations as normal

  1. Make a Singleton
  2. Make it static public and call Class.yourArray
  3. Create an interface and pass it , in the constructor or simply pass it with some method.
  4. Simply pass a the array as an object to another class

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