所以我正在尝试为我的一个朋友制作一个应用程序,这个朋友是一个铁杆锻炼迷,而且我被困在应用程序的一部分上。
我试图让它自动保存每一次训练的日期和时间,这样他就可以回头看看他最后一次训练的时间以及他在一个月内做了多少次以及类似的事情。
但是,我不知道如何解决这个问题。我对SharedPreferences的了解很少,而且我无法集成Google日历。还有其他方法可以让这样的事情发生吗?
如果没有,有人可以帮我处理SharedPreferences部分吗?
谢谢。
答案 0 :(得分:0)
我在这里为您创建了一个设计。您可以根据您的要求进行必要的更改。
//Create a dbHelper class like this
public class DatabaseNew extends SQLiteOpenHelper {
private static final String TAG = "DataBase";
public DatabaseNew(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Module1";
private static final String USERTABLE = "USER_INFO";
private static final String KEY_ID = "id";
private static final String WORKOUT = "WORKOUT";
private static final String WORKOUT_TIME = "WORKOUT_TIME";
private static final String CREATE_TABLE_USER = "CREATE TABLE IF NOT EXISTS "
+ USERTABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY," + WORKOUT + " TEXT,"
+ WORKOUT_TIME + " TEXT"+");";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + USERTABLE;
@Override
public void onCreate(SQLiteDatabase db) {
Log.e(TAG,"Inside onCreate: creating table");
db.execSQL(CREATE_TABLE_USER);
}
//to save workout name and time in db
public void saveData(String workout, String time){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues data = new ContentValues();
data.put(WORKOUT,workout);
data.put(WORKOUT_TIME,time);
db.insert(USERTABLE,null,data);
db.close();
}
//to get workout name and time from db
public List<HashMap<String,String>> getData(){
List<HashMap<String,String>> userData = new ArrayList<>();
String selectQuery = "SELECT * FROM " + USERTABLE ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String,String> dataMap = new HashMap<>();
dataMap.put(WORKOUT,cursor.getString(cursor.getColumnIndex(WORKOUT)));
dataMap.put(WORKOUT_TIME,cursor.getString(cursor.getColumnIndex(WORKOUT_TIME)));
userData.add(dataMap);
} while (cursor.moveToNext());
}
cursor.close();
return userData;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.e(TAG,"Inside onUpgrade");
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}
//然后在你的活动中
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
//Initializing the db
DatabaseNew db = new DatabaseNew(this);
//sending dummy data you can send actual workout and time like this
db.saveData("pull up","30 mins");
db.saveData("push up","40 mins");
db.saveData("Leg up","30 mins");
db.saveData("crunches","30 mins");
db.saveData("Bench Press","30 mins");
//to retrieve data from data base
List<HashMap<String,String>> data = db.getData();
for (HashMap<String,String> a : data){
Log.e("TestActivity"," "+"Workout : "+a.get("WORKOUT")
+" "+"Time : "+a.get("WORKOUT_TIME"));
}
}
希望它有所帮助!!!