-2

I am storing scores in a ArrayList, but when the user has a score equal to a previous score, the second one is not added to the ArrayList. How can I add equal values to a ArrayList (or use another type of List)?

Code:

[...]
ArrayList<String> savedArray = new ArrayList<>();
Set<String> gandula = new HashSet<>();
[...]
public Preferencias(Context contextoParametro) {
    contexto = contextoParametro;
    preferences = contexto.getSharedPreferences(NOME_ARQUIVO, MODE);
    editor = preferences.edit();
    }

public void addMediaGeral(double mediaGeral) {
   //Save Score
   Set<String> set = new HashSet<String>();
   if (!getMediaGeral().get(0).equals("0")) {
       savedArray.addAll(getMediaGeral());
   }
   savedArray.add(String.valueOf(mediaGeral));
   set.addAll(savedArray);
   editor.putStringSet(KEY_MEDIA_GERAL, set);
   editor.commit();
}

public ArrayList<String> getMediaGeral(){
    //get score
    Set<String> set = preferences.getStringSet(KEY_MEDIA_GERAL, gandula);
    ArrayList<String> list = new ArrayList<String>(set);
    return list;
}
[...]

Retrieving in my activity:

[...]
mediaGeral = score;
preferencias.addMediaGeral(Double.parseDouble(mediaGeral));
[...]
ArrayList<String> string_medias = new ArrayList<>();
    string_medias = preferencias.getMediaGeral();
    ArrayList<Float> float_medias = new ArrayList<>();
    for (int j = 0; j < string_medias.size(); j++){
        float_medias.add(Float.parseFloat(string_medias.get(j)));
    }
    Log.i("TESTANDO PRF", "TAMANHO DA LISTA: "+float_medias.size());
    Float[] dataObjects = float_medias.toArray(new 
    Float[float_medias.size()]);
    doChart(float_medias);
    [...]

I scored 0.33333 three times (I'll config decimal places) but it is showing only one score 0.3333.

Printscreen: http://prntscr.com/f1vx3h

But the chart accepts duplicates. Printscreen: http://prntscr.com/f1vxng (i manipulated the scores in the last printscreen).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
GLAPPs Mobile
  • 99
  • 1
  • 1
  • 12

2 Answers2

0

ArrayList accept duplicate this should not be your problem but I saw that your store yours score in a HashSet uses a hashMap instead because:

In the case of HashMap, it replaces the old value with the new one.

In the case of HashSet, the item isn't inserted.

lenon bob
  • 25
  • 8
0

A Set does not allow for duplicate values.

Doing this:

set.addAll(savedArray);

discards all your duplicates.

These answers may be of help.

Saving a JSON object as a string in preferences would probably be the way to go.

Community
  • 1
  • 1
rguessford
  • 370
  • 4
  • 10