RecyclerView не обновляется после вызова changeCursor - PullRequest
1 голос
/ 05 августа 2020

Фон:

У меня есть таблица заказов в моей базе данных, данные которой я показываю в RecyclerView. Я делаю это, используя CursorAdapter в RecyclerView.Adapter. Все это выполняется в родительском действии.

Кроме этого, у меня есть дочернее действие, которое отвечает за добавление новых заказов в таблицу заказов и последующее возвращение к родительскому действию для отображения всех заказов в RecyclerView, включая только что созданные. Новые заказы добавляются путем запуска дочернего действия в addOrder().

Проблема:

Когда я возвращаюсь из дочернего действия в родительское действие (после успешного добавления новых заказов в таблицу заказов) Я пытаюсь обновить sh RecyclerView с помощью changeCursor(), но не вижу, чтобы RecyclerView обновлялся новыми данными.

Мой код:

Адаптер:

public class OrderListAdapter extends RecyclerView.Adapter<OrderListAdapter.ViewHolder> {

    private CursorAdapter userList;
    private Context context;

    public OrderListAdapter(Context context, Cursor list){

        this.context = context;
        userList = new CursorAdapter(this.context, list, 0) {
            @Override
            public View newView(Context context, Cursor cursor, ViewGroup parent) {
                // Code for inflater
            }

            @Override
            public void bindView(View view, Context context, Cursor cursor) {
                // Code for bindView
            }
        };
    }

    public CursorAdapter getCursorAdapter(){ return userList; }

    public double getTotalPrice(){
        Cursor records = userList.getCursor();
        double total = 0;
        while (records.moveToNext()) {
              double price = records.getDouble(4);
              int quantity = records.getInt(3);
              total += price * quantity;
        }
        return total;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = userList.newView(context, userList.getCursor(), parent);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        userList.getCursor().moveToPosition(position);
        userList.bindView(holder.itemView, context, userList.getCursor());
    }

    @Override
    public int getItemCount() { return userList.getCount(); }

    public class ViewHolder extends RecyclerView.ViewHolder {
        // declaring holder variables
        public ViewHolder(View itemView){
            super(itemView);
           // Initialising holder variables
        }
    }
}

ParentActivity:

public class ParentActivity extends AppCompatActivity {

     private TextView totalText;
     private OrderListAdapter orderAdapter;
     private RecyclerView orderView; 

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_parent);
         totalText = findViewById(R.id.orderTotal);
         showTable();
     }

     private void setAdapter(Cursor records){
         orderView = findViewById(R.id.tableContent); 
         orderView.setLayoutManager(new LinearLayoutManager(this));
         orderList = new ArrayList<>();
         orderAdapter = new OrderListAdapter(this, records);
         orderView.setAdapter(orderAdapter);
     }

     private void showTotalPrice(){
         double totalPrice = orderAdapter.getTotalPrice();
         totalText.setText(String.valueOf(totalPrice));
     }

     private void showTable(String item){
         totalText.setText("0.0");
         Cursor records = db.query("orders", null, null, null, null, null, null);
         setAdapter(records);
         showTotalPrice();        
     }

     private void updateTable(){
         Cursor records = db.query("orders", null, null, null, null, null, null);
         orderAdapter.getCursorAdapter().changeCursor(records);
     }
     // This is called on click of a button 
     public void addOrder(View view){
         startActivity(new Intent(getApplicationContext(), ChildActivity.class));
         updateTable(); // this doesn't update the RecyclerView
         showTotalPrice();
     }
}

Если я закомментирую showTotalPrice() в addOrder(), RecyclerView, похоже, будет обновляться с новыми заказами. Почему так? почему showTotalPrice() препятствует обновлению? Мне нужно showTotalPrice(), чтобы отобразить обновленную общую стоимость товаров в таблице.

...