如何在添加新项目后更新ListView?

时间:2016-04-06 09:16:05

标签: android listview android-arrayadapter

我正在开发一个购物清单应用程序,但在添加新项目后无法刷新列表视图。在数据库中添加新项后,ListView不会刷新。如果我进入项目详细信息页面然后返回主活动,则再次调用onCreate并正确刷新它。

如果我在addItemToDb()(单击按钮上)方法中调用refresh方法,它会复制我的项目,但不会将它们添加到数据库中。 有谁有过这个问题之前??? 这是代码:

列表视图适配器

    public class ItemListViewAdapter extends ArrayAdapter<ItemModel> {
    Activity activity;
    int layoutResource;
    ArrayList<ItemModel> itemModelArrayList = new ArrayList<>();

    public ItemListViewAdapter(Activity act, int resource, ArrayList<ItemModel> data) {
        super(act, resource, data);

        activity = act;
        layoutResource = resource;
        itemModelArrayList = data;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return itemModelArrayList.size();
    }

    @Override
    public ItemModel getItem(int position) {
        return itemModelArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View row = convertView;
        final ViewHolder holder;

        if (row == null || (row.getTag()) == null) {

            LayoutInflater inflater = LayoutInflater.from(activity);
            row = inflater.inflate(layoutResource, null);

            holder = new ViewHolder();

            holder.hItemName = (TextView) row.findViewById(R.id.custom_row_productName);
            holder.hItemPrice = (TextView) row.findViewById(R.id.custom_row_productPrice);
            holder.hItemType = (TextView) row.findViewById(R.id.custom_row_productType);
            holder.hCheckBox = (CheckBox) row.findViewById(R.id.custom_row_checkBox);
            holder.hItemEdit = (ImageView) row.findViewById(R.id.custom_row_edit);

            row.setTag(holder);
        } else {
            holder = (ViewHolder) row.getTag();
        }

        holder.hModel = getItem(position);

        holder.hItemName.setText(holder.hModel.getItemName());
        holder.hItemPrice.setText(String.valueOf(holder.hModel.getItemPrice()));
        holder.hItemType.setText(holder.hModel.getItemType());

        holder.hItemEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int itemID = holder.hModel.getItemId();
                String itemName = holder.hModel.getItemName();
                String itemPrice = String.valueOf(holder.hModel.getItemPrice());
                String itemType = holder.hModel.getItemType();
                String itemDate = holder.hModel.getItemDate();

                Intent intent = new Intent(activity, ItemDetail.class);

                intent.putExtra("id", itemID);
                intent.putExtra("product", itemName);
                intent.putExtra("price", itemPrice);
                intent.putExtra("type", itemType);
                intent.putExtra("date", itemDate);

                startActivity(activity, intent, null);
            }
        });

        return row;
    }

    public class ViewHolder {
        ItemModel hModel;
        TextView hItemName;
        TextView hItemPrice;
        TextView hItemType;
        TextView hItemDate;
        CheckBox hCheckBox;
        ImageView hItemEdit;
    }
}

主要活动

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dbHandler = new DatabaseHandler(getApplicationContext());

    itemNameText = (EditText) findViewById(R.id.activity_main_productName);
    itemPriceText = (EditText) findViewById(R.id.activity_main_productPrice);
    itemTypeSpinner = (Spinner) findViewById(R.id.activity_main_spinner);
    addButton = (Button) findViewById(R.id.activity_main_addButton);
    saveListButton = (FloatingActionButton) findViewById(R.id.activity_main_fab);


    ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.productTypes, R.layout.spinner_item);
    itemTypeSpinner.setAdapter(spinnerAdapter);


    //USE BUTTONS
    addButton.setOnClickListener(this);
    saveListButton.setOnClickListener(this);

    //LIST_VIEW
    listView = (ListView) findViewById(R.id.activity_main_listView);

    //calling methods
    refreshData();
}

    public void refreshData() {
    modelArrayListContainer.clear();

    //GET ITEMS FROM DB
    ArrayList<ItemModel> modelArrayListFromDB = dbHandler.getAllItems();

    for (int i = 0; i < modelArrayListFromDB.size(); i++) {

        int ditemID = modelArrayListFromDB.get(i).getItemId();
        String dItemName = modelArrayListFromDB.get(i).getItemName();
        double dItemPrice = modelArrayListFromDB.get(i).getItemPrice();
        String dItemType = modelArrayListFromDB.get(i).getItemType();
        String dItemDate = modelArrayListFromDB.get(i).getItemDate();

        ItemModel newModel = new ItemModel();

        newModel.setItemId(ditemID);
        newModel.setItemName(dItemName);
        newModel.setItemPrice((int) dItemPrice);
        newModel.setItemType(dItemType);
        newModel.setItemDate(dItemDate);

        modelArrayListContainer.add(newModel);
    }

    //setup Adapter
    itemListViewAdapter = new ItemListViewAdapter(MainActivity.this, R.layout.custom_product_layout_activity_main, modelArrayListContainer);
    listView.setAdapter(itemListViewAdapter);
    itemListViewAdapter.notifyDataSetChanged();
}

        public void addItemToDb() {
        ItemModel model = new ItemModel();

        String spinnerValue = itemTypeSpinner.getSelectedItem().toString();
            model.setItemName(itemNameText.getText().toString().trim());      model.setItemPrice(Double.parseDouble((itemPriceText.getText().toString().trim())));
model.setItemType(spinnerValue);

            dbHandler.addItem(model);
            dbHandler.close();

            Log.v(TAG, "::addItemToDb - itemAdded");

        }
    }

1 个答案:

答案 0 :(得分:2)

您需要在refreshData()函数中致电addItemToDb,如:

     public void addItemToDb() {
        ItemModel model = new ItemModel();

        String spinnerValue = itemTypeSpinner.getSelectedItem().toString();
            model.setItemName(itemNameText.getText().toString().trim());      model.setItemPrice(Double.parseDouble((itemPriceText.getText().toString().trim())));
model.setItemType(spinnerValue);

            dbHandler.addItem(model);
            dbHandler.close();

            Log.v(TAG, "::addItemToDb - itemAdded");
            refreshData();

        }

但是如果您需要自动从数据库更新数据,则需要使用CursorAdaptor并使用Content Providers

<强>更新

还要更改dbhandler中的getAllItems()函数,并在函数的第一行包含以下语句:

modelArrayList.clear();