Non-Activity Class Storing Data in the Database Using the DBAdapter Class

advertisements
  1. I want to be able to store The Tournament Data in the Database
  2. I will be using a non Activity class in calling my DBAdapter for storing data (NO idea how)
  3. I Am using MVC in this implementation wherein my Controller is extended to Activity
  4. How am i able to use my TournamentModel Class to store the inputed data into my database NOTE it isn't extended to Activity.
  5. I Didn't SHOW the creation of the other tables anymore due to character limitations.

&&

     /* ------------------------------------ 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


DBHandler.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import vn.mve.def.Def;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

@SuppressLint("SdCardPath")
public class DBHandler extends SQLiteOpenHelper {
    private static final String TAG = DBHandler.class.getSimpleName();
    protected SQLiteDatabase db;
    private final Context context;
    private static String PACKAGE_NAME = "";
    private static int DATABASE_VERSION = 1;

    public DBHandler(Context context) {
        super(context, Def.DBNAME, null, DATABASE_VERSION);
        this.context = context;
        PACKAGE_NAME = this.context.getPackageName();
        Def.FOLDER_DB = "/data/data/" + PACKAGE_NAME + "/databases/";
        Log.d(TAG, Def.FOLDER_DB);
        try {
            this.createDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            this.createDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        context.deleteDatabase(Def.DBNAME);
        onCreate(db);
    }

    public void createDataBase() throws IOException{
        // for first database;
        boolean dbExist = checkDataBase();
        if(!dbExist){
            try {
                copyDataBase("db/" + Def.DBNAME);
            } catch (Exception e) {
                Log.e(TAG, "createDatabse -> Copy failed!");
                throw new Error("Error copying database");
            }
        } else {
            open();
            boolean isExist = false;
            Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = 'config'", null);
            if (cursor != null) {
                isExist = true;
                cursor.close();
            } else {
                isExist = false;
            }
            close();
            Log.d(TAG, isExist + "");
            if (!isExist) {
                this.context.deleteDatabase(Def.DBNAME);
                try {
                    Log.d(TAG, "createDatabase when database has existed");
                    copyDataBase(Def.DBNAME);
                } catch (Exception e) {
                    Log.e(TAG, "createDatabse -> Copy failed!");
                    throw new Error("Error copying database");
                }
            }
        }
    }
    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase(String DB) {
        //Open your local db as the input stream
        InputStream myInput = null;
        //Open the empty db as the output stream
        OutputStream myOutput = null;
        try {
            myInput = context.getResources().getAssets().open(DB);

            // Path to the just created empty db
            String outFileName = Def.FOLDER_DB + Def.DBNAME;
            myOutput = new FileOutputStream(outFileName);

            //transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0){
                myOutput.write(buffer, 0, length);
            }
        } catch (FileNotFoundException e) {
            Log.e(TAG, "copyDatabase -> File not found.");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e(TAG, "copyDatabase");
        } finally {
              //Close the streams
            try {
                myOutput.flush();
                myOutput.close();
                myInput.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private boolean checkDataBase(){
        boolean checkDB = false;
        try{
            String myPath = Def.FOLDER_DB + Def.DBNAME;
            File dbFile = new File(myPath);
            checkDB = dbFile.isFile();
            Log.d(TAG, "checkDatabase: " + String.valueOf(checkDB));
            try {
                File fTmp = new File(Def.FOLDER_DB);
                if (!fTmp.exists()) {
                    fTmp.mkdir();
                }
            } catch (Exception e) {
                Log.e(TAG, "checkDatabase" + e.getMessage());
            }
        }catch(SQLiteException e){}
        return checkDB;
    }
    public void open() {
        try {
            String myPath = Def.FOLDER_DB + Def.DBNAME;
            db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public synchronized void close() {
            if(db != null)
                db.close();
            super.close();
    }
    public SQLiteDatabase getSqlDb() {
        return db;
    }
    public void setSqlDb(SQLiteDatabase sqlDb) {
        this.db = sqlDb;
    }
}

[OPTIONAL]

DBHelper.java

import java.util.List;

public interface DBHelper<T> {
    boolean insert(T val);
    boolean update(T val);
    boolean delete(T val);
    List<T> getList(int type);
    T getChild(Object val);
}

public class MVideo extends DBHandler implements DBHelper<Video> {
    public static final String TAG = MVideo.class.getSimpleName();
    public MVideo(Context context) {
        super(context);
    }

    @Override
    public boolean insert(Video val) {
        open();
        ContentValues cValues = new ContentValues();
        cValues.put(Def.Video.ID, val.getId());
        cValues.put(Def.Video.TITLE, val.getTitle());
        cValues.put(Def.Video.THUMBNAIL, val.getThumbnail());
        cValues.put(Def.Video.DESCRIPTION, val.getDescription());
        cValues.put(Def.Video.ENGLISH, val.getEnglish());
        cValues.put(Def.Video.VIETNAMESE, val.getVietnamese());
        cValues.put(Def.Video.ISVIEW, val.getIsView());
        long result = db.insert(Def.Video.NAME, null, cValues);
        close();
        return result > 0;
    }

    public boolean insertList(List<Video> list) {
        open();
        db.execSQL("BEGIN IMMEDIATE TRANSACTION");
        for (Video v : list) {
            db.execSQL(String.format("INSERT INTO " + Def.Video.NAME + " (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\") VALUES" +
                    " (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")",
                    Def.Video.ID, Def.Video.TITLE, Def.Video.THUMBNAIL, Def.Video.DESCRIPTION,
                    Def.Video.ENGLISH, Def.Video.VIETNAMESE, Def.Video.ISVIEW,
                    v.getId(), v.getTitle(), v.getThumbnail(), v.getDescription(), v.getEnglish(), v.getVietnamese(), v.getIsView() + ""));
            Log.d(TAG, "insertList -> " + v.toString());
        }
        db.execSQL("COMMIT TRANSACTION");
        close();
        return true;
    }

    @Override
    public boolean update(Video val) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean delete(Video val) {
        open();
        db.delete(Def.Video.NAME, Def.Video.ID + "=?", new String[]{val.getId()});
        close();
        return false;
    }

    @Override
    public List<Video> getList(int type) {
        List<Video> list = new ArrayList<Video>();
        open();
        Cursor c = db.rawQuery(Def.Video.GET_ALL, null);
        if (c.moveToFirst()) {
            while (c.moveToNext()) {
                String ID = c.getString(0);
                String title = c.getString(1);
                String thumbnail = c.getString(2);
                String description = c.getString(3);
                String english = c.getString(4);
                String vietnamese = c.getString(5);
                boolean isView = Boolean.parseBoolean(c.getString(6));
                list.add(new Video(ID, title, thumbnail, description, english, vietnamese, isView));
            }
        }
        close();
        return list;
    }

    @Override
    public Video getChild(Object val) {
        open();
        Cursor c = db.query(Def.Video.NAME, new String[]{
                Def.Video.ID, Def.Video.TITLE, Def.Video.THUMBNAIL, Def.Video.DESCRIPTION,
                Def.Video.ENGLISH, Def.Video.VIETNAMESE, Def.Video.ISVIEW
        }, Def.Video.ID + "=?", new String[]{val.toString()}, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        Video v = new Video(c.getString(0), c.getString(1),
                c.getString(2), c.getString(3), c.getString(4),
                c.getString(5), Boolean.parseBoolean(c.getString(6)));
        close();
        return v;
    } 

}