我找到了恢复我的价值观的解决方案,请查看我的 populateFields() 新版本 好的,所以我一直在阅读此处的所有 Spinner 和 SQlite 帖子,似乎无法为我正在寻找的内容找到一个好的答案,所以我发布这种情况。我的应用程序有两个屏幕,并使用我设备上的 sqlite 数据库将 editTexts 中的名称和权重字段保存为字符串,如下所示
String eName = name.getText().toString();
String eWeight = weight.getText().toString();// where name and weight are EditTexts
我有两个微调器如下
String eReps = spinReps.getSelectedItem().toString();
String eSets = spinSets.getSelectedItem().toString();
然后我调用它来添加到数据库中
long id = mDbHelper.createExercise(eName, eWeight, eReps, eSets);
这是我的问题所在,当有人选择创建新练习时,我的应用程序崩溃,因为它试图错误地填充微调器。这是我目前所拥有的。
private void populateFields(){
if(mRowId != null){ // where mRowId is the selected row from the list
Cursor exercise = mDbHelper.fetchExercise();
name.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_NAME)));
weight.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_WEIGHT)));
// this is the part that i need help with, I do not know how to restore
// the current items spinner value for reps and sets from the database.
spinReps.setSelection(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS)));
spinSets.setSelection(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_SETS)));
}
I assume I need to use some sort of adapter to restore my list items along with the current value from the database, I am just not sure how.
Can someone please help me with this???
** BELOW IS MY SOLUTION**
I had to move my ArrayAdapters repsAdapter, spinAdapter out of my onCreate() and then implement this new populateFields()
private void populateFields(){
if(mRowId != null){
Cursor exercise = mDbHelper.fetchExercise(mRowId);
// same as before
name.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_NAME)));
// get the string for sReps and sSets from the database
String sReps = exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS));
String sSets = exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_SETS));
// use the strings to get their position in my adapters
int r = repsAdapter.getPosition(sReps);
int s = setsAdapter.getPosition(sSets);
// set their returned values to the selected spinner Items
spinReps.setSelection(r);
spinSets.setSelection(s);
// same as before
weight.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_WEIGHT)));
}
}