我很难创建三个表并向其中插入值。
SQlite查询是正确的,因为在我尝试制作三个表并向其中插入值之前,它仅处理一个表。
此外,我只放入GameOver类的一部分,并声明了数据类型。 感谢您的帮助。
import static com.avrahamzilberblat.battleshipfinal.Constants.COL1;
import static com.avrahamzilberblat.battleshipfinal.Constants.COL2;
import static com.avrahamzilberblat.battleshipfinal.Constants.COL3;
import static com.avrahamzilberblat.battleshipfinal.Constants.TABLE_NAME_Easy;
import static com.avrahamzilberblat.battleshipfinal.Constants.TABLE_NAME_Hard;
import static com.avrahamzilberblat.battleshipfinal.Constants.TABLE_NAME_Normal;
import static com.avrahamzilberblat.battleshipfinal.Constants.TAG;
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context,String tableName) {
super(context, tableName, null, 5);
SQLiteDatabase dbEasy=this.getWritableDatabase();
SQLiteDatabase dbNormal=this.getWritableDatabase();
SQLiteDatabase dbHard=this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME_Hard + " (ID INTEGER PRIMARY KEY, " +
COL2 +" TEXT,"+COL3+" REAL)");
db.execSQL("CREATE TABLE " + TABLE_NAME_Normal + " (ID INTEGER PRIMARY KEY, " +
COL2 +" TEXT,"+COL3+" REAL)");
db.execSQL("CREATE TABLE " + TABLE_NAME_Hard + " (ID INTEGER PRIMARY KEY, " +
COL2 +" TEXT,"+COL3+" REAL)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME_Easy);
onCreate(db);
}
public boolean addData(String tableName,PlayerDetails playerDetails) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2,playerDetails.getWinnerName());
contentValues.put(COL3, playerDetails.getRatio());
long result = db.insert(tableName, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
public class GameOver extends AppCompatActivity {
public void addData(String tableName,PlayerDetails playerDetails)
{
mDatabasehelper=new DatabaseHelper(this,tableName);
boolean insertData=mDatabasehelper.addData(tableName,playerDetails);
if(insertData)
{
Toast.makeText(this, "Data Successfully added", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Something Went Wrong ", Toast.LENGTH_SHORT).show();
}
}
}
答案 0 :(得分:1)
您正在尝试第二次创建相同的表(_Hard)。似乎您要创建_Easy。以下更改是我想要的:-
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME_Easy + " (ID INTEGER PRIMARY KEY, " +
COL2 +" TEXT,"+COL3+" REAL)");
db.execSQL("CREATE TABLE " + TABLE_NAME_Normal + " (ID INTEGER PRIMARY KEY, " +
COL2 +" TEXT,"+COL3+" REAL)");
db.execSQL("CREATE TABLE " + TABLE_NAME_Hard + " (ID INTEGER PRIMARY KEY, " +
COL2 +" TEXT,"+COL3+" REAL)");
}
请注意,进行更改后,您需要执行以下操作之一才能重新运行该应用程序:-
卸载应用程序。
P.S。具有难度指标(轻松,正常,困难),因此使用一个表而不是三个表会更简单/更好(因此,您可以更容易地说出选择所有简单选项,例如SELECT * FROM the_one_table WHERE difficulty = 'normal' OR difficulty = 'hard'
)