无法使用sqlite计算购物车中的总价金额

时间:2021-04-01 16:03:40

标签: android android-sqlite

我想使用 SQLite 计算购物车中产品的总价。当我使用 Settext() 在 textview 中设置价格时,它不会返回总和值。这是 DBhelper 类中的 gettotalprice 方法。

public int getTotalExpenses()
    {
        int total = 0;
        SQLiteDatabase database = this.getReadableDatabase();
        Cursor cursor = database.rawQuery("SELECT SUM("+ OrderContract.OrderEntry.COLUMN_PRICE + ") FROM " + OrderContract.OrderEntry.TABLE_NAME, null);
        if (cursor.moveToFirst())
        {
            total = cursor.getInt(4);
        }
        while (cursor.moveToNext());
        return total;
    }

OrderProvider 类:

package com.example.myapp;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class OrderProvider extends ContentProvider {

    // this constant is needed in order to define the path of our modification in the table
    public static final int ORDER=100;

    public DBHelper mhelper;
    public static UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        sUriMatcher.addURI(OrderContract.CONTENT_AUTHORITY,OrderContract.PATH,ORDER);
    }


    @Override
    public boolean onCreate() {

        mhelper = new DBHelper(getContext());

        return true;
    }


    @Override
    public Cursor query( Uri uri,  String[] projection,  String selection,  String[] selectionArgs, String sortOrder) {


        SQLiteDatabase database = mhelper.getReadableDatabase();
        Cursor cursor;
        int match = sUriMatcher.match(uri);
        switch (match){
            case ORDER:
                cursor = database.query(OrderContract.OrderEntry.TABLE_NAME, projection, selection, selectionArgs, null,null, sortOrder);
                break;

            default:
                throw new IllegalArgumentException("CANT QUERY");
        }

        cursor.setNotificationUri(getContext().getContentResolver(),uri);
        return cursor;

    }


    @Override
    public String getType(Uri uri) {
        return null;
    }


    @Override
    public Uri insert(Uri uri, ContentValues values) {
        int match = sUriMatcher.match(uri);
        switch (match) {
            case ORDER:
                return insertCart(uri, values);

            default:
                throw new IllegalArgumentException("Cant insert data");
        }

    }

    private Uri insertCart(Uri uri, ContentValues values) {

        String name = values.getAsString(OrderContract.OrderEntry.COLUMN_NAME);
        if(name == null){
            throw new IllegalArgumentException("Name is Required");
        }

        String quantity = values.getAsString(OrderContract.OrderEntry.COLUMN_QUANTITY);
        if(quantity == null){
            throw new IllegalArgumentException("Quantity is Required");
        }

        String price = values.getAsString(OrderContract.OrderEntry.COLUMN_PRICE);
        if(price == null){
            throw new IllegalArgumentException("Price is Required");
        }

        //insert values into order

        SQLiteDatabase database = mhelper.getWritableDatabase();
        long id = database.insert(OrderContract.OrderEntry.TABLE_NAME, null, values);

        if(id == 0){
            return null;
        }
        getContext().getContentResolver().notifyChange(uri,null);
        return ContentUris.withAppendedId(uri,id);


    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        //delete data once order is made

        int rowsDeleted;
        SQLiteDatabase database = mhelper.getWritableDatabase();
        int match = sUriMatcher.match(uri);
        switch (match) {
            case ORDER:
                rowsDeleted = database.delete(OrderContract.OrderEntry.TABLE_NAME, selection, selectionArgs);
                break;

            default:
                throw new IllegalArgumentException("Cannot delete");
        }

        if (rowsDeleted!=0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }

        return rowsDeleted;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return 0;
    }
}

OrderContract 类:

public class OrderContract {

    public OrderContract() {
    }

    //content authority requires package name
    public static final String CONTENT_AUTHORITY = "com.example.myapp";
    public static final Uri BASE_URI = Uri.parse(("content://" +CONTENT_AUTHORITY));
    //same as table name
    public static final String PATH = "orders" ;


    public static abstract class OrderEntry implements BaseColumns{

        public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_URI,PATH);

        public static final String TABLE_NAME = "orders" ;
        public static final String _ID = BaseColumns._ID ;
        public static final String COLUMN_NAME = "name" ;
        public static final String COLUMN_QUANTITY = "quantity" ;
        public static final String COLUMN_PRICE = "price" ;

    }

}

购物车活动:

 sofaname=findViewById(R.id.sofaname);
        sofaprice=findViewById(R.id.sofaprice);
        sofadesc=findViewById(R.id.sofadesc);
        plusquantity = findViewById(R.id.addquantity);
        minusquantity  = findViewById(R.id.subquantity);
        quantitynumber = findViewById(R.id.quantity);
        addtocart = findViewById(R.id.addtocart);


        ImageSlider imageSlider = findViewById(R.id.sofaslider1);
        List<SlideModel> slideModels = new ArrayList<>();
        slideModels.add(new SlideModel(R.drawable.card14));
        slideModels.add(new SlideModel(R.drawable.card6));
        slideModels.add(new SlideModel(R.drawable.card7));
        imageSlider.setImageList(slideModels,false);

        imageSlider.setClickable(false);

        DB = new DBHelper(Sofa1.this);
        String Name = DB.getProductNamePrice("SELECT F_Name FROM Furniture WHERE F_Type = 'Sofa';");
        String Price = DB.getProductNamePrice("SELECT F_Price FROM Furniture WHERE F_Type = 'Sofa';");
        String Desc = DB.getProductNamePrice("SELECT F_Description FROM Furniture WHERE F_Type = 'Sofa';");
        sofaname.setText(Name);
        sofaprice.setText(Price);
        sofadesc.setText(Desc);

        plusquantity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(quantity<5){
                    //sofaprice
                    int baseprice= Integer.parseInt(sofaprice.getText().toString());
                    quantity++;
                    displayquantity();
                    totalprice = baseprice * quantity;
                    String setnewprice = (String.valueOf(totalprice));
                    sofaprice.setText(setnewprice);
                }
            }
        });

        minusquantity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int baseprice=0;
                String Price = DB.getProductNamePrice("SELECT F_Price FROM Furniture WHERE F_Type = 'Sofa';");
                baseprice = Integer.parseInt(Price);
                    if(quantity>1) {
                        quantity--;
                        displayquantity();
                        totalprice = baseprice * quantity;
                        String setnewprice = (String.valueOf(totalprice));
                        sofaprice.setText(setnewprice);
                    }


            }
        });

        addtocart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(Sofa1.this,Cart.class);
                startActivity(intent);

                // once this button is clicked we want to save our values in the database and send those values
                // right away to summary activity where we display the order info

                SaveCart();

                totalamount = (TextView) findViewById(R.id.total);
                int totalAmount = DB.getTotalExpenses();
                totalamount.setText(String.valueOf(totalAmount));

            }
        });





    }

    private boolean SaveCart() {

        String name = sofaname.getText().toString();
        String price = sofaprice.getText().toString();
        String quantity = quantitynumber.getText().toString();

        ContentValues values = new ContentValues();
        values.put(OrderContract.OrderEntry.COLUMN_NAME,name);
        values.put(OrderContract.OrderEntry.COLUMN_PRICE,price);
        values.put(OrderContract.OrderEntry.COLUMN_QUANTITY,quantity);

        if(mcurrentcarturi == null){
            Uri newUri = getContentResolver().insert(OrderContract.OrderEntry.CONTENT_URI, values);

            if(newUri == null){
                Toast.makeText(this, "Failed to add to cart", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(this, "Product added to cart", Toast.LENGTH_SHORT).show();
            }

        }

        hasallrequiredvalues = true;
        return hasallrequiredvalues;

    }

    private void displayquantity() {
        quantitynumber.setText(String.valueOf(quantity));
    }



    @Override
    public @NotNull Loader<Cursor> onCreateLoader(int id, Bundle args) {

        String[] projection = {OrderContract.OrderEntry._ID,
                OrderContract.OrderEntry.COLUMN_NAME,
                OrderContract.OrderEntry.COLUMN_PRICE,
                OrderContract.OrderEntry.COLUMN_QUANTITY};

        return new CursorLoader(this, mcurrentcarturi, projection, null, null, null);
    }

    @Override
    public void onLoadFinished(@NotNull Loader<Cursor> loader, Cursor cursor) {

        if(cursor==null || cursor.getCount() < 1){
            return;
        }

        if(cursor.moveToFirst()){

            int name = cursor.getColumnIndex(OrderContract.OrderEntry.COLUMN_NAME);
            int price = cursor.getColumnIndex(OrderContract.OrderEntry.COLUMN_PRICE);
            int quantity = cursor.getColumnIndex(OrderContract.OrderEntry.COLUMN_QUANTITY);

            String nameofsofa = cursor.getString(name);
            String priceofsofa = cursor.getString(price);
            String quantityofsofa = cursor.getString(quantity);

            sofaname.setText(nameofsofa);
            sofaprice.setText(priceofsofa);
            quantitynumber.setText(quantityofsofa);

        }

    }

    @Override
    public void onLoaderReset(@NotNull Loader<Cursor> loader) {

        sofaname.setText("");
        sofaprice.setText("");
        quantitynumber.setText("");

    }

1 个答案:

答案 0 :(得分:0)

因为您的查询有效

SELECT SUM(price) FROM  orders;

只会返回一列,因此使用 total = cursor.getInt(4); 应该会导致异常,因为该列越界,只有 1 列并且它的索引将为 0。

因此尝试更改为使用 :-

public int getTotalExpenses()
{
    int total = 0;
    SQLiteDatabase database = this.getReadableDatabase();
    Cursor cursor = database.rawQuery("SELECT SUM("+ OrderContract.OrderEntry.COLUMN_PRICE + ") FROM " + OrderContract.OrderEntry.TABLE_NAME, null);
    if (cursor.moveToFirst())
    {
        total = cursor.getInt(0); //<<<<<<<<<< CHANGED
    }
    //while (cursor.moveToNext()); //<<<<<<<<<< COMMENTED OUT NOT NEEDED
    cursor.close(); //<<<<<<<<<< ADDED should always close cursor when finished with them
    return total;
}