简体   繁体   中英

How can I separate my ArrayList to different java class?

Good day, this is my QuestionActivity. Class and I want ArrayList<BasicItem> BasicList to put this on different class and still use it in this activity.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_question);


    final ArrayList<BasicItem> BasicList = new ArrayList<>();
    BasicList.add(new BasicItem();
    BasicList.add(new BasicItem();
    BasicList.add(new BasicItem();
    BasicList.add(new BasicItem();

My reason to separate this because, in the actual app, this activity become laggy and I'm gonna put 600 items. and I think separating it might help. Thanks in advance.

You just need to create a separate utility class that can be sharable for different activities/fragments), and you can utilize the singleton pattern for this to avoid multiple instantiations.

public class Utility {

    ArrayList<BasicItem> BasicList;
    private static Utility mUtility;

    private Utility() {
        BasicList = new ArrayList<>();
        BasicList.add(new BasicItem());
        BasicList.add(new BasicItem());
        BasicList.add(new BasicItem());
        BasicList.add(new BasicItem());
    }

    static Utility newInstance() {
        if (mUtility == null) {
            mUtility = new Utility();
        }
        return mUtility;
    }

}

And to use it in activity/fragment

Utility utility = Utility.newInstance();
BasicItem item = utility.BasicList.get(0);

You can also consider using the.

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