2017-03-24 32 views
0

我想从两天开始,但没有取得成功。我在我的片段的onStop方法中将arraylist保存在内部存储中,然后从onresume方法的内部存储中获取此数据。我正在检查要存储在interanlly存储的数组列表中的字符串,以防止在内部存储中存储重复的字符串,但这似乎不起作用。它每次都在内部存储器中存储重复字符串。我不明白我在这里做错了什么。我会非常感谢你的帮助。如何防止在内部存储器中存储重复的字符串

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; 
} 
+0

使用一个将防止重复的集合 – 7663233

+0

感谢您的回答:) – LanguageMaster

回答

1

ArrayList允许重复而HashSet不允许重复。 您应该使用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); 
    } 
    ...... 
+1

谢谢我会亲自尝试它)))))))))) – LanguageMaster

+0

@LanguageMaster确实。 –

0

你刚开始写在saveTitleList一个文件,然后直接从同一个文件调用getTitleList读取。

该文件是空的,然后豁免一个int。

所以你搞砸了。

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

+0

我真的搞砸了。我唯一试图做的是在写入之前阅读内部存储文件以检查重复的字符串 – LanguageMaster

0

首先为了检查重复项目,你应该使用Set/HashSet。 Arraylist包含方法将搜索O(n)中的每个字符串,以检查其是否存在。

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

此外,如果您想要保存此数据,以便在您的活动/片段死亡时它可以保留,然后将其保存在onSaveInstance方法中。

相关问题