I have an Android app that asks users to enter distance as a field. It is set as a SQLite REAL data type as I need a decimal place. I want to sum the column and display that to the user in a fragment as the Total distance they covered. I have a DBmanager with the code below. I'm not sure if that is the correct way to get a SUM value.
public Cursor Distance() {
Cursor Distance = database.rawQuery("SELECT Sum(" + DatabaseHelper.DSNM + ") AS myTotal FROM " + DatabaseHelper.TABLE_NAME, null);
return Distance;
}
I want to display the SUM value in a textView for which I have the code below. Could someone tell me where i'm going wrong? Thanks!
public class Summary extends Activity {
private TextView tnmView;
private DBManager dbManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Total Distance");
setContentView(R.layout.fragment_summary);
tnmView = (TextView) findViewById(R.id.tnmView);
dbManager = new DBManager(this);
dbManager.open();
Cursor Distance = dbManager.Distance();
tnmView.setText(nm);
}
}
You need to get column result as below
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Total Distance");
setContentView(R.layout.fragment_summary);
tnmView = (TextView) findViewById(R.id.tnmView);
dbManager = new DBManager(this);
dbManager.open();
Cursor Distance = dbManager.Distance();
String result = "";
// get column value
if (Distance.moveToNext())
result = String.valueOf(Distance.getDouble(Distance.getColumnIndex("myTotal")));
tnmView.setText(result);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.