For the same value last time it was used [closed]

1

How do I make the value of contador of for start with the same value as last time it was used? Because this for always starts when I start activity , and I need it to not start at 1 each time I start activity , which is often because then it will add me more values in ArrayList .

   for(int contador = 1 ;contador<=myDB.getLastId();contador++){

        testes.add("Data:  "+myDB.getDates(contador)+"        "+myDB.getHour(contador)+"\n"+"Discilpina:  "+myDB.getDisciplina(contador));


    }
    
asked by anonymous 18.07.2017 / 19:29

1 answer

2

One way to solve this is to use SharedPreferences to save your counter number. First Instance:

SharedPreferences config = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = config.edit();

Then in the for part I would replace a do while and get the value saved in the SharedPreferences to make the loop. It would look like this:

int contador = config.getInt("contador", 1);

  do {
      testes.add("Data:  "+myDB.getDates(contador)+"        "+myDB.getHour(contador)+"\n"+"Discilpina:  "+myDB.getDisciplina(contador));
      contador++;
    } while (contador<=myDB.getLastId());

editor.putInt("contador", contador);
ListAdapter adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,testes);
testList.setAdapter(adapter);

Note that before the% w / o of% the saved counter is obtained and if none is taken the number do-while is obtained. Then the counter value is saved through 1 . And as acklay commented, remove the editor from within the loop.

Maybe it would be better to use a static variable with the counter or change the architecture of your project to a more systematic way but this is what I have to solve.

    
18.07.2017 / 20:06