I have a ListView which displays items in my shopping cart from my existing database and at the bottom i have created TextView of total price of all the items in my cart,but the total price that displays at the bottom does not get updated according to the products in my cart.I am not getting where am I making mistake,please help me out.
xml code for TextView of Total price:
<TextView
android:id="#+id/totalItemPrice"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="RS "
android:textSize="20dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="20dp"
android:textColor="#FFFFFF"/>
AddToCartFragment.java :
private ArrayList<GenieCart_List_Model> mAddList;
private void getCart_Data() {
try {
db = new DataBasehelper1(getActivity());
mAddList = new ArrayList<GenieCart_List_Model>();
mAddList = db.getAllCotacts();
long sum = db.sum_Of_Rs();
mTotalItemPrice.setText("Total Rs : " + sum);
db.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
DataBaseHelper1.java:
public long sum_Of_Rs() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(" select * from " +CONTACTS_TABLE_NAME + " ORDER BY " + CONTACTS_PRODUCT_ID + " DESC " , null);
ArrayList<GenieCart_List_Model> list = new ArrayList<GenieCart_List_Model>();
try {
res.moveToFirst();
for (int i = 0; i < res.getCount(); i++) {
GenieCart_List_Model Prod_Details = new GenieCart_List_Model();
Prod_Details.setPrice(res.getString(res.getColumnIndex(CONTACTS_PRODUCT_RS)));
Prod_Details.setProdID(res.getString(res.getColumnIndex(CONTACTS_PRODUCT_ID)));
try {
int total = Integer.parseInt(res.getString(res.getColumnIndex(CONTACTS_PRODUCT_RS)));
Sum = Sum + total;
return Sum;
} catch (Exception e) {
e.printStackTrace();
}
list.add(Prod_Details);
res.moveToNext();
}
}
catch (Exception e) {
e.printStackTrace();
}
return Sum;
}
I think this is a conversion issue.
Set Text like that
mTotalItemPrice.setText("Total Rs : " + String.valueOf(sum));
Remove the line " return sum; " from try catch .
Your method sum_Of_Rs() is right. To update the total cost call your method sum_Of_Rs() and set the result to the TextView every time you add or delete an item in the cart i.e. if you are using ListView always do these steps when you notify the listview about the data changes using notifyDataSetChanged() you can also improve your method sum_Of_Rs() by changing your method to the following:
public long sum_Of_Rs() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT SUM (" + CONTACTS_PRODUCT_RS + ") FROM " + CONTACTS_TABLE_NAME , null);
cursor.moveToFirst();
int sum = cursor.getInt(0);
cursor.close();
return sum;
}
I Suggest to change your SQL Query to :
public long sum_Of_Rs() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT SUM ( " +CONTACTS_PRODUCT_RS + ") FROM " + CONTACTS_TABLE_NAME , null);
c.moveToFirst();
int i = c.getInt(0);
c.close();
return i;
}
PS: SUM() will return a number in the same format of the column that you are reading. if CONTACTS_PRODUCT_RS is a float/double use
float i = c.getFloat(0);
double i = c.getDouble(0);
Hope it help !! :))
Related
I want to make above type of RecyclerView (in my case). In above sample pic, the expenses show in red colours with zebra lines and income shows in green colours. I've write code for expense table values and successfully shown in RecyclerView. Now I want to show income from income table and make view same as sample pic. kindly help.
RecyclerView with expense values:
arrayListExpense = new ArrayList<>();
AdapterViewItems adapter = new AdapterViewItems(MainActivity.this, arrayListExpense);
recyclerView = (RecyclerView) findViewById(R.id.view_item_recycle_view);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(adapter);
Cursor cursor = db.selectExpense();
cursor.moveToFirst();
if (cursor.getCount() == 0) {
Toast.makeText(this, "Empty list", Toast.LENGTH_SHORT).show();
} else {
for (int i = 0; i < cursor.getCount(); i++) {
HashMap<String, Object> hm = new HashMap<>();
hm.put(ID_EXPENSE, cursor.getString(cursor.getColumnIndex(ID_EXPENSE)));
hm.put(NAME_EXPENSE, cursor.getString(cursor.getColumnIndex(NAME_EXPENSE)));
long valueExpense = cursor.getLong(cursor.getColumnIndex(VALUE_EXPENSE));
showExpense(valueExpense);
hm.put(VALUE_EXPENSE, String.valueOf(valueExpense));
hm.put(DATE_EXPENSE, Utility.dateFormat(cursor.getLong(cursor.getColumnIndex(DATE_EXPENSE))));
String id = cursor.getString(cursor.getColumnIndex(TYPE_ID_EXPENSE));
hm.put("type", db.selectTypeById(id));
arrayListExpense.add(hm);
cursor.moveToNext();
}
cursor.close();
}
Database:
Cursor selectExpense() {
Cursor cursor = null;
try {
SQLiteDatabase db = this.getWritableDatabase();
cursor = db.rawQuery("SELECT " + ID_EXPENSE + "," + NAME_EXPENSE + "," + VALUE_EXPENSE
+ "," + DATE_EXPENSE + "," + TYPE_ID_EXPENSE + " FROM " + TABLE_EXPENSE
+ " ORDER BY " + DATE_EXPENSE + " DESC", null);
} catch (Exception e) {
Log.d("selectExpenses", " error " + e.getMessage());
}
return cursor;
}
All you need is getItemViewType which will allow you to inflate multiple views within a recyclerview.
Example : see this or this
Use a tag that gives you information like it is expanses or inform.
add that tag in hashmap.
if(expanses){ // use variable to check expanses or income
hm.put(INFO_EXPENSE_INCOME, "red");
}else{
hm.put(INFO_EXPENSE_INCOME, "green");
}
and in bindViewHolder get the hashmap value and setTextColor accordingly.
I am trying to delete a row in sqlite database from recyclerview adapter. Based on the position of the adapter, I am deleting my row in sqlite like this :
helper = new DBHelper(v.getContext());
database = helper.getWritableDatabase();
//statement = database.compileStatement("update result set ANS =? where SNO ='" + pos + "'");
// statement = database.compileStatement("delete result where SNO ='" + pos + "'");
//statement.bindString(1, ANS);
// statement.executeInsert();
database.delete("result",
"SNO = ? ",
new String[]{Integer.toString(pos)});
Log.d("pos", "" + pos);
// helper.Delete(pos);
database.close();
but it is not deleting in my table, and I am not getting any error. What am I doing wrong?
db = this.getWritableDatabase();
int l;
l = db.delete("result", SNO = ? " , new String[]{pos+1});
if (l > 0) {
Toast.makeText(context, "Removed "+(pos+1), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
db.close();
Here you have pass "pos" so you have not passed right SNO(pos).
Please check SNO is passes on delete query
Try this method ,
public int deleteItem(String id) {
open();
int b = 0;
try {
b = db.delete(DATABASE_TABLE_POST_ITEMS, TAG_PLUS + " = '" + id + "'", null);
} catch (Exception e) {
e.printStackTrace();
}
close();
return b;
}
call this by using this sentence,
holder.img_plus.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
dbhelper.deleteItem((chatMessageList.get((int) v.getTag()).getListid()));
chatMessageList.remove(position);
notifyDataSetChanged();
}
});
i have retrieved some values from DB using the query which is given below.
public Cursor getcredittranscation(String date)
{
String sql="SELECT A.Acc_No,A.Cust_Name, T.Trans_Amnt FROM TransactionTable "
+ "T LEFT JOIN AccMaster A on A.Acc_ID = T.Acc_ID "
+ "WHERE T.Trans_Date =? AND T.Trans_Type=? ORDER BY T.Entry_Time asc";
Cursor cursor = db.rawQuery(sql, new String[]{date, "credit"});
return cursor;
}
And in main activity i want to show these results as a report. Activity code is as given below.
try{
db.open();
Cursor c = db.getdebittranscation(temp);
if (c.moveToFirst()) {
do {
DisplayDebitDetails(c);
debittotal(c);
} while (c.moveToNext());
}
db.close();
}catch (Exception e) {
// TODO: handle exception
Log.e("Retrive Debit Error ", " "+e.getMessage());
}
private void DisplayDebitDetails(Cursor c) {
String tempdebit = debitView.getText().toString() + " ";
tempdebit= " \t"+tempdebit+ "\n\t" +c.getString(0) + "\t\t\t"
+ c.getString(1) + "\t\t\t" + c.getString(2);
debitView.setText(tempdebit);
Log.e("debit", "Acc No :"+c.getString(0) +"Name :"+c.getString(1)+ "Trans Amnt :"+c.getString(2));
}
}
private void debittotal(Cursor c){
int tmp = Integer.parseInt(debiTotalView.getText().toString()+" ");
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp);
Retrieving and viewing all values is ok... But i need the sum of all values in String(2) . which is given in method debittotal(Cursor c). what is the error in that part ?? I am not getting total
you can use getCount() method
int number_of_records = cursor.getCount();
try this and make sure that debitTotalView.getText().toString() is not blank or null
initially that field value must be 0 otherwise it will give you NumberFormatException for invalid int value
replace
int tmp = Integer.parseInt(debiTotalView.getText().toString()+" ");
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp);
with
int tmp = Integer.parseInt(debiTotalView.getText().toString().trim());
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp+"");
I have a database (sqlite on Android) with several columns:
_id, datum, hour, note
The database is created by this:
private static final String DATABASE_CREATE =
"create table worked (_id integer primary key autoincrement, "
+ "datum text not null, hour text not null, "
+ "note text);";
At the end I want the total of hours and minutes out of my database and return it to my mainActivity.
I tried to do this:
public int getTotalHours(){
Cursor c = db.rawQuery("select hour from " + DATABASE_TABLE, null);
int total = 0;
Date hours = new Date();
SimpleDateFormat hourFormat = new SimpleDateFormat("HH:mm");
c.moveToFirst();
for(int i = 0; i<c.getCount(); i++){
String uur = c.getString(i);
try {
hours = hourFormat.parse(uur);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
total += hours.getHours();
}
return total;
}
But I'm already getting a error in my query. I also dont know how if the data is being extracted at the right way, I cant test that because of the query error...
The error I'm getting:
Failed to read row 0, column 1 from a cursorWindow which has 5 rows, 1 columns.
I hope I was in the right way, and that somebody can help me.
Thanks in advance!
Properly loop through your records, retrieve the proper column index, and close your cursor:
public int getTotalHours(){
Cursor c = db.rawQuery("select hour from " + DATABASE_TABLE, null);
if (c == null)
return 0;
try{
int total = 0;
Date hours = new Date();
SimpleDateFormat hourFormat = new SimpleDateFormat("HH:mm");
while(c.moveToNext())
{
String uur = c.getString(0);
try {
hours = hourFormat.parse(uur);
total += hours.getHours();
} catch (ParseException e) {
e.printStackTrace();
}
}
return hours;
}finally{
c.close();
}
}
use
String uur = c.getString(1);
In your for loop, start your int i off at 1 instead of 0
for(int i = 1; i<c.getCount(); i++){
String uur = c.getString(i);
try {
hours = hourFormat.parse(uur);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calling c.moveToNext() at the end of the loop would help. Also c.getString(i) should be c.getString(0).
Please make sure that the hours row is the first one in the db table. if you're not sure this modified code should work
enter code here
public int getTotalHours(){
Cursor c = db.rawQuery("select hour from " + DATABASE_TABLE, null);
int total = 0;
Date hours = new Date();
SimpleDateFormat hourFormat = new SimpleDateFormat("HH:mm");
c.moveToFirst();
int column = c.getColumnIndex("id")
for(int i = 0; i<c.getCount(); i++){
String uur = c.getString(c);
try {
hours = hourFormat.parse(uur);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
total += hours.getHours();
}
return total;
}
First, it's a table in a database what you are creating so I suggest you use CREATE_TABLE variable name instead.
Second, you can do:
Cursor c = db.rawQuery("select sum(hour) from " + DATABASE_TABLE, null);
having defined hour as integer in you table.
If you define the correct columns and use the right operations sqlite can do it:
sqlite> .schema t1
CREATE TABLE t1 (hours time not null);
sqlite> select * from t1;
05:30:00
06:30:00
01:30:00
02:15:00
sqlite> select strftime('%H:%M', 946684800 + sum(strftime('%s', hours) - 946684800), 'unixepoch') from t1;
15:45
sqlite>
I couldn't find a suitable title for my question. Here is the problem... After syso'ing the statement in getData(), it should print the values in the cursor, cMainTable, using the statement in displayDataForMainTable(). But, it doesn't. There are no exceptions, and errors. I have also kept the output that i get in the LogCat. Can someone help me with, why there is no output after the first print.
try {
pm = new PortfolioManager(this);
cMainTable = pm.getData("mainTable");
if (cMainTable.equals(null)) {
System.out.println("Null is returned");
}
displayDataForMainTable(cMainTable);
}
catch (Exception e) {
System.out.println("problem at Oncreate Method");
}
getData() method:
public Cursor getData(String string) {
System.out.println("Getting Data for Table " + string);
c = sqlDB.rawQuery("select * from " + string, null);
return c;
}
displayDataForMainTable() method:
private void displayDataForMainTable(Cursor c2) {
try {
if (c2 != null) {
if (c2.getCount() > 0) {
c2.moveToFirst();
do {
String SNo = c2.getString(c2.getColumnIndex("scriptnumber"));
String SName = c2.getString(c2.getColumnIndex("scriptname"));
int quant = Integer.parseInt(c2.getString(c2.getColumnIndex("totalquantity")));
double avg = Double.parseDouble(c2.getString(c2.getColumnIndex("averageprice")));
double cur = Double.parseDouble(c2.getString(c2.getColumnIndex("currentprice")));
double log = Double.parseDouble(c2.getString(c2.getColumnIndex("lossorgain")));
System.out.println("Inserted Values are ::: " + SNo
+ " " + SName + " " + String.valueOf(quant)
+ " " + String.valueOf(avg) + " "
+ String.valueOf(cur) + " "
+ String.valueOf(log));
} while (c2.moveToNext());
}
}
else {
System.out.println("Cursor c2 is Empty");
}
} catch (Exception e) {
System.out.println("Exception in displayDataForMainTable");
}
}
output
01-18 11:02:27.523: D/dalvikvm(468): GC_EXTERNAL_ALLOC freed 47K, 53% free 2567K/5379K, external 2090K/2137K, paused 45ms
01-18 11:02:33.983: I/System.out(468): Getting Data for Table mainTable
01-18 11:02:36.584: W/KeyCharacterMap(468): No keyboard for id 0
01-18 11:02:36.584: W/KeyCharacterMap(468): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
Edit 1 :::
I have modified the getData() as suggested by Nasser, but the output remains the same..
public Cursor getData(String string) {
System.out.println("Getting Data for Table "+string);
String table = string;
sqlDB = getReadableDatabase();
c = sqlDB.query(table, null, null, null, null, null, null);
//c = sqlDB.rawQuery("select * from "+string, null);
return c;
}
As I read, passing null to the columns(2nd argument) will return all the rows. If this is correct, then the result is the same.
i think u should not return cursor from db instead of that create a setterGetter class set data in its object and return array of that object..
here's my code for same.. try..
also put logs there so u'll get idea about what is going on..
public ArrayList<ContactSetterGetter> getAllNumbers() {
ArrayList<ContactSetterGetter> setterList = new ArrayList<ContactSetterGetter>();
db = getWritableDatabase();
Cursor c = db.query(C_TABLE_NAME, new String[] {"contact_number"},null, null, null, null, null);
if (c.getCount() != 0) {
c.moveToFirst();
do {
ContactSetterGetter setter = new ContactSetterGetter();
setter.setContactNumber(c.getString(0));
setterList.add(setter);
} while (c.moveToNext());
}else{
c.close();
db.close();
return setterList;
}
c.close();
db.close();
return setterList;
}
It seems that Eclipse has shown mercy on me and is displaying the output. Fought for over 4 hours changing code, surfing, finally ended up with no changes in code.
No matter how smart you are as a coder, IDEs always make you feel a novice.