【问题标题】:Multiplying two columns in SQLite and display it in Android studio textview将SQLite中的两列相乘并在Android studio textview中显示
【发布时间】:2017-09-13 18:29:41
【问题描述】:

我一直在通过学习在线模板和教程来学习如何在 Android Studio 中使用 SQL,但没有一个教程显示如何将两列相乘并将计算的数据添加到新列中。

任务是将成本和数量相乘得到总数。 目前,我已经掌握了一些基础知识,例如在 SQLite 中添加、更新和删除数据。

这是我更新的当前 DBHelper.java

    package ntws.itemsqlite;

/**
 * Created by eddie on 13/4/2017.
 */

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

import java.util.ArrayList;
import java.util.HashMap;

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "ProductList.db";
    public static final String PRODUCTS_TABLE_NAME = "product";
    public static final String PRODUCTS_COLUMN_ID = "id";
    public static final String PRODUCTS_COLUMN_NAME = "name";
    public static final String PRODUCTS_COLUMN_COST = "cost";
    public static final String PRODUCTS_COLUMN_QUANTITY = "quantity";
    public static final String PRODUCTS_COLUMN_TOTAL = "total";

    private HashMap hp;

    public DBHelper(Context context) {
        super(context, DATABASE_NAME , null, 1);
    }



    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(
                "create table products " +
                        "(id integer primary key, name text,cost double, quantity double, total double)"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS products");
        onCreate(db);
    }
public int getAllTotal(int cost){
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery("SELECT SUM(cost) FROM products", null);
    if(res.moveToFirst())
    {
        return res.getInt(0);
    }

    return cost;
}

    public boolean insertProduct (String name,  String cost, String quantity) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);

        contentValues.put("cost", cost);
        contentValues.put("quantity", quantity);

        db.insert("products", null, contentValues);
        return true;
    }

    public Cursor getData(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from products where id="+id+" ", null );

        return res;
    }

    public int numberOfRows(){
        SQLiteDatabase db = this.getReadableDatabase();
        int numRows = (int) DatabaseUtils.queryNumEntries(db, PRODUCTS_TABLE_NAME);
        return numRows;
    }

    public boolean updateProduct (Integer id, String name,  String cost, String quantity) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);

        contentValues.put("cost", cost);
        contentValues.put("quantity", quantity);



        db.update("products", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
        return true;
    }

    public Integer deleteProduct (Integer id) {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("products",
                "id = ? ",
                new String[] { Integer.toString(id) });
    }

    public ArrayList<String> getAllProduct() {
        ArrayList<String> array_list = new ArrayList<String>();

        //hp = new HashMap();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from products", null );
        res.moveToFirst();

        while(res.isAfterLast() == false){
            array_list.add(res.getString(res.getColumnIndex(PRODUCTS_COLUMN_NAME)));
            res.moveToNext();
        }
        return array_list;
    }

    public double getItemTotal(int value)
    {
        String countQuery = "SELECT  * FROM product";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery(countQuery , null );

        double itemtotal = 0;
        if(res.moveToFirst()){
            String costStr = res.getString(res.getColumnIndex("cost"));
            String qntStr = res.getString(res.getColumnIndex("quantity"));

            itemtotal = Double.parseDouble(costStr) * Double.parseDouble(qntStr);
            res.close();
        }
        return itemtotal;
    }

    //end of DBHelper

}

如您所见,我已尝试在 DBHelper.java 中添加方法调用 getItemTotal。 目前,所有其他功能都在工作,我可以通过 DisplayProduct.java 将相应的数据替换为 activity_display_product.xml 中的 TextViews

现在是在 DisplayProduct.Java 中实现 getItemTotal() 的问题,以便方法函数可以运行计算然后分别更新。

DisplayProduct.Java

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_product);
    name = (TextView) findViewById(R.id.editTextName);

    cost = (TextView) findViewById(R.id.editTextCost);
    quantity = (TextView) findViewById(R.id.editTextQuantity);



    mydb = new DBHelper(this);



    Bundle extras = getIntent().getExtras();
    if(extras !=null) {
        int Value = extras.getInt("id");

        if(Value>0){
            //means this is the view part not the add PRODUCT part.
            Cursor rs = mydb.getData(Value);
            id_To_Update = Value;
            rs.moveToFirst();

            String nam = 
rs.getString(rs.getColumnIndex(DBHelper.PRODUCTS_COLUMN_NAME));

            String cos = 
rs.getString(rs.getColumnIndex(DBHelper.PRODUCTS_COLUMN_COST));
            String quantit = 
rs.getString(rs.getColumnIndex(DBHelper.PRODUCTS_COLUMN_QUANTITY));


            if (!rs.isClosed())  {
                rs.close();
            }
            Button b = (Button)findViewById(R.id.button1);
            b.setVisibility(View.INVISIBLE);

            name.setText((CharSequence)nam);
            name.setFocusable(false);
            name.setClickable(false);


            cost.setText((CharSequence)cos);
            cost.setFocusable(false);
            cost.setClickable(false);

            quantity.setText((CharSequence)quantit);
            quantity.setFocusable(false);
            quantity.setClickable(false);


        }
    }

总值应该替换activity_display_product.xml中的T​​extView

更新

我知道我应该将 DBHelper 中的 getItemTotal 方法添加到 DisplayProduct.java 的 onCreate 中,但我不知道如何实现。 所有示例都显示数组或列表视图。

有没有更好的方法让textview“editTextTotal”获取itemTotal?

如果有帮助, activity_display_product.xml 的 .xml 文件如下所示。 除editTextTotal 之外的所有内容均已正确分配。

activity_display_product.xml

<EditText
            android:id="@+id/editTextTotal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/editTextQuantity"
            android:layout_marginTop="22dp"
            android:layout_toEndOf="@+id/textView7"
            android:ems="10"
            android:inputType="text|number" />

【问题讨论】:

  • 为什么在插入查询中不插入总值?
  • 不会在 InsertProduct() 中插入总值,允许用户添加总值。应用程序需要计算总值。我最初也尝试过,但它导致应用程序崩溃
  • 实际上的问题是您在 insert() 方法中插入字符串值,而不是在创建表中作为列类型的双精度值。在创建、插入、选择、更新等所有查询中使用相同类型是件好事。希望这会对你有所帮助。

标签: android sqlite android-sqlite android-database


【解决方案1】:

问题出在

cost text, quantity text, total text

你已经添加为文本,首先解析成这个字符串加倍然后计算你的 渴望计算。

【讨论】:

  • getItemTotal() 方法不是将文本包装成双精度吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 2020-06-09
  • 1970-01-01
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多