- 我希望能够将锦标赛数据存储在数据库中
- 我将使用非 Activity 类调用我的 DBAdapter 来存储数据(不知道如何)
- 我在这个实现中使用 MVC,其中我的控制器被扩展到 Activity
- 我如何使用我的 TournamentModel 类将输入的数据存储到我的数据库中注意它没有扩展到 Activity。
- 由于字符限制,我不再显示其他表的创建。
&&
/* ------------------------------------ DBADapter.java ---------------------------------------------*/
THIS IS MY DBAdapter <<<<<<<<<<
// TODO: Change the package to match your project.
package com.example.beachvolley;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
/////////////////////////// DB NAME UPDATE TABLE //////////////////////////////////
public static final String DATABASE_NAME = "MyDb"; //
private static final String TAG = "DBAdapter"; //
private final Context context; //
private DatabaseHelper myDBHelper; //
private SQLiteDatabase db; //
public static final int DATABASE_
VERSION = 21; //
///////////////////////////////////////////////////////////////////////////////////
/////////////////////////THIS IS THE TOURNAMENT TABLE/////////////////////////////////////
// DB Fields
public static final String TOURNAMENT_TABLE = "Tournament";
public static final String KEY_TOURNAMENT_ID = "IdTournament";
public static final int COL__TOURNAMENT_ID = 0;
public static final String KEY_NAME_TOURNAMENT = "TournamentName";
public static final int COL_NAME_TOURNAMENT = 1;
public static final String KEY_YEAR_TOURNAMENT = "Year";
public static final int COL_YEAR_TOURNAMENT = 2;
public static final String KEY_MYTEAM_TOURNAMENT = "MyTeam";
public static final int COL_MYTEAM_TOURNAMENT = 2;
public static final String[] ALL_TOURNAMENT_KEYS = new String[] {
KEY_TOURNAMENT_ID, KEY_NAME_TOURNAMENT, KEY_YEAR_TOURNAMENT, KEY_MYTEAM_TOURNAMENT};
private static final String TOURNAMEN_TABLE_CREATE_SQL =
"create table " + TOURNAMENT_TABLE
+ " (" + KEY_TOURNAMENT_ID + " integer primary key autoincrement, "
+ KEY_NAME_TOURNAMENT + " string not null, "
+ KEY_YEAR_TOURNAMENT + " string not null, "
+ KEY_MYTEAM_TOURNAMENT + " string not null "
+ ");";
public Cursor getAllTournamentRows() {
String where = null;
Cursor c = db.query(true, TOURNAMENT_TABLE, ALL_TOURNAMENT_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public long insertTournamentRow(String nameTournament, String yearTournament, String teamTournament) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME_TOURNAMENT, nameTournament);
initialValues.put(KEY_YEAR_TOURNAMENT, yearTournament);
initialValues.put(KEY_MYTEAM_TOURNAMENT, teamTournament);
return db.insert(TOURNAMENT_TABLE, null, initialValues);
}
public Cursor geTournamenttRow(long rowId) {
String where = KEY_TOURNAMENT_ID + "=" + rowId;
Cursor c = db.query(true, TOURNAMENT_TABLE, ALL_TOURNAMENT_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateTournamentRow(long rowId, String nameTournament) {
String where = KEY_TOURNAMENT_ID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME_TOURNAMENT, nameTournament);
// Insert it into the database.
return db.update(TOURNAMENT_TABLE, newValues, where, null) != 0;
}
///////////////////////////////////////TOURNAMENT TABLE///////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////GAME TABLE///////////////////////////////////////////////////////////////////////
public static final String GAME_TABLE = "Game";
public static final String KEY_GAME_ID = "idGame";
public static final int COL_GAME_ID = 0;
public static final String KEY_OPPONENT_NAME = "OpponentName";
public static final int COL_OPONENT_NAME = 1;
public static final String KEY_OPPONENT_SCORE = "OpponentScore";
public static final int COL_OPONENT_SCORE = 2;
public static final String KEY_TEAM_SCORE = "TeamScore";
public static final int COL_TEAM_SCORE = 3;
public static final String KEY_GAME_DATE = "Date";
public static final int COL_GAME_DATE = 3;
public static final String KEY_GAME_FK_TOURNAMENT_ID = "FKgameTournament";
public static final int COL_GAME_FK_TOURNAMENT_ID = 4;
public static final String[] ALL_GAME_KEYS = new String[] {KEY_GAME_ID, KEY_OPPONENT_NAME, KEY_OPPONENT_SCORE, KEY_TEAM_SCORE,KEY_GAME_DATE, KEY_GAME_FK_TOURNAMENT_ID };
private static final String GAME_TABLE_CREATE_SQL =
"create table " + GAME_TABLE
+ " ("
+ KEY_GAME_ID + " integer primary key autoincrement, "
+ KEY_OPPONENT_NAME + " string not null, "
+ KEY_OPPONENT_SCORE + " int not null, "
+ KEY_TEAM_SCORE + " int not null, "
+ KEY_GAME_DATE + " string not null, "
+ KEY_GAME_FK_TOURNAMENT_ID+" INTEGER REFERENCES " + KEY_TOURNAMENT_ID
+ ");";
///////////////// NOT YET DONE/////////////////////////
public static String GET_ALL_GAMES_SQL_IN_TOURNAMENT = "SELECT * FROM Game INNER JOIN Tournament ON idTournament = FKtournament WHERE FKtournament = ?";
/*
public static String GET_ONE_GAME_SQL_IN_TOURNAMENT = "SELECT * FROM Game INNER JOIN Tournament ON idTournament = FKtournament WHERE FKtournament = ? AND idGame = ?";
public static String GET_MYTEAM_GAME_SQL_IN_TOURNAMENT = "SELECT teamTournament FROM Game INNER JOIN Tournament ON idTournament = FKtournament WHERE FKtournament = ? AND idGame = ?";
*/
public long insertGAMERow(String opponentName, int OpponentScore, String teamScore, String dateGame, int keyGameTournament ) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_OPPONENT_NAME, opponentName);
initialValues.put(KEY_OPPONENT_SCORE, OpponentScore);
initialValues.put(KEY_TEAM_SCORE, teamScore);
initialValues.put(KEY_GAME_DATE, dateGame);
initialValues.put(KEY_GAME_FK_TOURNAMENT_ID, keyGameTournament);
return db.insert(GAME_TABLE, null, initialValues);
}
////////////////////////////////////GAME TABLE///////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(TOURNAMEN_TABLE_CREATE_SQL);
_db.execSQL(GAME_TABLE_CREATE_SQL);
_db.execSQL(PLAYER_TABLE_CREATE_SQL);
_db.execSQL(PLAYER_SET_CREATE_SQL);
_db.execSQL(PLAYER_MOVE_CREATE_SQL);
_db.execSQL(TOURNAMENT_PLAYER_CREATE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + TOURNAMENT_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + GAME_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + PLAYER_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + SET_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + MOVE_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + TOURNAMENT_PLAYER_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
&&
THIS IS WHERE MY CONTROLLER GOES IT BASICALLY GETS THE DATA FROM the XML VIEW layout
package com.example.beachvolley;
import java.util.Observable;
import java.util.Observer;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class TournamentController extends Activity implements Observer {
EditText tournamentName;
EditText year;
EditText team , p1Number , p2Number, p3Number;
Button SaveTournament;
TextView errorTN, errorYR, errorTM, errorPlayer,FNplayer1, LNplayer1, FNplayer2, LNplayer2, FNplayer3, LNplayer3;
TournamentModel Model = new TournamentModel();
boolean correctInputs = false;
private boolean checkTN, checkYN, checkPNandPnum, checkTM;
//final Context context = this;
DBAdapter myDb;
int countOfTournament;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tournament_view);
openDB();
tournamentName = (EditText) findViewById(R.id.teamNameTextBox);
year = (EditText) findViewById(R.id.yearTextbox);
team = (EditText) findViewById(R.id.teamInput);
FNplayer1 = (EditText) findViewById(R.id.player1FirstName);
LNplayer1 = (EditText) findViewById(R.id.player1LastName);
FNplayer2 = (EditText) findViewById(R.id.player2FirstName);
LNplayer2 = (EditText) findViewById(R.id.player2LastName);
FNplayer3 = (EditText) findViewById(R.id.player3FirstName);
LNplayer3 = (EditText) findViewById(R.id.player3LastName);
p1Number = (EditText) findViewById(R.id.p1Number);
p2Number = (EditText) findViewById(R.id.p2number);
p3Number = (EditText) findViewById(R.id.p3number);
errorTN = (TextView) findViewById(R.id.ErrorCheckTname);
errorYR = (TextView) findViewById(R.id.ErorCheckyeaer);
errorTM = (TextView) findViewById(R.id.ErrorNoTeam);
errorPlayer = (TextView) findViewById(R.id.errorPlayers);
SaveTournament = (Button) findViewById(R.id.saveTournament);
Model.addObserver(this);
SaveTournament.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
correctInputs = Model.CheckIfInvalid(
tournamentName.getText().toString(),
year.getText().toString(),
team.getText().toString(),
FNplayer1.getText().toString(),
LNplayer1.getText().toString(),
FNplayer2.getText().toString(),
LNplayer2.getText().toString(),
FNplayer3.getText().toString(),
LNplayer3.getText().toString(),
p1Number.getText().toString(),
p2Number.getText().toString(),
p3Number.getText().toString()
);
if(correctInputs)
Toast.makeText(getApplicationContext(), "Tournament Saved", Toast.LENGTH_SHORT).show();
/* <<<<<<hi this is where i send the data to my tournament Model if the inputs are valid >>>>>*/
Model.StoreInputsForTournament(correctInputs, tournamentName.getText().toString(), year.getText().toString(), team.getText().toString());
}
});
}
public void update(Observable observable, Object data) {
checkTN = Model.isToggeTname();
checkYN = Model.isToggeTyear();
checkTM = Model.isToggeTteam();
checkPNandPnum = Model.isToggePlayerNames();
if(checkTN){
errorTN.setVisibility(TextView.INVISIBLE);
Model.setTournamentName(team.getText().toString());
}
else {
errorTN.setTextColor(Color.RED);
errorTN.setVisibility(TextView.VISIBLE);
}
if(checkYN){
errorYR.setVisibility(TextView.INVISIBLE);
}
else {
errorYR.setTextColor(Color.RED);
errorYR.setVisibility(TextView.VISIBLE);
}
if(checkTM){
errorTM.setVisibility(TextView.INVISIBLE);
}
else {
errorTM.setTextColor(Color.RED);
errorTM.setVisibility(TextView.VISIBLE);
}
if(checkPNandPnum){
errorPlayer.setVisibility(TextView.INVISIBLE);
}
else{
errorPlayer.setTextColor(Color.RED);
errorPlayer.setVisibility(TextView.VISIBLE);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB() {
myDb.close();
}
}
&&
/*TOURNAMENTMODEL CLASS*/
import java.util.ArrayList;
import java.util.Observable;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.provider.OpenableColumns;
public class TournamentModel extends Observable { /*NOTE IT ONLY EXTENDS TO Observable NOT Activity so method Open() cannot be used */
public String TournamentName;
public String TournamentYear;
public String TeamRecorded;
public boolean ToggeTname = true;
public boolean ToggeTyear = true;
public boolean ToggeTteam= true;
public boolean ToggePlayerNames= true;
Player[] ListOfPlayers;
DBAdapter myDb = new DBAdapter(null); // THIS IS MY PROBLEM It's null
public boolean CheckIfInvalid(String TournamentName, String Year, String teamName, String FirstName1, String LastName1,String FirstName2, String LastName2, String FirstName3, String LastName3, String p1, String p2, String p3 ){
ToggeTname = true;
ToggeTyear = true;
ToggeTteam= true;
if(TournamentName.equals(""))
this.ToggeTname = false;
else
this.ToggeTname = true;
if(Year.equals(""))
this.ToggeTyear = false;
else
this.ToggeTyear = true;
if(teamName.equals(""))
this.ToggeTteam = false;
else
this.ToggeTteam = true;
if(FirstName1.equals("") || LastName1.equals("") || FirstName2.equals("") || LastName2.equals("")|| FirstName3.equals("") || LastName3.equals("") || p1.equals("")|| p2.equals("")|| p3.equals(""))
this.ToggePlayerNames = false;
else
this.ToggePlayerNames = true;
triggerObservers();
if(this.ToggeTname && this.ToggeTyear && this.ToggeTteam && this.ToggePlayerNames)
return true;
else
return false;
}
public void StoreInputsForTournament(boolean tog , String TournamentName, String Year, String teamName){
if(tog == true){
/*THIS IS WHERE I TRY TO INSERT TO THE DATABASE THE DATA GOTTEN FROM THE CONTROLER */
myDb.insertTournamentRow(TournamentName, Year, teamName);
}
}
private void triggerObservers() {
setChanged();
notifyObservers();
}
public boolean isToggeTname() {
return ToggeTname;
}
public void setToggeTname(boolean toggeTname) {
ToggeTname = toggeTname;
}
public boolean isToggeTyear() {
return ToggeTyear;
}
public void setToggeTyear(boolean toggeTyear) {
ToggeTyear = toggeTyear;
}
public boolean isToggeTteam() {
return ToggeTteam;
}
public void setToggeTteam(boolean toggeTteam) {
ToggeTteam = toggeTteam;
}
public boolean isToggePlayerNames() {
return ToggePlayerNames;
}
public void setToggePlayerNames(boolean toggePlayerNames) {
ToggePlayerNames = toggePlayerNames;
}
public String getTournamentYear() {
return TournamentYear;
}
public void setTournamentYear(String tournamentYear) {
TournamentYear = tournamentYear;
}
public String getTeamRecorded() {
return TeamRecorded;
}
public void setTeamRecorded(String teamRecorded) {
TeamRecorded = teamRecorded;
}
public String getTournamentName() {
return TournamentName;
}
public void setTournamentName(String tournamentName) {
this.TournamentName = tournamentName;
}
}
&&
/* LOG CAT ERROR NULL*/
08-18 17:32:42.939: D/AndroidRuntime(19690): Shutting down VM
08-18 17:32:42.939: W/dalvikvm(19690): threadid=1: thread exiting with uncaught exception (group=0x40015560)
08-18 17:32:42.948: E/AndroidRuntime(19690): FATAL EXCEPTION: main
08-18 17:32:42.948: E/AndroidRuntime(19690): java.lang.NullPointerException
08-18 17:32:42.948: E/AndroidRuntime(19690): at com.example.beachvolley.DBAdapter.insertTournamentRow(DBAdapter.java:69)
08-18 17:32:42.948: E/AndroidRuntime(19690): at com.example.beachvolley.TournamentModel.StoreInputsForTournament(TournamentModel.java:62)
08-18 17:32:42.948: E/AndroidRuntime(19690): at com.example.beachvolley.TournamentController$1.onClick(TournamentController.java:95)
08-18 17:32:42.948: E/AndroidRuntime(19690): at android.view.View.performClick(View.java:2485)
08-18 17:32:42.948: E/AndroidRuntime(19690): at android.view.View$PerformClick.run(View.java:9080)
08-18 17:32:42.948: E/AndroidRuntime(19690): at android.os.Handler.handleCallback(Handler.java:587)
08-18 17:32:42.948: E/AndroidRuntime(19690): at android.os.Handler.dispatchMessage(Handler.java:92)
08-18 17:32:42.948: E/AndroidRuntime(19690): at android.os.Looper.loop(Looper.java:123)
08-18 17:32:42.948: E/AndroidRuntime(19690): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-18 17:32:42.948: E/AndroidRuntime(19690): at java.lang.reflect.Method.invokeNative(Native Method)
08-18 17:32:42.948: E/AndroidRuntime(19690): at java.lang.reflect.Method.invoke(Method.java:507)
08-18 17:32:42.948: E/AndroidRuntime(19690): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-18 17:32:42.948: E/AndroidRuntime(19690): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-18 17:32:42.948: E/AndroidRuntime(19690): at dalvik.system.NativeStart.main(Native Method)
08-18 17:37:42.984: I/Process(19690): Sending signal. PID: 19690 SIG: 9