【问题标题】:How to prevent storing duplicate strings in internal storage如何防止在内部存储中存储重复的字符串
【发布时间】:2017-03-24 09:03:31
【问题描述】:

我从两天开始尝试,但没有成功。我在片段的 onStop 方法中将 arraylist 保存在内部存储中,然后在 onresume 方法中从内部存储中取回这些数据。我正在检查字符串是否存在于内部存储的数组列表中,以防止在内部存储中存储重复的字符串,但这似乎不起作用。它每次都在内部存储中存储重复的字符串。我不明白我在这里做错了什么。我将非常感谢您的帮助。

 public void saveTitleList (){
    try {
        FileOutputStream fileOutputStream= mContext.openFileOutput("radiotitle2.txt",MODE_PRIVATE);
        DataOutputStream dataOutputStream=new DataOutputStream(fileOutputStream);
        dataOutputStream.writeInt(stationName2.size());
        ArrayList<String> titletest=getTitleList();
        for(String line:stationName2){
            if(!titletest.contains(line)){//here i am checking for duplicate strings in intenal file
                dataOutputStream.writeUTF(line);
                Log.d("title2 saved",line);
            }

        }
        dataOutputStream.flush();
        dataOutputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public ArrayList<String> getTitleList(){
    ArrayList<String> titleList= new ArrayList<>();
    try {
        FileInputStream fileInputStream= mContext.openFileInput("radiotitle2.txt");
        DataInputStream dataInputStream= new DataInputStream(fileInputStream);
        int size=dataInputStream.readInt();
        for(int i =0;i<size;i++){
            String line=dataInputStream.readUTF();
            titleList.add(line);
            Log.d("title2 from storage",line);
        }
        dataInputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return titleList;
}

【问题讨论】:

  • 使用防止重复的集合
  • 感谢您的回答:)

标签: java android android-studio storage internal


【解决方案1】:

ArrayList 允许重复,而 HashSet 不允许重复 s>。 你应该使用 HashSet

Set 接口的重要特点是它不允许 重复的元素;存储独特的元素。

 HashSet <String> titleList= new HashSet <String>();

    try {
    FileInputStream fileInputStream= mContext.openFileInput("radiotitle2.txt");
    DataInputStream dataInputStream= new DataInputStream(fileInputStream);
    int size=dataInputStream.readInt();
    for(int i =0;i<size;i++){
        String line=dataInputStream.readUTF();
        titleList.add(line);
        Log.d("title2 from storage",line);
    }
   ......

【讨论】:

  • 谢谢,我会好好尝试一下 ;))))))))))
【解决方案2】:

您刚刚开始写入 saveTitleList 中的文件,然后直接从同一个文件中读取调用 getTitleList。

那个文件是空的,然后是一个整数。

所以你搞砸了。

你的代码会有什么样的逻辑?

【讨论】:

  • 我真的搞砸了。我唯一想做的就是在写入之前读取内部存储文件以检查重复的字符串
【解决方案3】:

首先要检查重复项,您应该使用 Set/HashSet。 Arraylist contains 方法会在 O(n) 中搜索每个字符串,以检查其是否存在。

你应该这样做的方式是定义一个 hashSet,并开始向它添加字符串。请务必检查字符串是否实际存在。如果存在则不要添加,否则将其添加到哈希集中。

此外,如果您想保存这些数据,以便在您的活动/片段死亡时它可能会持续存在,则将其保存在 onSaveInstance 方法中。

【讨论】:

    猜你喜欢
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多