S
S
Sergey Shilovsky2018-06-18 18:52:24
Java
Sergey Shilovsky, 2018-06-18 18:52:24

How to update a reference inside a nested class definition?

A bit strange wording of the question, but I couldn't think of a better one. There is a code (simplified to see the main thing):

@Override
protected void onCreate(){
  Callback call = new Callback((answer)->{
    MyAdapter adapter = new MyAdapter(answer);
    
    ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
      @Override
      public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        adapter.deleteAt(viewHolder.getAdapterPosition());				
    }
  };
  
  btn.setOnClickListener(()->{
    API.response().enqueue(call);
  });
  
  API.response().enqueue(call);
}

After onCreate everything is OK, the adapter created in call == adapter in onSwiped, but in subsequent requests it turns out that the adapter inside ItemTouchHelper.SimpleCallback is not updated. Maybe this should be so, but it misleads me, because in the callback we make it clear that we need exactly new ItemTouchHelper.SimpleCallback

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Shilovsky, 2018-06-18
@First_Spectr

The problem turned out to be outside the provided code, namely in the line just below:

new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);

The new itemTouchHelperCallback was stupidly not attached unless the old one was manually unbind:
if(touchHelper != null)
    touchHelper.attachToRecyclerView(null);
touchHelper = new ItemTouchHelper(itemTouchHelperCallback);
touchHelper.attachToRecyclerView(recyclerView);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question