jashajasha jashajasha - 12 days ago 7
Android Question

Android sum all values from SQLite database to textview

What i want to do is to get all values from a column in a database table, add the values upp and show the sum of these values in a textview. What i have tried so far is:

public int addAllValues(){

int total = 0;

Cursor c = db.rawQuery("SELECT SUM(" + (K_SALARY) + ") FROM " + DATABASE_TABLE, null);
if(c.moveToFirst()){
total = c.getInt(0);
}
return total;

}


And in main:

int sum = myDb.addAllValues();
DaySalary = (TextView) findViewById(R.id.txtDaySalary);
DaySalary.setText(sum);


I don't know what im doing wrong here. This is the error i get:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ad.salarycount, PID: 4236
android.content.res.Resources$NotFoundException: String resource ID #0x15
at android.content.res.Resources.getText(Resources.java:299)
at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
at android.widget.TextView.setText(TextView.java:4132)
at com.example.ad.salarycount.MySalary.addIhop(MySalary.java:71)
at com.example.ad.salarycount.MySalary.access$100(MySalary.java:22)
at com.example.ad.salarycount.MySalary$1.onClick(MySalary.java:52)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Answer

First convert integer to String:

 DaySalary.setText(Integer.toString(sum));

Or

 DaySalary.setText(sum+"");