[英]whenever I am going to update a record each time it will create a new entry ( not able to update a record in database)
[英]How to make sql database update if entry exists and if not, insert a new record
我的代碼中有問題,這是一個井字游戲,每次用戶贏得游戲時,它會將高分(點)保存到sql數據庫中。 如果用戶名不存在,它將在列表視圖中創建一個新的用戶名。 我似乎找不到這些點沒有增加的原因。 有什么幫助嗎?
這是我嘗試更新數據庫並在用戶名已經存在的情況下將點增加一的活動。 否則,請創建新的。
private boolean player1Turn = true;
private int roundCount;
private TextView currentPlayer;
private Button[][] buttons = new Button[3][3];
private int player1Points;
private int player2Points;
private DbHighscoresHelper dbHelper;
private ArrayAdapter<String> mAdapter;
private ListView mScoreListView;
private SQLiteDatabase scoreDB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_board);
createTable();
dbHelper = new DbHighscoresHelper(this);
mScoreListView = findViewById(R.id.highscore_list);
}
private void createTable() {
//create the table
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
String btn_id = "button_" + i + j;
int resID = getResources().getIdentifier(btn_id, "id", getPackageName());
buttons[i][j] = findViewById(resID);
buttons[i][j].setOnClickListener(this);
}
}
}
@Override
public void onClick(View v) {
TextView whoseTurn = (TextView) findViewById(R.id.whose_turn);
if (checkForWin() == true) {
Toast.makeText(this, "Game over", Toast.LENGTH_SHORT).show();
return;
}
//checks if the clicked button is empty(empty string), if not, the button is full
if(!((Button) v).getText().equals("")) {
return;
}
//lets check if its player1turn, puts the mark in the button
if(player1Turn) {
((Button) v).setText("X");
} else {
((Button) v).setText("O");
}
if(player1Turn) {
whoseTurn.setText("Player 1's turn");
} else {
whoseTurn.setText("Player 2's turn");
}
//one round is over until all the rounds are used(9)
roundCount++;
if(checkForWin()) {
if(player1Turn) {
winnerPlayer1();
} else {
winnerPlayer2();
}
} else if(roundCount == 9) {
draw();
} else {
player1Turn = !player1Turn;
}
}
private boolean checkForWin() {
String[][] checkBoard = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//check if the checkboard stuff is in the same place than in the buttons board
checkBoard[i][j] = buttons[i][j].getText().toString();
}
}
//lets go through all the rows
for (int i = 0; i < 3; i++) {
//columns, check field to the one next to it and all three of them
if(checkBoard[i][0].equals(checkBoard[i][1])
&& checkBoard[i][0].equals(checkBoard[i][2])
&& ! checkBoard[i][0].equals("")) {
return true; //theres a winner
}
}
//lets go through columns
for (int i = 0; i < 3; i++) {
//columns, check field to the one next to it and all three of them
if(checkBoard[0][i].equals(checkBoard[1][i])
&& checkBoard[0][i].equals(checkBoard[2][i])
&& ! checkBoard[0][i].equals("")) {
return true; //theres a winner
}
}
//lets check diagonals
if(checkBoard[0][0].equals(checkBoard[1][1])
&& checkBoard[0][0].equals(checkBoard[2][2])
&& ! checkBoard[0][0].equals("")) {
return true; //theres a winner
}
//lets check diagonals
if(checkBoard[0][2].equals(checkBoard[1][1])
&& checkBoard[0][2].equals(checkBoard[2][0])
&& ! checkBoard[0][2].equals("")) {
return true; //theres a winner
}
return false; //we dont have a winner
}
public void winnerPlayer1() {
Toast.makeText(getApplicationContext(), "Player 1 won", Toast.LENGTH_SHORT).show();
player1Points++;
enterName(player1Points);
}
public void winnerPlayer2() {
Toast.makeText(getApplicationContext(), "Player 2 won", Toast.LENGTH_SHORT).show();
player2Points++;
enterName(player2Points);
}
private void draw() {
Toast.makeText(getApplicationContext(), "Draw", Toast.LENGTH_SHORT).show();
}
public boolean enterName(final int points) {
if(checkForWin()) {
final EditText editText = new EditText(this);
android.support.v7.app.AlertDialog alert = new android.support.v7.app.AlertDialog.Builder(this)
.setTitle("You won!")
.setMessage("Enter your name")
.setView(editText)
.setPositiveButton("Apply", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String getText = editText.getText().toString();
new backGroundStuff(points, getText).execute();
}
})
.setNegativeButton("Cancel", null)
.create();
alert.show();
}
return false;
}
public static boolean doesDatabaseExists(Context c, String scoreDb) throws IOException {
File dbFile = c.getDatabasePath(scoreDb);
FileOutputStream file = new FileOutputStream(dbFile);
file.close();
return dbFile.exists();
}
public boolean nameExists(String tableName, String dbField, String fieldValue) {
SQLiteDatabase scoreDb = dbHelper.getWritableDatabase();
String Query = "SELECT " + highscores.highscoreEntry._ID + " FROM " + tableName + " WHERE " + fieldValue + " = " + fieldValue;
Cursor cursor = scoreDb.rawQuery(Query, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
return true;
}
public static class backGroundStuff extends AsyncTask<String, Void, Boolean> {
int points;
String getText;
backGroundStuff(int points, String getText) {
this.points = points;
this.getText = getText;
}
@Override
protected void onPreExecute() {
}
@Override
protected Boolean doInBackground(String...params) {
SQLiteDatabase scoreDB = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(highscores.highscoreEntry.COL_HIGHSCORE_TITLE, this.getText);
values.put(highscores.highscoreEntry.COL_HIGHSCORE_SCORE, this.points);
Cursor c = scoreDB.rawQuery("SELECT * FROM highscores WHERE title LIKE '" + this.getText + "'", null);
if (c.getCount() == 0) {
c.close();
scoreDB.insert(highscores.highscoreEntry.TABLE, null, values);
} else {
c.moveToNext();
scoreDB.update(highscores.highscoreEntry.TABLE, values, highscores.highscoreEntry.COL_HIGHSCORE_SCORE + " ?" , new String[] {Integer.toString(this.points)});
}
scoreDB.close();
return true;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
}
}
在查找您使用的現有行時
Cursor c = scoreDB.rawQuery("SELECT * FROM highscores WHERE title LIKE '" + this.getText + "'", null);
您不應該使用百分比修飾符使它匹配“包含”而不是“等於”,如下所示:
Cursor c = scoreDB.rawQuery("SELECT * FROM highscores WHERE title LIKE '%" + this.getText + "%'", null);
如果沒有通配符百分號,則實際上是在直接匹配。 另外,我不確定區分大小寫的匹配是否也是一個問題。
Cursor c = scoreDB.rawQuery("SELECT * FROM highscores WHERE LOWER(title) LIKE '%" + this.getText.toLowerCase() + "%'", null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.