简体   繁体   中英

How to stop an ArrayList from being cleared

I am having an Android app which has a list of certain files.

The files are in an ArrayList like this

public static ArrayList<File> list=new ArrayList<File>();
list.add("PATH");
list.add("PATH");
list.add("PATH");
....

The above ArrayList is present in the Application Class.

The Main problem is that suppose the user minimizes my app for a while till my app is loading the list of the files and the user starts using some other app. After the loading in my app is over the list contains the list of all the necessary files. The user returns back after some time, but meanwhile when the user is using other app the Android System is requiring to free up some memory so it clears the ArrayList in my app, as my app is in the recent list and not being currently used by the user.

So when the user returns back he has to wait again till the loading is over.

Is there any solution to this as I don't want to save the ArrayList for ever but want it to not be cleared by Android system.

You can also serve this use case with Singleton class.

class Holder
{
    private static Holder instance = null;
    private List<String> itemArray;
    private Holder(){
       itemArray = new ArrayList<>();
    }

    public static Holder getInstance(){
        if (instance == null)
            instance = new Holder();
        return instance;
    }

    public List<String> getItemArray(){
        return new ArrayList<>(this.itemArray);
    }

    public void addItemToArray(String item){
            this.itemArray.add(item);
    }
}

You might consider to use SharedPreferences .

edit .

SharedPreferences preferences = getSharedPreferences("PATH_KEEPER",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();     

//You can use Set<String> or turn into Json and store as String
Set<String> stringSet = new HashSet<>();

stringSet.add("somePath");
stringSet.add("somePath");
editor.putStringSet("Path",stringSet);
editor.apply();

//Whenever you want to remove
editor.clear();

If you keep list in activity class, and store file path as String then this code will serve your purpose:

For String Array:

public static ArrayList<String> list = new ArrayList<String>();

protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putStringArrayList("list", list);
}

protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    list = savedInstanceState.getStringArrayList("list");
}

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