我在我的 android 应用程序中使用 SQLite DB 来存储足球运动员并维护他们所属的名单。管理这些花名册的活动能够打开 2 个对话窗口,1 个用于将当前花名册保存到数据库,1 个用于从数据库加载现有花名册。
保存花名册然后打开加载花名册的对话框时,在我对现有花名册的查询中找不到新保存的花名册。如果我退出活动并重新启动它,则会列出新的名册并且可以正常加载。
这是在数据库中查询现有名册名称的代码
public String[] fetchRosterNames() {
String query = "SELECT "+ _ID + ", " + ROSTER_NAME + ", COUNT(" + ROSTER_NAME + ") As `NUM_PLAYERS`" +
" FROM " + TABLE_NAME +
" GROUP BY " + ROSTER_NAME;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
ArrayList<String> rosterNames = new ArrayList<String>();
if(cursor.getCount() > 0){
while(!cursor.isLast()){
cursor.moveToNext();
rosterNames.add(cursor.getString(1));
}
}
cursor.close();
db.close();
return rosterNames.toArray(new String[rosterNames.size()]);
}
这是将花名册插入数据库的代码 public void insertRoster(String roster_name, LeagueRoster roster){
SQLiteDatabase db = getWritableDatabase();
Iterator<Player> players = roster.getFullRoster();
while(players.hasNext()){
Player player = players.next();
ContentValues values = new ContentValues();
Log.e("MySQLiteHelper: insertRoster()", player.getName());
values.put(PlayerStats.NAME.name(), player.getName());
values.put(PlayerStats.POSITION.name(), player.getPosition().name());
values.put(PlayerStats.TEAM.name(), player.getTeam().name());
values.put(ROSTER_NAME, roster_name);
db.insertOrThrow(TABLE_NAME, null, values);
}
db.close();
}
最后,这是我的活动中创建两个不同对话框的代码
protected Dialog onCreateDialog(int id){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
switch(id) {
case 1:
final MySQLiteHelper rosterData = new MySQLiteHelper(this);
final String[] items = rosterData.fetchRosterNames();
builder.setTitle("Select the roster you would like to load");
builder.setItems(items, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
Log.e("Roster Names Dialog", items[which]);
LeagueRoster loadedRoster = rosterData.fetchRoster(items[which]);
if(loadedRoster != null){
roster = loadedRoster;
db.setRoster(roster);
redrawTables();
}
}
});
dialog = builder.create();
break;
case 2:
default:
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View saveRosterView = inflater.inflate(R.layout.saveroster_dialog, null);
builder.setView(saveRosterView);
final EditText nameField = (EditText)saveRosterView.findViewById(R.id.saveroster_dialog_editText);
Button saveButton = (Button)saveRosterView.findViewById(R.id.saveroster_dialog_button);
saveButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
MySQLiteHelper rosterData = new MySQLiteHelper(RosterActivity.this);
String rosterName = nameField.getText().toString();
rosterData.insertRoster(rosterName, roster);
dialog.dismiss();
}
});
dialog = builder.create();
break;
}
return dialog;
}
如果有人有任何想法,我将非常感谢您对这个问题的帮助......