簡體   English   中英

如何在listView中初始化商品的總計數和某個價格的總價值?

[英]How to initialize in listView total count of items and total value of some price?

我的應用程式

這是我的應用程序,這是我的MainActivity。 就像我在問題中說的那樣,我將如何獲得商品的總價格和某些價格的總價值。

這是MainActivity.java的代碼:

public class MainActivity extends BaseActivity {

    // Declare variables
    private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;

    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;

    private GroceryDbAdapter mDbHelper;

    Button addItem;
    private Toolbar toolbar;
    private ListView listView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FrameLayout frameLayout = (FrameLayout)findViewById(R.id.frame_container);

         // inflate the custom activity layout
        LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View activityView = layoutInflater.inflate(R.layout.activity_main, null,false);

        frameLayout.addView(activityView);

        // Setting toolbar
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setLogo(R.drawable.shopping_cart_logo);

        // Setting database and adapter
        mDbHelper = new GroceryDbAdapter(this);
        mDbHelper.open();

        // Locate ListView
        listView = (ListView) findViewById(R.id.list);

        // Locate button and initialization
        addItem = (Button) findViewById(R.id.add_item);
        addItem.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in, R.anim.slide_out);

            }
        });

        fillData();
    }

    @SuppressWarnings("deprecation")
    private void fillData() {
        Cursor itemsCursor =  mDbHelper.fetchAllItems();
        startManagingCursor(itemsCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{GroceryDbAdapter.KEY_TITLE, GroceryDbAdapter.KEY_PRICE};

        // and an array of the fields we want to bind those fields to (in this case just title)
        int[] to = new int[]{R.id.title, R.id.price};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter items = 
            new SimpleCursorAdapter(this, R.layout.list_item_row, itemsCursor, from, to);
        listView.setAdapter(items);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID, 0, "Add Item");
        return true;
    }

    public boolean onOptionsItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case INSERT_ID:
                createItem();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, "Delete Item");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case DELETE_ID:
                AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
                mDbHelper.deleteItem(info.id);
                fillData();
                return true;
        }
        return super.onContextItemSelected(item);
    }

    private void createItem() {
        Intent i = new Intent(this, AddActivity.class);
        startActivityForResult(i, ACTIVITY_CREATE);
    }

    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, AddActivity.class);
        i.putExtra(GroceryDbAdapter.KEY_ROWID, id);
        startActivityForResult(i, ACTIVITY_EDIT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        fillData();
    }
}

從MainActivity的布局中:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainContent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <include
        android:id="@+id/app_bar"
        layout="@layout/app_bar" />

    <Button
        android:id="@+id/add_item"
        style="@style/MyCustomButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="@string/add_button" />

    <ListView
        android:id="@+id/list"
        android:choiceMode="multipleChoice"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/add_item"
        android:layout_below="@+id/relativeLayout"
        android:layout_centerHorizontal="true"
        android:layout_margin="@dimen/margin"
        android:divider="@color/list_divider_row"
        android:dividerHeight="@dimen/divider_height"
        android:listSelector="@drawable/list_row_selector" >

    </ListView>

    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/listView1"
        android:layout_alignStart="@+id/listView1"
        android:layout_alignRight="@+id/listView1"
        android:layout_alignEnd="@+id/listView1"
        android:layout_below="@+id/app_bar"
        android:padding="@dimen/relative_layout_padding" >

        <TextView
            android:id="@+id/item_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="4dp"
            android:text="Items"
            android:textColor="#474747"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/item_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="4dp"
            android:layout_toRightOf="@+id/item_text"
            android:text="(2)"
            android:textColor="#474747"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/total_amount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:text="Rs. 5700"
            android:textColor="#000000"
            android:textSize="20dp" />

    </RelativeLayout>

</RelativeLayout>

這是我的課程項目:

    public class Item {

    //private variables
    int _id;
    String title;
    String price;

    // Empty constructor
    public Item(){

    }
    // constructor
    public Item(int id, String title, String price){
        this._id = id;
        this.title = title;
        this.price = price;
    }

    // constructor
    public Item(String title, String price){
        this.title = title;
        this.price = price;
    }
    // getting ID
    public int getID(){
        return this._id;
    }

    // setting id
    public void setID(int id){
        this._id = id;
    }

    // getting name
    public String getTitle(){
        return this.title;
    }

    // setting name
    public void setTitle(String title){
        this.title = title;
    }

    // getting phone number
    public String getPrice(){
        return this.price;
    }

    // setting phone number
    public void setPrice(String price){
        this.price = price;
    }
}

和數據庫代碼:

    public class GroceryDbAdapter {

    public static final String KEY_TITLE = "title";
    public static final String KEY_PRICE = "price";
    public static final String KEY_ROWID = "_id";

    private static final String TAG = "GroceryDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    private Context mCtx;

    /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
        "create table grocery (_id integer primary key autoincrement, "
        + "title text not null, price text not null);";

    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "grocery";
    private static final int DATABASE_VERSION = 2;

    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 grocery");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public GroceryDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the notes database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public GroceryDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }


    /**
     * Create a new note using the title and body provided. If the note is
     * successfully created return the new rowId for that note, otherwise return
     * a -1 to indicate failure.
     * 
     * @param title the title of the note
     * @param body the body of the note
     * @return rowId or -1 if failed
     */
    public long createItem(String title, String price) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_PRICE, price);

        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

    /**
     * Delete the note with the given rowId
     * 
     * @param rowId id of note to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteItem(long rowId) {

        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list of all notes in the database
     * 
     * @return Cursor over all notes
     */
    public Cursor fetchAllItems() {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
                KEY_PRICE}, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the note that matches the given rowId
     * 
     * @param rowId id of note to retrieve
     * @return Cursor positioned to matching note, if found
     * @throws SQLException if note could not be found/retrieved
     */
    public Cursor fetchItem(long rowId) throws SQLException {

        Cursor mCursor =

            mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                    KEY_TITLE, KEY_PRICE}, KEY_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    /**
     * Update the note using the details provided. The note to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param rowId id of note to update
     * @param title value to set note title to
     * @param body value to set note body to
     * @return true if the note was successfully updated, false otherwise
     */
    public boolean updateItem(long rowId, String title, String price) {
        ContentValues args = new ContentValues();
        args.put(KEY_TITLE, title);
        args.put(KEY_PRICE, price);

        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}

將TextView初始化為itemCountTextView,並將適配器設置為listView之后,將from數組的長度(表示項目數)添加為該TextView的文本。

聲明TextView itemcountTextView; 作為類變量。

onCreate() ,寫入: itemcountTextView = (TextView) findViewById(R.id.item_count);

然后在fillData()方法中:

 private void fillData() {
        Cursor itemsCursor =  mDbHelper.fetchAllItems();
        startManagingCursor(itemsCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{GroceryDbAdapter.KEY_TITLE, GroceryDbAdapter.KEY_PRICE};

        // and an array of the fields we want to bind those fields to (in this case just title)
        int[] to = new int[]{R.id.title, R.id.price};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter items = 
            new SimpleCursorAdapter(this, R.layout.list_item_row, itemsCursor, from, to);
        listView.setAdapter(items);
        itemCountTextView.setText(String.ValueOf(listView.getCount()));
    }

對另一個TextView做類似的事情。

在您的filldata()方法中嘗試這樣做;

itemCountTextView.setText(String.ValueOf(listview.getCount())); 

應該返回您的計數,您的列表視圖中有多少個項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM