简体   繁体   English

从SQLite数据库填充TableLayout

[英]Populate TableLayout from SQLite-database

I want to display a simple list in a table view which I've created and included below but can't see how i capture the data which I'm getting back from my query to populate this. 我想在表格视图中显示一个简单的列表,该列表已创建并包含在下面,但是看不到如何捕获从查询中获取的数据来填充此数据。

I have a database adapter which i think is working: 我有一个我认为正在工作的数据库适配器:

public class DbAdapter {

    public static final String KEY_ROWID = "id";
    public static final String KEY_ITEM_NAME = "name";
    public static final String KEY_ITEM_COST = "cost";
    public static final String KEY_ITEM_PRICE_VALUE = "price";
    public static final String KEY_ITEM_POSTAGE = "postage";
    public static final String KEY_ACTUAL_PL = "profitloss";

    private static final String TAG = "DbAdapter";

    private static final String DATABASE_NAME = "eBaySalesDB";
    private static final String DATABASE_TABLE = "actualSales";
    private static final int DATABASE_VERSION = 1;

    private DatabaseHelper mDbHelper;
    private SQLiteDatabase db;

    //private static final String DATABASE_CREATE = "create table if not exists"
    //      + DATABASE_TABLE + "(" + KEY_ROWID
    //      + "integer primary key autoincrement, " + KEY_ITEM_NAME
    //      + "text not null," + KEY_ITEM_COST + "text not null,"
    //      + KEY_ITEM_PRICE_VALUE + "text not null," + KEY_ITEM_POSTAGE
    //      + "text not null," + KEY_ACTUAL_PL + "text not null);";

    private static final String DATABASE_CREATE = "create table if not exists "
            + DATABASE_TABLE + "(" + KEY_ROWID
            + " integer primary key autoincrement, " + KEY_ITEM_NAME
            + " text not null," + KEY_ITEM_COST + " text not null,"
            + KEY_ITEM_PRICE_VALUE + " text not null," + KEY_ITEM_POSTAGE
            + " text not null," + KEY_ACTUAL_PL + " text not null);";

    private final Context mCtx;

    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);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("Drop table if exists " + DATABASE_TABLE);
            onCreate(db);
        }

    }

    /**
     * constructor - takes the context to allow the database to be opened /
     * created
     * 
     * @param ctx
     */
    public DbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * open up the database. If it cannot be opened it will try to create a new
     * instance of the database. if this can't be created it will throw an
     * exception
     * 
     * @return this (self reference)
     * @throws SQLException
     *             (if the database can't be opened or closed.
     */
    public DbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        db = mDbHelper.getWritableDatabase();
        return this;
    }

    /**
     * Method to close the code off to others
     */
    public void close() {
        mDbHelper.close();
    }

    /**
     * method to insert a record into the database
     */
    public long insertRecord(String name, String cost, String price,
            String postage, String profitloss) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_ITEM_NAME, name);
        initialValues.put(KEY_ITEM_COST, cost);
        initialValues.put(KEY_ITEM_PRICE_VALUE, price);
        initialValues.put(KEY_ITEM_POSTAGE, postage);
        initialValues.put(KEY_ACTUAL_PL, profitloss);
        return db.insert(DATABASE_TABLE, null, initialValues);

    }

    /**
     * method to delete a record from the database
     */
    public boolean deleteRecord(long id) {
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + id, null) > 0;
    }

    /**
     * method to retrieve all the records
     */
    public Cursor getAllRecords() {
        return db.query(DATABASE_TABLE, new String[] { KEY_ROWID,
                KEY_ITEM_NAME, KEY_ITEM_COST, KEY_ITEM_PRICE_VALUE,
                KEY_ITEM_POSTAGE, KEY_ACTUAL_PL }, null, null, null, null,
                null, null);

    }

    /**
     * method to retrieve a particular record
     */
    public Cursor getRecord(long id) throws SQLException {
        Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
                KEY_ROWID, KEY_ITEM_NAME, KEY_ITEM_COST, KEY_ITEM_PRICE_VALUE,
                KEY_ITEM_POSTAGE, KEY_ACTUAL_PL }, KEY_ROWID + "=" + id, null,
                null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    /**
     * method to update a record
     */
    public boolean updateRecord(long id, String name, String cost,
            String price, String postage, String profitloss) {
        ContentValues args = new ContentValues();
        args.put(KEY_ITEM_NAME, name);
        args.put(KEY_ITEM_COST, cost);
        args.put(KEY_ITEM_PRICE_VALUE, price);
        args.put(KEY_ITEM_POSTAGE, postage);
        args.put(KEY_ACTUAL_PL, profitloss);
        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + id, null) > 0;
    }
}

I've also created an Activity to activate a button to view the data which a user can press. 我还创建了一个活动来激活按钮以查看用户可以按下的数据。 It's the third button, viewRecordsDB, which I'm having trouble getting to function.... 这是第三个按钮,viewRecordsDB,我无法正常使用...。

public class ActualSalesTracker extends Activity implements OnClickListener {

    DbAdapter db = new DbAdapter(this);
    Button BtnSalesCal, BtnAddRecordDB, BtnViewRecordsDB;
    EditText item_name, item_cost, item_price_value, item_postage, actual_pl;
    SalesProfitLossCal actSalesCal = new SalesProfitLossCal();

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

        Button salesCalBtn = (Button) findViewById(R.id.BtnSalesCal);
        // register the click event with the sales calculating profit/loss
        // button
        salesCalBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                // get EditText by id to represent the value of the item stock
                // cost and store it as a double
                EditText itemCostString = (EditText) findViewById(R.id.item_cost);
                String ic = itemCostString.getText().toString();
                double itemCost = Double.valueOf(ic).doubleValue();

                // get EditText by id to represent the value of the post and
                // packaging cost and store it as a double
                EditText itemPostageString = (EditText) findViewById(R.id.item_postage);
                String ipapc = itemPostageString.getText().toString();
                double itemPostage = Double.valueOf(ipapc).doubleValue();

                // get EditText by id to represent the value of the selling
                // price and store it as a double
                EditText itemPriceValueString = (EditText) findViewById(R.id.item_price_value);
                String sp = itemPriceValueString.getText().toString();
                double itemPriceValue = Double.valueOf(sp).doubleValue();

                double actTotalCost = actSalesCal.ActTotalCostCal(itemCost,
                        itemPostage, itemPriceValue);
                double actualProfitLoss = actSalesCal
                        .calculateProfitLossGenerated(itemPriceValue,
                                actTotalCost);

                String ActualProfitLossString = String.format(
                        "You made £ %.2f", actualProfitLoss);
                TextView ActualProfitLossView = (TextView) findViewById(R.id.yourActualPL);
                ActualProfitLossView.setText(ActualProfitLossString);
            }

        });

        // activate the add record button
        Button addRecordDB = (Button) findViewById(R.id.BtnAddRecordDB);
        // register the click event with the add record button
        addRecordDB.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                EditText nameText = (EditText) findViewById(R.id.item_name);
                String name = nameText.getText().toString();
                EditText costText = (EditText) findViewById(R.id.item_cost);
                String cost = costText.getText().toString();
                EditText priceText = (EditText) findViewById(R.id.item_price_value);
                String price = priceText.getText().toString();
                EditText postageText = (EditText) findViewById(R.id.item_postage);
                String postage = postageText.getText().toString();
                TextView profitlossText = (TextView) findViewById(R.id.actual_pl);
                String profitloss = profitlossText.getText().toString();

                db.open();
                long id = db.insertRecord(name, cost, price, postage,
                        profitloss);
                db.close();

            }

        });

        // activate the view record button
        Button viewRecordsDB = (Button) findViewById(R.id.BtnViewRecordsDB);
        // register the click event with the add record button
        viewRecordsDB.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                db.open();
                Cursor id = db.getAllRecords();
                db.close();

                // for (id.moveToFirst(); !id.moveToLast(); id.moveToNext()){
                // id.getString(
                // result = result +
                // }

            }

        });

    }

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

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }

}

I wanted it to populate the following view file on xml 我希望它在xml上填充以下视图文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TableLayout
        android:id="@+id/table_sales"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TableRow android:id="@+id/tableRow1" >

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="@string/item_name"
                android:layout_weight="1" >
            </TextView>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="@string/profit_loss"
                android:layout_weight="1" >
            </TextView>
        </TableRow>
    </TableLayout>

    <TextView
        android:id="@+id/sales_info"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="get info from database" >
    </TextView>

</LinearLayout>

and i have a java file set up to activate this : 我有一个Java文件设置来激活此:

public class ViewSales extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_sales);
    }

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

Use a ListView rather than a TableLayout . 使用ListView而不是TableLayout A TableLayout is usually used to display static, pre-defined content, while a ListView is much more dynamic and can directly handle the Cursor you get from the SQLite-db: Learn How to Create ListView From SQLite Database in Android Development TableLayout通常用于显示静态的预定义内容,而ListView更动态,可以直接处理从SQLite-db获取的Cursor了解如何在Android开发中从SQLite数据库创建ListView

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM