【问题标题】:How to stop an ArrayList from being cleared如何阻止 ArrayList 被清除
【发布时间】:2023-03-25 01:37:02
【问题描述】:

我有一个包含某些文件列表的 Android 应用程序。

文件在这样的 ArrayList 中

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

上述 ArrayList 存在于应用程序类中。

主要问题是假设用户将我的应用程序最小化一段时间,直到我的应用程序正在加载文件列表并且用户开始使用其他应用程序。在我的应用程序中加载完成后,list 包含所有必要文件的列表。用户在一段时间后返回,但与此同时,当用户使用其他应用程序时,Android 系统需要释放一些内存,因此它会清除我的应用程序中的 ArrayList,因为我的应用程序在最近的列表中并且当前未被使用用户。

所以当用户返回时,他必须再次等待直到加载结束。

是否有任何解决方案,因为我不想永远保存 ArrayList,但希望它不会被 Android 系统清除。

【问题讨论】:

  • 列表中有多少项?用户还需要在应用程序的不同会话中使用这些项目吗?应用程序不同启动之间的那些文件更改或它们始终相同?
  • @PierGiorgioMisley 可能有多达 1000 个左右的项目。对于 App Start,项目应保持不变,但可以在不同的 App Start 上更改。
  • 将数组写入文件。在应用启动时,从该文件中读取数据。
  • @ZUNJAE 谢谢。但是保存数组并再次检索它可能需要一些我不需要的时间,因为我不想保存它们以供重复使用。
  • 需要多长时间?我想知道

标签: java android memory arraylist memory-management


【解决方案1】:

您也可以使用 Singleton 类来服务这个用例。

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);
    }
}

【讨论】:

  • 谢谢。但是,如果 Android 系统需要释放一些内存并且我的应用程序在最近列表中,这种方法会保护 ArrayList 不被清除吗?如果我的应用关闭,ArrayList 会发生什么?
  • 一旦应用程序被杀死,所有Holder类的实例都会被GC删除,同时也会调用活动的OnDestroy。你需要这样编码,一旦调用onCreate你需要创建 Holder 类的实例并将值添加到数组列表中。
【解决方案2】:

您可以考虑使用 SharedPreferences

编辑。

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();

【讨论】:

  • 谢谢。但正如我之前所说,我不想永远保存它。但只是不希望它被清除。在共享首选项中存储大(1000 大小)ArrayList 也会导致任何问题。
  • 您可以随时清除该数据。无论如何,@Priyank 的回答也可能适合你
  • @FerhatErgün 谢谢,我会试试最适合我的。
【解决方案3】:

如果您在活动类中保留列表,并将文件路径存储为String,那么此代码将满足您的目的:

对于字符串数组:

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");
}

【讨论】:

  • 谢谢。但是可以在Application类中使用这种设置吗?
  • 不,因为这些方法是activity class 的一部分。
  • 谢谢。将尝试这个并检查哪种答案方法最适合我。
猜你喜欢
  • 1970-01-01
  • 2013-04-23
  • 2013-04-06
  • 2022-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-19
相关资源
最近更新 更多