Обновление активности или списка после обновления базы данных - PullRequest
0 голосов
/ 15 июня 2019

Итак, у меня есть свой собственный ArrayAdapter с методом getView, определенным так:

@Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        int orderId = getItem(position).getId();
        int menuId = getItem(position).getMenuId();
        int userId = getItem(position).getUserId();
        String status = getItem(position).getStatus();

        LayoutInflater inflater = LayoutInflater.from(activity);
        convertView = inflater.inflate(resource, parent, false);

        TextView idView = convertView.findViewById(R.id.order_id);
        TextView nameView = convertView.findViewById(R.id.item_name);
        TextView userIdView = convertView.findViewById(R.id.user_id);
        TextView statusView = convertView.findViewById(R.id.status_view);
        ImageButton cancelButton = convertView.findViewById(R.id.order_canceled);
        ImageButton orderDoneButton = convertView.findViewById(R.id.order_done);
        cancelButton.setTag(orderId);
        orderDoneButton.setTag(orderId);

        if(status.equals("done"))
            orderDoneButton.setImageResource(android.R.drawable.checkbox_on_background);
        else {
            orderDoneButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    orderRequest.getGenericRequest().setUri("/" + v.getTag() + "?status=done");
                    orderRequest.put();
//                ((ImageButton)v).setImageResource(android.R.drawable.checkbox_on_background);

                    notifyDataSetChanged();
                    // TODO cheating but it works
//                Intent intent = activity.getIntent();
//                intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
//                activity.startActivity(intent);
                }
            });
        }
  • И моя проблема в том, что, когда я вызываю его так и нажимаю OrderDoneButton, мой список выглядит так:не обновляет себя, даже если я звоню notifyDataSetChanged() и вижу, что база данных обновлена, у меня вопрос: почему?
  • Второй вопрос в этом методе - закомментировано 'Intent', которое работает вкак я хочу, но я не уверен, что это хороший способ сделать это, какие-либо предложения?

1 Ответ

0 голосов
/ 15 июня 2019

вот какое-то объяснение, что я обычно делал

вид установки с адаптером

private ArrayAdapter<String> arrayAdapter;
private ArrayList<String> listPName = new ArrayList<>();
private void showBluetoothPrinters() {
    arrayAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, listPName) {
        @NonNull
        @Override
        public View getView(int position, View convertView, @NotNull ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            TextView tv = view.findViewById(android.R.id.text1);
            tv.setPadding(padding * 3, 0, padding * 3, 0);
            return view;
        }
    };
    lvPrinter.setAdapter(arrayAdapter);
}

затем вызвать notifyDataSetChanged () после обновления некоторых данных

Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
                if (mPairedDevices.size() > 0) {
                    for (BluetoothDevice mDevice : mPairedDevices) {
                        listPName.add(mDevice.getName());
                    }
                }
                if (arrayAdapter != null){
                    arrayAdapter.notifyDataSetChanged();
                }

не знаю, ожидаете ли вы этого

Я добавляю некоторые из фрагментов вызовов notifydatasetchage в адаптер

@Override
public void onBindViewHolder(@NonNull VH holder, int position) {
    int amount = mListData.get(position);
    holder.tvAmount.setText(String.valueOf(amount));
    holder.tvText.setText(decimalFormat.format(amount));

    holder.itemView.setOnClickListener(v -> {
        if (mListener != null){
            mListener.onAmountTapped(amount);
        }
        tempSelected = position;
        notifyDataSetChanged();
    });
    if (position == tempSelected){
        holder.containerView.setBackground(mContext.getResources().getDrawable(R.drawable.rp_shadow_select));
    } else {
        holder.containerView.setBackground(mContext.getResources().getDrawable(R.drawable.rp_shadow));
    }
}
...