前言
最近上智能终端开发课程时,和舍友一起写了个安卓小程序。名字是ZJU健康,用于记录用户的健康变化情况,以及一些其他的辅助功能(如插入图片、时钟等)。现在将本程序的Weight部分来发表在这里,希望能对同样学习这门课的同袍们有所帮助。
所用的开发平台是Android Studio,开发语言为Java。
代码部分
WeightDB模块
package com.android.project.core;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class WeightDB {
protected static final String TAG = WeightDB.class.getSimpleName();
protected static final int DB_VERSION = 1;
protected static final String DB_NAME = "weight_db";
protected static final String DB_PRIMARY_KEY = "_id";
protected static final String DB_TABLE_NAME = "weight";
protected static final String DB_TABLE_COLUMN_WEIGHT = "weight";
protected static final String DB_TABLE_COLUMN_DATE = "record_date";
protected static final String DB_DEFAULT_ORDERBY = DB_TABLE_COLUMN_DATE + " DESC";
protected DatabaseHelper mDBHelper;
protected SQLiteDatabase mDB;
protected OnDBDataChangeListener mDBDataChangeListener;
protected static final WeightDB mInstance = new WeightDB();
private final String DB_TABLE_CREATE_SQL = "create table " + DB_TABLE_NAME + " (_id integer primary key autoincrement, "
+ DB_TABLE_COLUMN_WEIGHT + " text not null, "
+ DB_TABLE_COLUMN_DATE + " integer);";
public interface OnDBDataChangeListener {
public void onDBDataChanged();
}
public static class Weight {
public long key = -1;
public String value;
public long date;
}
protected class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context,String dbName, int dbVersion) {
super(context, dbName , null, dbVersion);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_TABLE_CREATE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE_NAME);
onCreate(db);
}
}
private WeightDB() {};
public static WeightDB getInstance() {
return mInstance;
}
public void setOnDBDataChangeListener(OnDBDataChangeListener listener) {
mDBDataChangeListener = listener;
if (listener!=null) {
listener.onDBDataChanged();
}
}
public boolean open(Context context) {
try {
mDBHelper = new DatabaseHelper(context,DB_NAME,DB_VERSION);
mDB = mDBHelper.getWritableDatabase();
}
catch(SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public void close() {
mDB.close();
mDBHelper.close();
}
public String makeCondition(int position) {
long key = getkey(position,null);
if (key == -1) {
return null;
}
String condition = DB_PRIMARY_KEY + "=" + "\'" + key + "\'";
return condition;
}
public String makeCondition(int position,String condition) {
long key = getkey(position,condition);
if (key == -1) {
return null;
}
String conditions = DB_PRIMARY_KEY + "=" + "\'" + key + "\'";
return conditions;
}
public String makeCondition(long startdate,long enddate) {
String condition = DB_TABLE_COLUMN_DATE + " >= " + startdate + " AND ";
condition += (DB_TABLE_COLUMN_DATE + " < " + enddate);
return condition;
}
public String makeCondition(String condition1,String condition2) {
String condition = condition1 + " AND " + condition2;
return condition;
}
public int size() {
return size(null);
}
public int size(String condition) {
Cursor mCursor = mDB.query(DB_TABLE_NAME,new String[]{DB_PRIMARY_KEY},condition,null,null,null,
null, null);
int size = mCursor.getCount();
mCursor.close();
return size;
}
public boolean insert(Weight weight) {
ContentValues values = new ContentValues();
values.put(DB_TABLE_COLUMN_WEIGHT, weight.value);
values.put(DB_TABLE_COLUMN_DATE, weight.date);
weight.key = mDB.insert(DB_TABLE_NAME,null,values);
if (weight.key == -1) {
Log.e(TAG,"db insert fail!");
return false;
}
if (mDBDataChangeListener!=null) {
mDBDataChangeListener.onDBDataChanged();
}
return true;
}
public boolean update(Weight weight) {
if (weight.key == -1) {
return false;
}
ContentValues values = new ContentValues();
values.put(DB_TABLE_COLUMN_WEIGHT, weight.value);
values.put(DB_TABLE_COLUMN_DATE, weight.date);
String condition = DB_PRIMARY_KEY + "=" + "\'" + weight.key + "\'";
if (!update(values,condition,null)) {
return false;
}
if (mDBDataChangeListener!=null) {
mDBDataChangeListener.onDBDataChanged();
}
return true;
}
protected boolean update(ContentValues values, String whereClause, String[] whereArgs) {
int rows = mDB.update(DB_TABLE_NAME,values, whereClause, whereArgs);
if (rows <= 0) {
Log.d(TAG,"db update fail!");
return false;
}
return true;
}
public boolean delete(int position) {
return delete(makeCondition(position));
}
public boolean delete(int position,String condition) {
return delete(makeCondition(position,condition));
}
public boolean delete(String condition) {
return delete(condition,null);
}
protected boolean delete(String whereClause, String[] whereArgs) {
int rows = mDB.delete(DB_TABLE_NAME,whereClause,whereArgs);
if (rows <= 0) {
Log.e(TAG,"db delete fail!");
return false;
}
if (mDBDataChangeListener!=null) {
mDBDataChangeListener.onDBDataChanged();
}
return true;
}
public boolean clear() {
return delete(null,null);
}
public boolean clear(String condition) {
return delete(condition,null);
}
public Weight get(int position) {
return get(position,null);
}
public Weight get(int position,String condition) {
Cursor cursor = mDB.query(DB_TABLE_NAME,null,condition,null,null,null,
DB_DEFAULT_ORDERBY,null);
List<Weight> weights = extract(position,cursor);
if (weights.isEmpty()) {
return null;
}
return weights.get(0);
}
public List<Weight> query() {
Cursor cursor = mDB.query(DB_TABLE_NAME,null,null,null,null,null,
DB_DEFAULT_ORDERBY,null);
return extract(0,cursor);
}
public List<Weight> query(String condition) {
Cursor cursor = mDB.query(DB_TABLE_NAME,null,condition,null,null,null,
DB_DEFAULT_ORDERBY,null);
return extract(0,cursor);
}
public List<Weight> query(int offset,int limit) {
return query(null,offset,limit);
}
public List<Weight> query(String condition,int offset,int limit) {
Cursor cursor = mDB.query(DB_TABLE_NAME,null,condition,null,null,null,
DB_DEFAULT_ORDERBY, offset + "," + limit);
return extract(0,cursor);
}
protected List<Weight> extract(int position, Cursor cursor) {
List<Weight> weights = new ArrayList<Weight>();
if (cursor == null || cursor.getCount() <= position) {
return weights;
}
cursor.moveToFirst();
cursor.moveToPosition(position);
do {
Weight weight = new Weight();
weight.key = cursor.getLong(cursor.getColumnIndex(DB_PRIMARY_KEY));
weight.value = cursor.getString(cursor.getColumnIndex(DB_TABLE_COLUMN_WEIGHT));
weight.date = cursor.getLong(cursor.getColumnIndex(DB_TABLE_COLUMN_DATE));
weights.add(weight);
}while(cursor.moveToNext());
cursor.close();
return weights;
}
protected long getkey(int position,String condition) {
long key = -1;
Cursor cursor = mDB.query(true,DB_TABLE_NAME, new String[]{DB_PRIMARY_KEY},condition,null,null,null,
DB_DEFAULT_ORDERBY, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToPosition(position);
key = cursor.getLong(cursor.getColumnIndex(DB_PRIMARY_KEY));
cursor.close();
}
return key;
}
}
WeightDBHelper模块
package com.android.project.core;
import java.text.DecimalFormat;
import java.util.List;
import com.android.project.Configuration;
import com.android.project.core.DateHelper.DatePeriod;
import com.android.project.core.WeightDB.Weight;
public class WeightDBHelper {
public static boolean isEmpty() {
return WeightDB.getInstance().size()==0;
}
public static boolean isEmpty(int year) {
DatePeriod period = DateHelper.getYearPeriod(year);
String condition = WeightDB.getInstance().makeCondition(period.begin,period.end);
return WeightDB.getInstance().size(condition)==0;
}
public static boolean isEmpty(int year,int month) {
DatePeriod period = DateHelper.getMonthPeriod(year,month);
String condition = WeightDB.getInstance().makeCondition(period.begin,period.end);
return WeightDB.getInstance().size(condition)==0;
}
public static boolean isEmpty(int year,int month,int day) {
DatePeriod period = DateHelper.getDatePeriod(year,month,day);
String condition = WeightDB.getInstance().makeCondition(period.begin,period.end);
return WeightDB.getInstance().size(condition)==0;
}
public static Double getWeightAverage(int year) {
DatePeriod period = DateHelper.getYearPeriod(year);
return getWeightAverage(period);
}
public static Double getWeightAverage(int year,int month) {
DatePeriod period = DateHelper.getMonthPeriod(year,month);
return getWeightAverage(period);
}
public static Double getWeightAverage(int year,int month,int day) {
DatePeriod period = DateHelper.getDatePeriod(year,month,day);
return getWeightAverage(period);
}
public static Double getWeightReduceThisWeek() {
DatePeriod period = DateHelper.getWeekPeriod(DateHelper.getToday());
String condition = WeightDB.getInstance().makeCondition(period.begin,period.end);
List<Weight> weights = WeightDB.getInstance().query(condition);
if (weights.size() < 2) {
return 0.0;
}
return Double.valueOf(weights.get(0).value) - Double.valueOf(weights.get(weights.size()-1).value);
}
public static Double getWeightReduceThisMonth() {
DatePeriod period = DateHelper.getMonthPeriod(DateHelper.getToday());
String condition = WeightDB.getInstance().makeCondition(period.begin,period.end);
List<Weight> weights = WeightDB.getInstance().query(condition);
if (weights.size() < 2) {
return 0.0;
}
return Double.valueOf(weights.get(0).value) - Double.valueOf(weights.get(weights.size()-1).value);
}
public static Double getWeightAverage(DatePeriod period) {
String condition = WeightDB.getInstance().makeCondition(period.begin,period.end);
List<Weight> weights = WeightDB.getInstance().query(condition);
Double average = 0.0;
if (weights.isEmpty()) {
return average;
}
for (int i=0; i<weights.size(); i++) {
average += Double.valueOf(weights.get(i).value);
}
average = average/weights.size();
DecimalFormat format = new DecimalFormat("0.00");
average = Double.valueOf(format.format(average).toString());
return average;
}
public static boolean isYestdayRecord() {
DatePeriod period = DateHelper.getDatePeriod(DateHelper.getYestday());
String condition = WeightDB.getInstance().makeCondition(period.begin,period.end);
List<Weight> weights = WeightDB.getInstance().query(condition);
if (weights.isEmpty()) {
return false;
}
return true;
}
public static boolean isTodayRecord() {
DatePeriod period = DateHelper.getDatePeriod(DateHelper.getToday());
String condition = WeightDB.getInstance().makeCondition(period.begin,period.end);
List<Weight> weights = WeightDB.getInstance().query(condition);
if (weights.isEmpty()) {
return false;
}
return true;
}
public static int getContinuousDays() {
if (!isYestdayRecord()) {
if (isTodayRecord()) {
Configuration.setContinousDays(1);
}
else {
Configuration.setContinousDays(0);
}
}
return Configuration.getContinousDays();
}
public static void addContinuousDays() {
if (!isTodayRecord()) {
int continuous = Configuration.getContinousDays();
Configuration.setContinousDays(++continuous);
}
}
}
WeightData模块
package com.android.project;
import java.text.DecimalFormat;
import com.android.project.core.DateHelper;
import com.android.project.core.WeightDB.Weight;
public class WeightData {
private static final String WEIGHT_SUFFIX = "kg";
private static final String BMI_PREFIX = "BMI: ";
public String mWeightValue;
public long mRecordDate;
public WeightData(Weight weight) {
mWeightValue = weight.value;
mRecordDate = weight.date;
}
public String getWeightValue() {
return mWeightValue;
}
public String getWeightStr() {
String result = String.format("%-4s", mWeightValue);
return (result + " " + WEIGHT_SUFFIX);
}
public String getBMIStr() {
return (BMI_PREFIX + getBMIValue());
}
public String getWeekStr() {
return DateHelper.getWeekStr(mRecordDate);
}
public String getDateStr() {
return DateHelper.getDateStr(mRecordDate);
}
public String getBMIValue() {
double height = Configuration.getUserHeight();
if (height == 0.0) {
return "0.00";
}
double bmi = CommonUtil.calculateBMI(Double.valueOf(mWeightValue), height);
return new DecimalFormat("0.00").format(bmi).toString();
}
}
WeightDataAdapter模块
package com.android.project;
import com.android.project.R;
import com.android.project.core.WeightDB;
import com.android.project.core.WeightDB.Weight;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
public class WeightDataAdapter extends BaseAdapter {
private Context mContext;
private String mCondition = null;
protected class ViewHolder {
TextView mWeightWeek;
TextView mWeightData;
TextView mWeightBMI;
TextView mWeightValue;
}
public WeightDataAdapter(Context context,String condition) {
mContext = context;
mCondition = condition;
}
@Override
public int getCount() {
return WeightDB.getInstance().size(mCondition);
}
@Override
public Object getItem(int position) {
return WeightDB.getInstance().get(position,mCondition);
}
@Override
public long getItemId(int position) {
return ((Weight)getItem(position)).key;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = (LinearLayout)inflater.inflate(R.layout.widget_weight_item, null);
ViewHolder holder = new ViewHolder();
holder.mWeightWeek = (TextView)convertView.findViewById(R.id.WeightWeek);
holder.mWeightData = (TextView)convertView.findViewById(R.id.WeightData);
holder.mWeightBMI = (TextView)convertView.findViewById(R.id.WeightBMI);
holder.mWeightValue = (TextView)convertView.findViewById(R.id.WeightValue);
convertView.setTag(holder);
}
Weight weight = (Weight)getItem(position);
if (weight != null) {
WeightData data = new WeightData(weight);
ViewHolder holder = (ViewHolder)convertView.getTag();
holder.mWeightWeek.setText(data.getWeekStr());
holder.mWeightData.setText(data.getDateStr());
holder.mWeightBMI.setText(data.getBMIStr());
holder.mWeightValue.setText(data.getWeightStr());
}
return convertView;
}
}
后记
以上各部分代码仅为weight部分代码,用于给大家扩展思路。如果想要主要源程序,可以联系笔者。但个人建议还是自己试着开拓着写一写对自己的能力提高比较大。