android


Non Activity Class Storing Data in the Database using DBAdapter class


I want to be able to store The Tournament Data in the Database
I will be using a non Activity class in calling my DBAdapter for storing data (NO idea how)
I Am using MVC in this implementation wherein my Controller is extended to Activity
How am i able to use my TournamentModel Class to store the inputed data into my database NOTE it isn't extended to Activity.
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;
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter extends SQLiteOpenHelper {
public static final String KEY_NOTOFICATION_DATE_AND_TIME = "notification_date_and_time";
private static String DB_PATH = "";
private static final String DATABASE_NAME = "MindEditor";
private SQLiteDatabase myDataBase;
private final Context mContext;
private static DBAdapter mDBConnection;
public DBAdapter(Context context) {
super(context, DATABASE_NAME, null, 1);
this.mContext = context;
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
}
public static synchronized DBAdapter getDBAdapterInstance(Context context) {
if (mDBConnection == null) {
mDBConnection = new DBAdapter(context);
}
return mDBConnection;
}
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DATABASE_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException {
InputStream myInput = mContext.getAssets().open(DATABASE_NAME);
String outFileName = DB_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
#Override
public void onCreate(SQLiteDatabase myDataBase) {
}
#Override
public void onUpgrade(SQLiteDatabase myDataBase, int oldVersion,
int newVersion) {
}
public Cursor GetAllDataNotificationsDateAndTime() {
return myDataBase.query("tbl_notification_date_and_time",
new String[] { KEY_NOTOFICATION_DATE_AND_TIME }, null, null,
null, null, null);
}
public Cursor getRandomHi(String tbl_name) {
Cursor cursor = myDataBase.rawQuery("SELECT * FROM " + tbl_name
+ " ORDER BY RANDOM() LIMIT 1", null);
if (cursor.moveToFirst()) {
return cursor;
}
return cursor;
}
public Cursor getRandom(String tbl_name, String type) {
Cursor cursor = myDataBase.rawQuery("SELECT * FROM " + tbl_name
+ " where cycletype=" + "'" + type + "'"
+ " ORDER BY RANDOM() LIMIT 1", null);
if (cursor.moveToFirst()) {
return cursor;
}
return cursor;
}
public long InsertNotificationDateAndTime(String date) {
ContentValues initialValues = new ContentValues();
initialValues.put("notification_date_and_time", date);
return myDataBase.insert("tbl_notification_date_and_time", null,
initialValues);
}
public long InsetCyleDetails(String cyclename) {
ContentValues initialValues = new ContentValues();
initialValues.put("cyclename", cyclename);
return myDataBase.insert("mind_cycleid", null, initialValues);
}
public Cursor GetSingleData(String date) {
Cursor cursor = myDataBase
.rawQuery(
"SELECT * FROM tbl_notification_date_and_time where notification_date_and_time="
+ "'" + date + "'", null);
if (cursor.moveToFirst()) {
return cursor;
}
return cursor;
}
public void deleteOldNotificationData() {
myDataBase.delete("tbl_notification_date_and_time", null, null);
}
public long InsertNotificationSetDateAndTime(String date) {
ContentValues initialValues = new ContentValues();
initialValues.put("notification_set_date", date);
return myDataBase.insert("tbl_notification_set_day", null,
initialValues);
}
public Cursor GetNotificationStartDate(String date) {
Cursor cursor = myDataBase.rawQuery(
"SELECT * FROM tbl_notification_set_day where notification_set_date="
+ "'" + date + "'", null);
if (cursor.moveToFirst()) {
return cursor;
}
return cursor;
}
public Cursor GetCycleId() {
return myDataBase.query("mind_cycleid", new String[] { "cycleid",
"cyclename" }, null, null, null, null, null);
}
public long InsertDataGatheringPingForMajority(String date, String cycle,
String thought, String feeling, String days, String cycleid) {
ContentValues initialValues = new ContentValues();
initialValues.put("datestr", date);
initialValues.put("cycle", cycle);
initialValues.put("thought", thought);
initialValues.put("feelings", feeling);
initialValues.put("days", days);
initialValues.put("cycleid", cycleid);
return myDataBase.insert("mind_majority", null, initialValues);
}
public Cursor GetDataFromMindMajority(String id) {
Cursor cursor = myDataBase.rawQuery(
"SELECT * FROM mind_majority where cycleid=" + "'" + id + "'",
null);
if (cursor.moveToFirst()) {
return cursor;
}
return cursor;
}
public long InsertMindEditorDataForStats(String date, String cycle,
String thought, String feeling, String days, String cycleid,
String stateupdate, String iscompleted, String runningday,
String isuploaded, String NoofNotificationAnswered) {
ContentValues initialValues = new ContentValues();
initialValues.put("datestr", date);
initialValues.put("cycle", cycle);
initialValues.put("thought", thought);
initialValues.put("feelings", feeling);
initialValues.put("days", days);
initialValues.put("cycleid", cycleid);
initialValues.put("stateupdate", stateupdate);
initialValues.put("iscompleted", iscompleted);
initialValues.put("runningday", runningday);
initialValues.put("isuploaded", isuploaded);
initialValues.put("notification_answered", NoofNotificationAnswered);
return myDataBase.insert("mindeditor", null, initialValues);
}
public Cursor GetStatsData() {
return myDataBase.query("mindeditor", new String[] { "id", "datestr",
"cycle", "thought", "feelings", "days", "cycleid",
"stateupdate", "iscompleted", "runningday", "isuploaded",
"notification_answered" }, null, null, null, null, null);
}
public boolean updateMindEditorDataForStats(String cycleid, String notification_answered) {
ContentValues args = new ContentValues();
args.put("notification_answered", notification_answered);
return myDataBase.update("mindeditor", args, "cycleid" + "=" + cycleid, null) > 0;
}
}

Related Links

How to track Installs (Install Referrer) using Android firebase dynamic links?
AOSP Build - syscall ERROR
Android Remote View not picking up the correct layout based on the language
Application crashes on dialog dismiss
Can staggered manage view based on the content's width and scroll as vertical?
ListView not updating after elements added to bound ObservableCollection (Xamarin)
How to maintain multiple google-service.json in Android Studio
how to add a custom object into azure in android?
Android Copy Image From Gallery Into New File
FAB between layouts
Tracking app usage via service android studio
Android Studio Android Device Monitor can't access File Explorer
Setting percentage size on dynamically created fragments within a scrolling layout
Cordova: Error in adding android platform
Dynamiclly create Imgeviews
UTM tracking codes in Firebase

Categories

HOME
sonarqube
turing-machines
powerpoint
gradient
appcelerator
ms-access-2016
xbee
entity-framework-core
code-coverage
crystal-reports-2013
jax-ws
fabric.io
google-schemas
x-cart
frequency-distribution
eip
docx
package.json
android-7.0-nougat
oledb
kendo-mobile
cgbitmapcontext
postscript
scriptella
ckfinder
dapper-extensions
motion-detection
rpgle
vex
scrollview
volatile
mnist
processwire
navigator
z-notation
sim-card
comparison-operators
stringtokenizer
monkey-testing
ntvs
mongotemplate
reindex
excel-dna
avx
otp
gpg-signature
django-1.10
branch-prediction
centrifuge
envi
jquery-jscrollpane
android-wake-lock
lua-telegram-bot
findfirst
pushbots
np-spring
concept-insights
oracle-spatial
sapscript
mod-proxy
dbaccess
rickshaw
functional-java
high-resolution
notorm
breakout
modular
time.h
azman
predicatebuilder
cloudfiles
uideviceorientation
updatesourcetrigger
vs-android
openfaces
wcf-proxy
pnrp

Resources

Encrypt Message