在android中使用rawQuery的总价格

时间:2015-02-11 04:01:14

标签: java android

我一直试图从数据库中获取价格值并尝试获得总计。我使用了rawQuery,但总是崩溃。我认为我的rawQuery中有一个问题..我仍然无法在多次尝试之后获得总数...

这是代码:

将对DBAdapter

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


// ------------------------------------ DBAdapter.java ---------------------------------------------
// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
public class DBAdapter {

    /////////////////////////////////////////////////////////////////////
    //  Constants & Data
    /////////////////////////////////////////////////////////////////////
    // For logging:
    private static final String TAG = "DBAdapter";

    // DB Fields
    public static final String KEY_ROWID = "_id";
    public static final int COL_ROWID = 0;
    /*
     * CHANGE 1:
     */
    // TODO: Setup your fields here:
    public static final String KEY_NAME = "name";
    public static final String KEY_QUANTITY = "studentnum";
    public static final String KEY_PRICE = "favcolour";

    // TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
    public static final int COL_NAME = 1;
    public static final int COL_QUANTITY = 2;
    public static final int COL_PRICE = 3;


    public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_PRICE};

    // DB info: it's name, and the table we are using (just one).
    public static final String DATABASE_NAME = "MyDb";
    public static final String DATABASE_TABLE = "mainTable";
    // Track DB version if a new version of your app changes the format.
    public static final int DATABASE_VERSION = 2;

    private static final String DATABASE_CREATE_SQL =
            "create table " + DATABASE_TABLE
                    + " (" + KEY_ROWID + " integer primary key autoincrement, "

            /*
             * CHANGE 2:
             */
                    // TODO: Place your fields here!
                    // + KEY_{...} + " {type} not null"
                    //  - Key is the column name you created above.
                    //  - {type} is one of: text, integer, real, blob
                    //      (http://www.sqlite.org/datatype3.html)
                    //  - "not null" means it is a required field (must be given a value).
                    // NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
                    + KEY_NAME + " text not null, "
                    + KEY_QUANTITY + " integer not null, "
                    + KEY_PRICE + " string not null"

                    // Rest  of creation:
                    + ");";

    // Context of application who uses us.
    private final Context context;

    private DatabaseHelper myDBHelper;
    private SQLiteDatabase db;

    /////////////////////////////////////////////////////////////////////
    //  Public methods:
    /////////////////////////////////////////////////////////////////////

    public DBAdapter(Context ctx) {
        this.context = ctx;
        myDBHelper = new DatabaseHelper(context);
    }

    // Open the database connection.
    public DBAdapter open() {
        db = myDBHelper.getWritableDatabase();
        return this;
    }

    // Close the database connection.
    public void close() {
        myDBHelper.close();
    }

    // Add a new set of values to the database.
    public long insertRow(String name, String studentNum, String favColour) {
        /*
         * CHANGE 3:
         */
        // TODO: Update data in the row with new fields.
        // TODO: Also change the function's arguments to be what you need!
        // Create row's data:
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_QUANTITY, studentNum);
        initialValues.put(KEY_PRICE, favColour);

        // Insert it into the database.
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    // Delete a row from the database, by rowId (primary key)
    public boolean deleteRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        return db.delete(DATABASE_TABLE, where, null) != 0;
    }

    public Cursor getTotalPrice() {
        Cursor c = db.rawQuery("SELECT SUM("+ KEY_PRICE +")from " + DATABASE_TABLE, null);
        return c;
        }


    public void deleteAll() {
        Cursor c = getAllRows();
        long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
        if (c.moveToFirst()) {
            do {
                deleteRow(c.getLong((int) rowId));
            } while (c.moveToNext());
        }
        c.close();
    }

    // Return all data in the database.
    public Cursor getAllRows() {
        String where = null;
        Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS,
                where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Get a specific row (by rowId)
    public Cursor getRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS,
                where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Change an existing row to be equal to new data.
    public boolean updateRow(long rowId, String name, int studentNum, String favColour) {
        String where = KEY_ROWID + "=" + rowId;

        /*
         * CHANGE 4:
         */
        // TODO: Update data in the row with new fields.
        // TODO: Also change the function's arguments to be what you need!
        // Create row's data:
        ContentValues newValues = new ContentValues();
        newValues.put(KEY_NAME, name);
        newValues.put(KEY_QUANTITY, studentNum);
        newValues.put(KEY_PRICE, favColour);

        // Insert it into the database.
        return db.update(DATABASE_TABLE, newValues, where, null) != 0;
    }




    /////////////////////////////////////////////////////////////////////
    //  Private Helper Classes:
    /////////////////////////////////////////////////////////////////////

    /**
     * Private class which handles database creation and upgrading.
     * Used to handle low-level database access.
     */
    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DATABASE_CREATE_SQL);
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading application's database from version " + oldVersion
                    + " to " + newVersion + ", which will destroy all old data!");

            // Destroy old database:
            _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

            // Recreate new database:
            onCreate(_db);
        }
    }
}

Listprice:

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;


/**
 * Created by User on 6/2/2015.
 */

public class Listprice extends ActionBarActivity {

    DBAdapter myDb;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listprice);

        openDB();
        TextView textView = (TextView) findViewById(R.id.order90);
        TextView textView1 = (TextView) findViewById(R.id.quan90);
        TextView textView2 = (TextView) findViewById(R.id.price90);
        TextView textView3 = (TextView) findViewById(R.id.totalprice);

        Bundle extras = getIntent().getExtras();


        if (extras != null) {
            String newText = extras.getString("firstmessage");
            String newText1 = extras.getString("secondmessage");
            String newText2 = extras.getString("thirdmessage");

            if (newText != null) {
                textView.setText(newText);
            }
            if (newText1 != null) {
                textView1.setText(newText1);
            }
            if (newText2 != null) {
                textView2.setText(newText2);
            }
        }
        String num1 = textView.getText().toString().trim();
        int num2 = Integer.parseInt(textView1.getText().toString());
        int num3 = Integer.parseInt(textView2.getText().toString());

        int num4 = num2 * num3;

        registerListClickCallBack();
        myDb.insertRow(num1, "Quantity = " + num2, ""+num4);
        populateListViewFromDB();

        Cursor sum=myDb.getTotalPrice();
        textView3.setText(""+sum);

    }


    private void populateListViewFromDB() {


        Cursor cursor = myDb.getAllRows();
        //Query for the record we just added.
        //Use the ID:
        startManagingCursor(cursor);

        String[] fromFieldNames = new String[]
                {DBAdapter.KEY_NAME, DBAdapter.KEY_QUANTITY, DBAdapter.KEY_PRICE};

        int[] toViewIDs = new int[]
                {R.id.item_name, R.id.quantities, R.id.pricest};

        SimpleCursorAdapter myCursorAdapter =
                new SimpleCursorAdapter(
                        this,
                        R.layout.item_layout,
                        cursor,
                        fromFieldNames,
                        toViewIDs
                );

        // Set the adapter for the list view
        ListView myList = (ListView) findViewById(R.id.listViewFromDB);
        myList.setAdapter(myCursorAdapter);

    }

    private void openDB(){

        myDb = new DBAdapter(this);
        myDb.open();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDB();
    }



    private void closeDB() {
        myDb.close();
    }


    private void registerListClickCallBack() {

        ListView myList = (ListView) findViewById(R.id.listViewFromDB);
        myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View viewClicked,
                                    int position, long idInDB) {

                updateItemForId(idInDB);

            }
        });
    }


    private void updateItemForId(final long idInDB) {

        final Cursor cursor = myDb.getRow(idInDB);
        if (cursor.moveToFirst()) {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(Listprice.this);

            // Setting Dialog Title
            alertDialog.setTitle("Confirm Delete...");

            // Setting Dialog Message
            alertDialog.setMessage("Are you sure you want delete this?");


            // Setting Positive "Yes" Button
            alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int which) {

                    // Write your code here to invoke YES event
                    Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
                    myDb.deleteRow(idInDB);
                    populateListViewFromDB();
                }
            });

            // Setting Negative "NO" Button
            alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // Write your code here to invoke NO event
                    Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                    dialog.cancel();
                }
            });

            // Showing Alert Message
            alertDialog.show();
        }
        cursor.close();
        populateListViewFromDB();
    }

    public void clear(View view) {
        myDb.deleteAll();
        populateListViewFromDB();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    public void addFood(View view) {
        Intent gotofood = new Intent(this, food.class);
        startActivity(gotofood);
    }

    public void addDrinks(View view) {
        Intent gotodrinks = new Intent(this, drink.class);
        startActivity(gotodrinks);
    }

    public void gotomainmaenu(View view) {
        Intent gotomain = new Intent(this, MainActivity.class);
        startActivity(gotomain);
    }


}

1 个答案:

答案 0 :(得分:0)

听起来您希望每件商品的价格总和乘以该商品的数量。如果是这样,这应该有效:

public double getTotalPrice() {
    String sql = "select sum(" + KEY_QUANTITY + " * " + KEY_PRICE + ") from "
             + DATABASE_TABLE;
    Cursor cursor = db.rawQuery(sql, null);
    if (cursor.moveToFirst()) {
        return cursor.getDouble(0);
    }
    return 0;
}