Reputation: 3219
So here is my application and this is my MainActivity. Like i said in my question, how would i get total cound of Items and total value of some prices.
Here's the code of 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();
}
}
and from layout of 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>
And this is my class Item:
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;
}
}
and code of DataBase:
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;
}
}
Upvotes: 0
Views: 1468
Reputation: 1737
Initialize the TextView as itemCountTextView, and after setting the adapter to the listView, add the length of from array, which signifies the number of item, as text to this TextView.
Declare TextView itemcountTextView;
as a class variable.
In onCreate()
, write : itemcountTextView = (TextView) findViewById(R.id.item_count);
Then in the fillData()
method :
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()));
}
Do something similar for the other TextView
.
Upvotes: 1
Reputation: 1761
Try to this in your filldata() methods;
itemCountTextView.setText(String.ValueOf(listview.getCount()));
It should be return your count how many items at your listview.
Upvotes: 1