更新数据库对象的特定值

时间:2017-07-06 16:43:04

标签: java android sql

我目前正在建立一个库存,用户应该可以在商品概览/主要活动中点击“购买”按钮,这会将商品的数量减少1。 我已经在另一个活动(所选项目的详细视图)中完成了这项任务,但我似乎无法在主要活动中完成它。

以下是完整的源代码:https://github.com/Fedor98/InventoryApp/tree/master/app/src/main

DetailActivity.java (其中一切正常)

    /**
    * Displays details of item that wes selected in the CatalogActivity.
     */

public class DetailActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {

    /** Tag for the log messages */
    public static final String LOG_TAG = DetailActivity.class.getSimpleName();

    /**
     * Identifier for the inventory data loader
     */
    private static final int EXISTING_INVENTORY_LOADER = 0;

    /** Content URI for the existing item */
    private Uri mCurrentItemUri;

    /** TextView to show item's name */
    private TextView mNameTextView;

    /** TextView to show item's price */
    private TextView mPriceTextView;

    /** TextView to show item's quantity */
    private TextView mQuantityTextView;

    /** TextView to show item's supplier */
    private TextView mSupplierTextView;

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

        // Examine the intent that was used to launch this activity,
        // We're creating a new item.
        Intent intent = getIntent();
        mCurrentItemUri = intent.getData();

        // Change app bar to say "View Item details"
        setTitle(getString(R.string.detail_activity_title_detail_item));

        // Initialize a loader to read the item data from the database
        // and display the current values in the editor
        getLoaderManager().initLoader(EXISTING_INVENTORY_LOADER, null, this);

        // Find all relevant views that we will need to read info from
        mNameTextView = (TextView) findViewById(R.id.name);
        mPriceTextView = (TextView) findViewById(R.id.price);
        mQuantityTextView = (TextView) findViewById(R.id.quantity);
        mSupplierTextView = (TextView) findViewById(R.id.supplier);

        // Find the Button which will increase the item's quantity by 1
        Button increaseButton = (Button) findViewById(R.id.increase_button);

        // Setup the item click listener
        increaseButton.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
              int quantity = Integer.parseInt(mQuantityTextView.getText().toString());
                  quantity = quantity + 1;

                  ContentValues values = new ContentValues();
                  values.put(InventoryEntry.COLUMN_ITEM_QUANTITY, quantity);

                  int rowsAffected = getContentResolver().update(mCurrentItemUri, values, null, null);
                  // Show a toast message depending on whether or not the increasement was successful.
                  if (rowsAffected == 0) {
                      // If no rows were affected, then there was an error with the update.
                      Toast.makeText(DetailActivity.this, "Error with increasing quantity",
                              Toast.LENGTH_SHORT).show();
                  } else {
                      // Otherwise, the update was successful and we can display a toast.
                      Toast.makeText(DetailActivity.this, "Quantity increased by 1",
                              Toast.LENGTH_SHORT).show();
                  }

              }
      });

        // Find the Button which will decrease the item's quantity by 1
        Button decreaseButton = (Button) findViewById(R.id.decrease_button);

        // Setup the item click listener
        decreaseButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                int quantity = Integer.parseInt(mQuantityTextView.getText().toString());
                if (quantity > 0) {
                    quantity = quantity - 1;

                    ContentValues values = new ContentValues();
                    values.put(InventoryEntry.COLUMN_ITEM_QUANTITY, quantity);

                    int rowsAffected = getContentResolver().update(mCurrentItemUri, values, null, null);
                    // Show a toast message depending on whether or not the decreasement was successful.
                    if (rowsAffected == 0) {
                        // If no rows were affected, then there was an error with the update.
                        Toast.makeText(DetailActivity.this, "Error with decreasing quantity",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        // Otherwise, the update was successful and we can display a toast.
                        Toast.makeText(DetailActivity.this, "Quantity decreased by 1",
                                Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(DetailActivity.this,
                            "Cannot set quantity to a value lower than 0",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    [...]
    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // User clicked on a menu option in the app bar overflow menu
            switch (item.getItemId()) {
                // Respond to a click on the "Delete" menu option
                case R.id.action_delete:
                    // Pop up confirmation dialog for deletion
                    showDeleteConfirmationDialog();
                    return true;
                case R.id.action_shop:
                    purchaseItem();
                    return true;
            }
            return super.onOptionsItemSelected(item);
        }
    [...]

    public void purchaseItem() {
            int quantity = Integer.parseInt(mQuantityTextView.getText().toString());
            if (quantity > 0) {
                quantity = quantity - 1;

                ContentValues values = new ContentValues();
                values.put(InventoryEntry.COLUMN_ITEM_QUANTITY, quantity);

                int rowsAffected = getContentResolver().update(mCurrentItemUri, values, null, null);
                // Show a toast message depending on whether or not the purchase was successful.
                if (rowsAffected == 0) {
                    // If no rows were affected, then there was an error with the update.
                    Toast.makeText(DetailActivity.this, "Error with purchasing product",
                            Toast.LENGTH_SHORT).show();
                } else {
                    // Otherwise, the update was successful and we can display a toast.
                    Toast.makeText(DetailActivity.this, "Purchase was successful",
                            Toast.LENGTH_SHORT).show();
                }

            } else {
                Toast.makeText(DetailActivity.this,
                        "Item sold out",
                        Toast.LENGTH_SHORT).show();
            }
        }

InventoryCursorAdapter.java (我需要最后的onClickListener与上面方法中的减少功能相同)

 /**{@link InventoryCursorAdapter} is an adapter for a list or grid view
 * that uses a {@link Cursor} of inventory data as its data source. This adapter knows
 * how to create list items for each row of inventory data in the {@link Cursor}.
 */
public class InventoryCursorAdapter extends CursorAdapter {

    /** Tag for the log messages */
    public static final String LOG_TAG = DetailActivity.class.getSimpleName();

    /** Content URI for the existing item */
    private Uri mCurrentItemUri;

    /**
     * Constructs a new {@link InventoryCursorAdapter}.
     *
     * @param context The context
     * @param c       The cursor from which to get the data.
     */
    public InventoryCursorAdapter(Context context, Cursor c) {
        super(context, c, 0 /* flags */);
    }

    /**
     * Makes a new blank list item view. No data is set (or bound) to the views yet.
     *
     * @param context app context
     * @param cursor  The cursor from which to get the data. The cursor is already
     *                moved to the correct position.
     * @param parent  The parent to which the new view is attached to
     * @return the newly created list item view.
     */
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // Inflate a list item view using the layout specified in list_item.xml
        return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
    }

    /**
     * This method binds the inventory data (in the current row pointed to by cursor) to the given
     * list item layout. For example, the name for the current item can be set on the name TextView
     * in the list item layout.
     *
     * @param view    Existing view, returned earlier by newView() method
     * @param context app context
     * @param cursor  The cursor from which to get the data. The cursor is already moved to the
     *                correct row.
     */
    @Override
    public void bindView(View view, final Context context, Cursor cursor) {
        // Find individual views that we want to modify in the list item layout
        TextView nameTextView = (TextView) view.findViewById(R.id.name_catalog);
        final TextView quantityTextView = (TextView) view.findViewById(R.id.quantity_catalog);
        TextView priceTextView = (TextView) view.findViewById(R.id.price_catalog);

        // Find the columns of item attributes that we're interested in
        int nameColumnIndex = cursor.getColumnIndex(InventoryEntry.COLUMN_ITEM_NAME);
        final int quantityColumnIndex = cursor.getColumnIndex(InventoryEntry.COLUMN_ITEM_QUANTITY);
        int priceColumnIndex = cursor.getColumnIndex(InventoryEntry.COLUMN_ITEM_PRICE);

        // Read the item attributes from the Cursor for the current item
        String itemName = cursor.getString(nameColumnIndex);
        String itemQuantity = cursor.getString(Integer.parseInt(Integer.toString(quantityColumnIndex)));
        String itemPrice = cursor.getString(priceColumnIndex);
        itemPrice = itemPrice + "€";

        // Update the TextViews with the attributes for the current item
        nameTextView.setText(itemName);
        quantityTextView.setText(itemQuantity);
        priceTextView.setText(itemPrice);

        mCurrentItemUri = ContentUris.withAppendedId(InventoryEntry.CONTENT_URI, id);

        // Find the Button which will decrease the item's quantity by 1
        Button saleButton = (Button) view.findViewById(R.id.sale_button);

        // Setup the item click listener
        saleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

提前感谢您的帮助。我很迷茫,从几天开始坐在这里,没有再进一步......

0 个答案:

没有答案