>我的活动类中有一个方法,它应该向玩家打印一个随机角色(存储在SQLite数据库中)。我收到成功消息,但没有执行。到目前为止,我的 SQLite 数据库中只有 1 条记录,并将添加一个 while 循环来填充每一行。
这是我的活动课:
public class StartGame extends AppCompatActivity implements View.OnClickListener {
DatabaseHelper myDb;
Button btnRoles;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startgame);
myDb = new DatabaseHelper(this);
btnRoles = (Button) findViewById(R.id.btnAssignRoles);
assignRoles();
}
public String RandomNumber() {
List < String > roles = Arrays.asList("Mafia", "Mafia", "Angel", "Detective", "Civilian", "Civilian", "Civilian");
Collections.shuffle(roles);
return roles.get(0);
}
public void assignRoles() {
btnRoles.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
{
boolean isUpdated = myDb.updateRole(RandomNumber().toString());
if (isUpdated == true)
Toast.makeText(StartGame.this, "Roles assigned, keep them secret!", Toast.LENGTH_LONG).show();
else
Toast.makeText(StartGame.this, "UNSUCCESSFUL!", Toast.LENGTH_LONG).show();
}
}
}
);
}
这是我的数据库帮助程序类中的方法:
public boolean updateRole(String role){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_ROLE, role);
db.update(TABLE_NAME, contentValues, "Role =?", new String[] {role});
return true;
}
我做错了什么?
您在此行中遇到错误:
db.update(TABLE_NAME, contentValues, "Role =?", new String[] {role});
您正在更新表中的所有行,其中Role = {role}
具有Role
值的列{role}
。所以显然这不会有任何影响。
你需要有一些类似id
的东西,并在你的 where 语句中使用它,像这样的东西:
db.update(TABLE_NAME, contentValues, "id =?", new String[] {id});