Bugs with Total Amount,Wrong Calculation & format - android

May I know what's the problem with this? It should be "5555555556" instead. See the Total Amount is Not CORRECT.
Is My Code wrote wrong already?
Here is my CODE
//show total amount
try {
SQLiteDatabase db = mSQLiteHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT SUM (Amount) from Donation_Details WHERE strftime('%d %m %Y',CreatedDate) = strftime('%d %m %Y',date('now'))", null);
if (cursor.moveToFirst()) {
int sum = cursor.getInt(0);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String yourFormattedString = formatter.format(sum);
total_Amount.setText("RM " + yourFormattedString);
}
} catch (Exception e) {
e.printStackTrace();
}
And It can't show Decimal if I wrote "555555.55". It will only show infront numbers. Can anyone help me?

Change int to double of sum variable and also change DecimalFormat like below code,
try {
SQLiteDatabase db = mSQLiteHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT SUM (Amount) from Donation_Details WHERE strftime('%d %m %Y',CreatedDate) = strftime('%d %m %Y',date('now'))", null);
if (cursor.moveToFirst()) {
double sum = cursor.getDouble(0);
DecimalFormat formatter = new DecimalFormat("#,###,###,###.00");
String yourFormattedString = formatter.format(sum);
total_Amount.setText("RM " + yourFormattedString);
}
} catch (Exception e) {
e.printStackTrace();
}

The solution is to change
int
to
double
and change your decimal format to
DecimalFormat formatter = new DecimalFormat("#,###,###,###");

Related

How to update total price in cart listview in android

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 !! :))

SQLite search by name, show sum result in textfield

I have a code that would give me the sum of a column in a database, i have done the crud, but now i would like to do a search by a the name of a column and show the sum of all the records(that have the same name) and show in a textfield.
the following is my DatabasdeHandler:
public Cursor getSingleDespesaSum(String date) {
SQLiteDatabase db = this.getReadableDatabase();
int sum = 0;
Cursor cursor = db.rawQuery(
"select sum(valor) from despesas WHERE data = ?", null);
if (cursor.moveToFirst()) {
do {
sum = cursor.getInt(0);
} while (cursor.moveToNext());
}
return cursor;
}
And this is my activity;
btGetSum.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
dia = (String) spinDia.getSelectedItem();
mes = (String) spinMes.getSelectedItem();
ano = (String) spinAno.getSelectedItem();
String dataSendTo = dia + "/" + mes + "/" + ano;
dbhelper.getSingleDespesaSum(dataSendTo); //missing code
} catch (Exception erro) {
mensagemExibir("Erro Ao Buscar", "" + erro.getMessage());
}
}
});
}
Content Providers are the way to go, don't access your database directly like this.
But... to answer your current question:
SQLiteDatabase db = this.getReadableDatabase();
int sum = 0;
Cursor cursor = db.rawQuery(
"select value from table WHERE date= ?", null);
while (cursor.moveToNext()) {
//Increment your counter
sum += cursor.getInt(cursor.getColumnIndex("value");
};

Why does the variable return 0 always?

I am trying to retrieve the count from a Sqlite database. But the variable number is always returning zero even if I adda values in the database. can anyone tell me step by step what am I doing wrong. Here is my code.
public int isUserAvailable(Double latitude,Double longitude)
{
int number = 0;
Cursor c = null;
try
{
c = db.rawQuery("select latitude,longitude from savedlocation where latitude = ? and longitude = ? ", new String[] {String.valueOf(latitude),String.valueOf(longitude)});
if(c.getCount() != 0)
number = c.getCount();
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return number;
}
I think its because I have initialized number=0; so its returning that value. I am not able to access number outside try.
{String.valueOf(latitude),String.valueOf(longitude)} may be the problem
it doesnt happen EVERY time, but sometimes String.valueOf returns an unexpected value
something like u - s - e - r - a - r - r - y
try latitude+"" , longitude+"" to convert them to string.
cursor.moveToFirst should not affect cursor.getCount()
public int isUserAvailable(Double latitude,Double longitude)
{
int number = 0;
Cursor c = null;
try
{
c = db.rawQuery("select latitude,longitude from savedlocation where latitude = ? and longitude = ? ", new String[] {latitude+"",longitude+""});
if(c.getCount() != 0)
number = c.getCount();
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return number;
}
On a side note, if you want to just get the number of rows that match a query try this:
public int isUserAvailable(Double latitude,Double longitude)
{
int number = 0;
Cursor c = null;
try
{
c = db.rawQuery("select count(*) from savedlocation where latitude = ? and longitude = ? ", new String[] {latitude+"",longitude+""});
if(c.moveToFirst())
number = c.getInt(0);
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return number;
}

Getting total out of sqlite database

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>

how to retrieve values from the database(Sqlite) by using date in android?

I have stored the date as string in sqlite database table. What i need i i have to retrieve the values which stored in last seven days. I have tried by using following but it doesn't showing any values.
My Database function
public Cursor paymentWeek(Activity activity)
{
String[] from = { _PAYMENTID, NAME, REQUESTEDDATE, FROMAD, TOADD, EMAILBODYPAYMENT, AMOUNT};
SQLiteDatabase db = getReadableDatabase();
String orderby = REQUESTEDDATE+" DESC";
Cursor cursor = db.rawQuery("select * from " + PAYMENTTABLE + " where " + REQUESTEDDATE + " BETWEEN "
+ "date('now')" + " AND " + "date('now','-7 days')", null);
activity.startManagingCursor(cursor);
return cursor;
}
Calling function
Cursor week = db.paymentWeek(this);
String[] weekly = new String[] { PaymentAppDataBase.REQUESTEDDATE,PaymentAppDataBase.PAYMENTNAME,PaymentAppDataBase.AMOUNT };
int[] sevendays = new int[] { R.id.Date,R.id.Name,R.id.Amount };
SimpleCursorAdapter weekcursor =
new SimpleCursorAdapter(this, R.layout.listview, week, weekly, sevendays);
setListAdapter(weekcursor);
db.close();
It would be helpful if you guys sort out this problem. I get stuck over here.
try Following query to get records for last week(7 days):
"select * from " + PAYMENTTABLE + " where " + REQUESTEDDATE + "DATE_SUB( CURDATE( ) ,INTERVAL 7 DAY ) AND CURDATE( )";
You don't have to change your db design.
Just write your own convert from dateString to long method, and put it in class like DateUtil.java, then call it wherever you want to do something with date type.
The method should look like this:
public static long convertStringDateToLong(String date, String yourDateFormat) {
Long time = 0L;
try {
SimpleDateFormat df = new SimpleDateFormat(yourDateFormat);
Date d = null;
try {
d = df.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
time = d.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return time;
}
where yourDateFormat should be something like: "MM/dd/yyyy"

Categories

Resources