I have a list in which I want to add data that I take from the database. There is a func function where I add entries to my list . It would seem that after the called function, the size of the list should increase. To verify this, I checked the size immediately after calling the func function. But the size was equal to zero. But if you check the size of the list inside the func function, then it is not at all zero. What could be the reason? I think I do not know some simple basic thing.

PS: For readability, I minimized the size of the code

public class TaskActivity extends AppCompatActivity { ArrayList<Task> list ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_task); list = new ArrayList<>() ; func() ; // вызов функции tx.setText("Size:" + list.size()); //проверка размера } public void func() { Backendless.Persistence.of(Task.class).find(new AsyncCallback<BackendlessCollection<Task>>() { @Override public void handleResponse(BackendlessCollection<Task> response) { Iterator<Task> it = response.getCurrentPage().iterator(); while(it.hasNext()) { Task t = it.next() ; list.add(t) ; } //tx.setText("Size:" + list.size()); // проверка размера внутри функции } @Override public void handleFault(BackendlessFault fault) { Toast.makeText(getApplicationContext() , "WRONG!!!" , Toast.LENGTH_SHORT).show(); } }) ; } 

}

    1 answer 1

    I am not an expert on Java, but judging by the documentation, you are using an asynchronous version of the search. This means at least two things:

    1. The program flow (after calling find ) will not be interrupted.
    2. It takes some time to find .

    It follows from this that you call the func() method, it starts the asynchronous operation and immediately returns to the onCreate method where you check the size of the collection. But, the find method has not yet had time to complete the work and call a callback handleResponse , where you, according to your idea, fill the list collection.

    Here are some ways to solve your problem:

    1. Move / call the verification code into the appropriate AsyncCallback method
    2. Use the synchronous version of find (i.e., the one that blocks the program execution flow while it is running)

    All the same documentation suggests a suitable method:

     public BackendlessCollection<Map> Backendless.Persistence.of( "TABLE-NAME" ).find() 
    • Can you clarify about 'Wait for an asynchronous operation'? How to achieve this? - abay
    • Slightly corrected the answer. Perhaps even Java experts will tell you how. - Artyom Okonechnikov