在Android Studios中,单击产品列表项时,显示该产品的相应价格

时间:2015-09-22 21:17:05

标签: java android sqlite

我一直在寻找我的问题的答案。在这里......我有产品要在列表中显示,其中一些产品可能有多个单位和价格。我定义了模型类,我的DBAdapter创建了我的表,我从XML表中拉取数据,这看起来很棒。

我遇到的问题是如何从SQLite数据库中的多个表中检索和显示数据。我以为我可以将这些数据分别检索到两个不同的列表并组合列表,但我需要保持我的product_id和price_id链接,以便我得到该产品的正确单位和价格。任何帮助都将受到赞赏和帮助。

创建表格的我的DBAdapter

public class DBAdapter extends SQLiteOpenHelper {

    private static final String LOGTAG = "FarrellDB";

    //DATABASE NAME AND VERSION
    private static final String DATABASE_NAME = "farrell.db";
    private static final int DATABASE_VERSION = 3;

    // Product Table Field Names
    public static final String TABLE_PRODUCTS = "products";
    public static final String PRODUCT_ID = "product_id";
    public static final String PRODUCT_SKU = "sku";
    public static final String PRODUCT_DESC = "desc";

    // Price Table Field Names
    public static final String TABLE_PRICES = "prices";
    public static final String PRICE_ID = "id";
    public static final String PRICE_ID_ID = "price_id";
    public static final String PRICE_UNITS = "units";
    public static final String PRICE_PRICE = "amount";

    //SQL_CREATE_TABLE_PRODUCTS
    public static final String SQL_CREATE_TABLE_PRODUCTS =
        "CREATE TABLE " + TABLE_PRODUCTS + " (" + PRODUCT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + PRODUCT_SKU + " TEXT, " + PRODUCT_DESC + " TEXT " +
        ")";

    //SQL_CREATE_TABLE_PRICES
    public static final String SQL_CREATE_TABLE_PRICES =
        "CREATE TABLE " + TABLE_PRICES + " (" + PRICE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + PRICE_ID_ID + " INTEGER, " + PRICE_UNITS + " INTEGER, " + PRICE_PRICE + " NUMERIC " +
        ")";


    public DBAdapter(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_TABLE_PRODUCTS);
        db.execSQL(SQL_CREATE_TABLE_PRICES);

        Log.i(LOGTAG, "Tables have been created");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRICES);
        onCreate(db);

        Log.i(LOGTAG, "Database has been upgraded from " + oldVersion + " to " + newVersion);
    }
}

public class ProductViewActivity extends AppCompatActivity {

    private static final String LOGTAG = "FarrellDB";

    DataSource dataSource;

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

        dataSource = new DataSource(this);
        dataSource.open();

        List < Product > products = dataSource.findAllProducts();
        if (products.size() == 0) {
            insertProductData();
            insertPriceData();
            products = dataSource.findAllProducts();
        }

        ArrayAdapter < Product > adapter = new ArrayAdapter < Product > (this,
        android.R.layout.simple_list_item_1, products);
        ListView product_list_view = (ListView) findViewById(R.id.product_list_view);
        product_list_view.setAdapter(adapter);


        // WHEN THE USER CLICKS ON A ITEM IN THE LIST GOES TO THE NEW ACTIVITY
        product_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Override
            public void onItemClick(AdapterView <? > parent, View view, int position, long id) {

                Intent intent = new Intent(ProductViewActivity.this, PriceListViewActivity.class);

                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_product_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        dataSource.open();
    }

    @Override
    protected void onPause() {
        super.onPause();
        dataSource.close();
    }

    public void insertProductData() {
        ProductPullParser parser = new ProductPullParser();
        List < Product > products = parser.parseXML(this);

        for (Product product: products) {
            dataSource.createProduct(product);
        }
    }

    public void insertPriceData() {
        PricePullParser parser = new PricePullParser();
        List < Price > prices = parser.parseXML(this);

        for (Price price: prices) {
            dataSource.createPrice(price);
        }
    }
}

public class DataSource {

    public static final String LOGTAG = "FarrellDB";

    SQLiteOpenHelper dbHelper;
    SQLiteDatabase database;

    public DataSource(Context context) {
        dbHelper = new DBAdapter(context);
    }

    public void open() {
        Log.i(LOGTAG, "Database Opened");
        database = dbHelper.getWritableDatabase();
    }

    public void close() {
        Log.i(LOGTAG, "Database Closed");
        dbHelper.close();
    }

    public Product createProduct(Product product) {
        ContentValues productValues = new ContentValues();
        productValues.put(DBAdapter.PRODUCT_SKU, product.getSku());
        productValues.put(DBAdapter.PRODUCT_DESC, product.getDesc());
        long insertid = database.insert(DBAdapter.TABLE_PRODUCTS, null, productValues);
        product.setProduct_id(insertid);
        return product;
    }

    public Price createPrice(Price price) {
        ContentValues priceValues = new ContentValues();
        priceValues.put(DBAdapter.PRICE_ID_ID, price.getPrice_id());
        priceValues.put(DBAdapter.PRICE_UNITS, price.getUnits());
        priceValues.put(DBAdapter.PRICE_PRICE, price.getAmount());
        long insertid = database.insert(DBAdapter.TABLE_PRICES, null, priceValues);
        price.setId(insertid);
        return price;
    }

    public List < Product > findAllProducts() {
        List < Product > products = new ArrayList < Product > ();
        List < Price > prices = new ArrayList < Price > ();
        List final_list = new ArrayList();

        final_list.addAll(products);
        final_list.addAll(prices);

        Log.i(LOGTAG, "final_list contains " + final_list);

        String productQuery = "SELECT products.sku, products.desc, prices.units, prices.amount " +
            "FROM products, prices " +
            "WHERE products.product_id = prices.price_id";

        Cursor cursor = database.rawQuery(productQuery, null);

        Log.i(LOGTAG, "Returned products " + cursor.getCount() + " rows");

        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                Product product = new Product();
                product.setProduct_id(cursor.getLong(cursor.getColumnIndex(DBAdapter.PRODUCT_ID)));
                product.setSku(cursor.getString(cursor.getColumnIndex(DBAdapter.PRODUCT_SKU)));
                product.setDesc(cursor.getString(cursor.getColumnIndex(DBAdapter.PRODUCT_DESC)));
                products.add(product);
            }
        }
        return products;
    }

    public List < Price > findAllPrices() {
        List < Price > prices = new ArrayList < Price > ();

        String priceQuery = "SELECT products.sku, products.desc, prices.units, prices.amount " +
            "FROM products, prices " +
            "WHERE products.product_id = prices.price_id";

        Cursor cursor = database.rawQuery(priceQuery, null);

        Log.i(LOGTAG, "Returned products " + cursor.getCount() + " rows");

        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                Price price = new Price();
                price.setId(cursor.getLong(cursor.getColumnIndex(DBAdapter.PRICE_ID)));
                price.setPrice_id(cursor.getInt(cursor.getColumnIndex(DBAdapter.PRICE_ID_ID)));
                price.setUnits(cursor.getInt(cursor.getColumnIndex(DBAdapter.PRICE_UNITS)));
                price.setAmount(cursor.getDouble(cursor.getColumnIndex(DBAdapter.PRICE_PRICE)));
                prices.add(price);
            }
        }
        return prices;
    }

}

1 个答案:

答案 0 :(得分:-1)

实际上,您可以非常轻松地将两个不同的项目组合成一个非常容易的基本列表,例如名称和数字。当你超越它时,你需要一种自定义的方式。

例如,我在我自己的代码中使用这个类作为一种自定义的方式将很多东西拉到一个列表中(但是有不同的方法),这个对我有用:

private class CustomListAdapterH extends BaseAdapter implements ListAdapter {
    // Implement all required methods

    // private View createViewFromResource(final int position, View convertView, ViewGroup parent, int resource) {
           // EXAMPLE:
           // priceTextView.setText(price[position]);
    // }
}

您可以使用图像,OnClickListeners以及该列表中的所有内容。你还必须学习如何使列表平滑,因为在用户滚动时创建项目的方法内部尽可能不做,或者在不断重复代码时滚动不好。

如果你需要更多,你可以谷歌搜索它。它在那里。

你在这里复杂的东西如此放松因为它需要相当多的工作。