Is with the same value as the last time it was used

Asked

Viewed 84 times

1

How do I make the value of contador of for start with the same value as the last time it was used? Why this for always starts when I start to activity, and I need him not to start at 1 every time I start at activity, which are often, because so will add me values to the ArrayList.

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

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


    }
  • 2

    Why the adapter is inside the for?! There’s something wrong there that’s not right.

  • I’ve already pulled the Adapter out of the room and keep repeating it. Because this cycle is started when Activity is indicated, which by chance is often why Arraylist tests will always be added values

  • I wanted the value of the counter to remain constant

1 answer

2


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

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

Then on the part of for I would replace it with a do while and take the amount saved in SharedPreferences to perform 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 do-while the counter is obtained unless and if there is no number1. Then the value of the counter is saved through the editor. And as acklay commented, remove the adapter from inside the loop.

Perhaps 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 what I went through should solve.

  • It didn’t solve , it continues to do while once from(do to myDB.getLastID()) start and then when this Activity is started again do do while do 0 for myDB.getLastID() again

  • I did with Static only that the problem is that when I left Activity and reopened it did not execute because the value of the counter was equal to myDB.getLastID()

  • The myDB.getLastID() starts at 0? Try changing the counter to start with 0 int contador = config.getInt("contador", 0);. The SharedPreferences keeps the saved value even closing the app.

  • Also try to print the values of myDB.getLastID() to see if they’re right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.