I am creating an instance of DBHelper Class in onCreate() of main activity.
databaseHelper = new DatabaseHelper(getBaseContext());
I am not getting when is onCreate() called. I tried giving Toast. As Soon as getWritableDatabase(); is called application force closes. Here is my code:
public class DatabaseHelper extends SQLiteOpenHelper
{
SQLiteDatabase db;
// Database Name
private static final String DATABASE_NAME = "manasi.db";
// database table name
private static final String TABLE_DATA = "data";
// Database table fields
private static final String KEY_IMEI = "imei";
private static final String KEY_LAT = "lat";
private static final String KEY_LONG = "long";
private static final String KEY_DATETIME = "datetime";
private static final String KEY_ALTITUDE = "altitude";
private static final String KEY_SPEED = "speed";
private static final String KEY_BATTERY = "battery";
Context context;
/**
* #param context Application Context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
// db = this.getWritableDatabase();
Toast.makeText(context, "db helper", Toast.LENGTH_LONG).show();
}
/* Called when the database is created for the first time.
* #see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
*/
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE DB_TABLE(_id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT);");
Toast.makeText(context, "db helper onCreate", Toast.LENGTH_LONG).show();
String CREATE_DATA_TABLE = "CREATE TABLE " + TABLE_DATA + "("
+ KEY_IMEI + " TEXT ," + KEY_LAT + " DOUBLE," + KEY_LONG
+ "DOUBLE," + KEY_DATETIME + "DATETIME," + KEY_ALTITUDE + "DOUBLE,"
+ KEY_SPEED + "TEXT," + KEY_BATTERY + "TEXT" + ")";
db.execSQL(CREATE_DATA_TABLE);
Context context = null;
}
/* Called when the database needs to be upgraded.
* #see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("DatabaseHelper", "Upgrading database, which will destroy all old data");
onCreate(db);
}
public void insertRecordToDB(Data data) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMEI, data.getImei());
values.put(KEY_LAT, data.getLatitude());
values.put(KEY_LONG, data.getLongitude());
values.put(KEY_DATETIME, data.getDateTime());
values.put(KEY_ALTITUDE, data.getAltitude());
values.put(KEY_SPEED, data.getSpeed());
values.put(KEY_BATTERY, data.getBattery());
// Inserting Row
db.insert(TABLE_DATA, null, values);
db.close(); // Closing database connection*/
}
}
Do this in your activity
databaseHelper = new DatabaseHelper(this);
SQLiteDatabase sb = databaseHelper.getWritableDatabase();//this line responsible to call onCreate()
and read this http://mobileapplications-by-himanshu.blogspot.in/
onCreate() call once.
Related
I am currently working on an android quiz application with the questions linking to the database, however, I was be able to create the database created but somehow the values such as list of questions won't be inserted manually. As I have opened the database, it has organized the columns I have wanted but no values will be display such as the 'example question' Have I been missing some line of code?
Many Thanks
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "Questions.db";
public static final String TABLE_NAME = "Questions";
public static final String QUESTION_NUMBER = "Question_Number";
public static final String QUESTION = "Question";
public static final String ANSWER_ONE = "Answer_ONE";
public static final String ANSWER_TWO = "Answer_THREE";
public static final String ANSWER_THREE = "Answer_FOUR";
private SQLiteDatabase db;
public DatabaseHelper(Context context)
{
super(context,DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db)
{
this.db = db;
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
TABLE_NAME + " ( " +
QUESTION_NUMBER + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
QUESTION + " TEXT, " +
ANSWER_ONE + " TEXT, " +
ANSWER_TWO + " TEXT, " +
ANSWER_THREE + " TEXT " +
")";
db.execSQL(SQL_CREATE_QUESTIONS_TABLE);
fillQuestionTable();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1)
{
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
private void fillQuestionTable()
{
Question q1 = new Question(1,"Example Question?","Yes","Sometimes","No");
addQuestion(q1);
}
private void addQuestion (Question question)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(QUESTION_NUMBER, question.getQuestionNum());
cv.put(QUESTION, question.getQuestion());
cv.put(ANSWER_ONE, question.getOption1());
cv.put(ANSWER_TWO, question.getOption2());
cv.put(ANSWER_THREE, question.getOption3());
db.insert(TABLE_NAME,null,cv);
}
}
This is the activity Class
public class MainActivity extends Activity implements View.OnClickListener
{
Button screenOneButton;
Button screenTwoButton;
Button screenThreeButton;
Button quitButton;
DatabaseHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHelper mydb = new DatabaseHelper(this);
}
This is programmed under Intellij software and was able to open the database under DB SQL software FYI!
Many thanks
This question already has answers here:
What is a stack trace, and how can I use it to debug my application errors?
(7 answers)
Closed 7 years ago.
I have two tables: user and balance.
User DAO:
public class NewUserDAO {
public static final String TAG = "NewUserDAO";
public static final String TABLE_NEWUSER = "newUser";
//database fields
private SQLiteDatabase mDataBase;
private DatabaseHandler mDbHelper;
private Context mContext;
private String [] mAllColumns = {
DatabaseHandler.COLUMN_NEWUSER_ID,
DatabaseHandler.COLUMN_NEWUSER_NAME, DatabaseHandler.COLUMN_NEW_USER_PASSWORD,
DatabaseHandler.COLUMN_NEW_USER_AGE };
public NewUserDAO(Context context){
this.mContext = context;
mDbHelper = new DatabaseHandler(context);
try{
open();
} catch (SQLException e){
Log.e(TAG,"SQLexception on opening database" + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException{
mDataBase = mDbHelper.getWritableDatabase();
}
public void close(){
mDbHelper.close();
}
public void createNewUser(NewUserTable newUserTable){
ContentValues values = new ContentValues();
values.put(DatabaseHandler.COLUMN_NEWUSER_NAME,newUserTable.getName());
values.put(DatabaseHandler.COLUMN_NEW_USER_PASSWORD, newUserTable.getPassword());
values.put(DatabaseHandler.COLUMN_NEW_USER_AGE, newUserTable.getAge());
mDataBase.insert(TABLE_NEWUSER, null, values);
mDataBase.close();
}
}
balance DAO:
public class BalanceDAO {
public static final String TAG = "BalanceDAO";
public static final String TABLE_BALANCE = "balanceOfUser";
private Context mContext;
//Database fields
private SQLiteDatabase mDatabase;
private DatabaseHandler mDhelper;
private String[] mAllColumns = {
DatabaseHandler.COLUMN_BALANCE_ID,
DatabaseHandler.COLUMN_BALANCE_DOLLARBALANCE,
DatabaseHandler.COLUMN_BALANCE_RUBBALANCE,
DatabaseHandler.COLUMN_BALANCE_NEW_USER_ID
};
public BalanceDAO (Context context){
mDhelper = new DatabaseHandler(context);
this.mContext = context;
try{
open();
}
catch (SQLException e){
Log.e(TAG, "SQLException on openning database" + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDhelper.getWritableDatabase();
}
public void close(){
mDhelper.close();
}
public void createBalance (BalanceTable balanceTable){
ContentValues values = new ContentValues();
values.put(DatabaseHandler.COLUMN_BALANCE_DOLLARBALANCE,balanceTable.getDollarBalance());
values.put(DatabaseHandler.COLUMN_BALANCE_RUBBALANCE,balanceTable.getRubBalance());
mDatabase.insert(TABLE_BALANCE, null, values);
mDatabase.close();
}
}
And SQLiteOpenHelper class:
public class DatabaseHandler extends SQLiteOpenHelper {
//COLUMNS OF THE NEW USER TABLE
public static final String TABLE_NEWUSER = "newUser";
public static final String COLUMN_NEWUSER_ID = "id";
public static final String COLUMN_NEWUSER_NAME = "name";
public static final String COLUMN_NEW_USER_PASSWORD = "password";
public static final String COLUMN_NEW_USER_AGE = "age";
//COLUMNS OF THE BALANCE TABLE
public static final String COLUMN_BALANCE_ID = "id";
public static final String TABLE_BALANCE = "balanceOfUser";
public static final String COLUMN_BALANCE_DOLLARBALANCE = "dollarBalance";
public static final String COLUMN_BALANCE_RUBBALANCE = "rubBalance";
public static final String COLUMN_BALANCE_NEW_USER_ID = "newUserId";
private static final String DATABASE_NAME = "webStore";
private static final int DATABASE_VERSION = 1;
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_NEWUSER = "CREATE TABLE " + TABLE_NEWUSER + "("
+ COLUMN_NEWUSER_ID + " INTEGER PRIMARY KEY autoincrement,"
+ COLUMN_NEWUSER_NAME + " TEXT not null,"
+ COLUMN_NEW_USER_PASSWORD + " TEXT not null,"
+ COLUMN_NEW_USER_AGE + " INTEGER"
+ ")";
db.execSQL(SQL_CREATE_NEWUSER);
String SQL_CREATE_BALANCE = "CREATE TABLE " + TABLE_BALANCE + "("
+ COLUMN_BALANCE_ID + " INTEGER PRIMARY KEY autoincrement,"
+ COLUMN_BALANCE_DOLLARBALANCE + " INTEGER,"
+ COLUMN_BALANCE_RUBBALANCE + " INTEGER,"
+ COLUMN_BALANCE_NEW_USER_ID + " INTEGER," + "FOREIGN KEY("+COLUMN_BALANCE_NEW_USER_ID+") REFERENCES "
+ TABLE_NEWUSER + "(id) "+ ")" ;
db.execSQL(SQL_CREATE_BALANCE);
onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWUSER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BALANCE);
}
}
I want to join user and balance tables. How can i do? When i call Create Method, i have exception.
public void CreateUser(View view) {
etName = (EditText)findViewById(R.id.etName);
etPassword = (EditText)findViewById(R.id.etPassword);
etAge = (EditText)findViewById(R.id.etAge);
String name = String.valueOf(etName.getText());
String password = String.valueOf(etPassword.getText());
int age = Integer.parseInt(String.valueOf(etAge.getText()));
BalanceTable balanceTable = new BalanceTable(0,0);
NewUserTable newUserTable = new NewUserTable(name,password,age);
//write to database of user from our edit texts
DatabaseHandler databaseHandler = new DatabaseHandler(this);
Log.d("Insert: ", "Inserting ..");
NewUserDAO dbForUser = new NewUserDAO(this);
dbForUser.createNewUser(newUserTable);
BalanceDAO balanceDAO = new BalanceDAO(this);
balanceDAO.createBalance(balanceTable);
}
From edit text i take data. Help please
There are a few types if join, inner (which I think is what you want) which shows the data that matches, left showing all data from the first table and any additional data from the second table that meets the on condition or right which is shows all from the second table and any form the right that matches.
to Join two table you must use a statement such as
"SELECT <all the values you want> "+
" FROM users" +
" left join balance" +
" ON users.id=balance.userid " +
" where <some condition> "+
" order by gmttimestamp ;"; "
this will give you result set of mixed tables
I am making a small app and therefore i need to use a small SQLite-database.
Please help me, i dont know how to fix this error:
At the line "SQLiteDatabase db = this.getReadableDatabase();" in the database
, (Main: int teams = db.countAllTeams())
Error: W/System.errīš Invalid int: ""
Database:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "database";
private static final String TABLE_TEAM = "team";
private static final String KEY_TEAM_FULLNAME = "full_name";
private static final String KEY_TEAM_SHORTNAME = "short_name";
private static final String KEY_TEAM_STADIUM = "stadium";
private static final String KEY_TEAM_LOGO = "logo";
private static final String CREATE_TABLE_TEAM = "CREATE TABLE "
+ TABLE_TEAM + "(" + KEY_TEAM_FULLNAME + " TEXT PRIMARY KEY," +
KEY_TEAM_SHORTNAME + " TEXT," +
KEY_TEAM_STADIUM + " TEXT," +
KEY_TEAM_LOGO + " INTEGER" + ")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_TEAM);
}
#Override
public void onUpgrade(SQLiteDatabase db, int old, int neW) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEAM);
onCreate(db);
}
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen()) db.close();
}
public long createTeam(Team team) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TEAM_FULLNAME, team.getFullName());
values.put(KEY_TEAM_SHORTNAME, team.getShortName());
values.put(KEY_TEAM_LOGO, team.getLogo());
values.put(KEY_TEAM_STADIUM, team.getStadium());
return db.insert(TABLE_TEAM, null, values);
}
public int countAllTeams(){
SQLiteDatabase db = this.getReadableDatabase();
List<Team> teams = new ArrayList<Team>();
return Integer.getInteger(db.compileStatement("SELECT COUNT(*) FROM " + TABLE_TEAM).simpleQueryForString());
}
}
Main
DatabaseHelper db;
TextView tvText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
tvText = (TextView)findViewById(R.id.tvText);
String text = "";
db = new DatabaseHelper(getApplicationContext());
int teams = db.countAllTeams();
tvText.setText(teams);
}
}
Integer.getInteger does not convert a string to an integer.
The easiest way to get a single number from a query is to use DatabaseUtils:
long count = DatabaseUtils.longForQuery(db,
"SELECT COUNT(*) FROM " + TABLE_TEAM, null);
But to get the number of rows in the table, there's an even simpler function:
long count = DatabaseUtils.queryNumEntries(db, TABLE_TEAM);
Furthermore, when you give an integer to TextView.setText, it expects a resource ID.
You have to convert your count into a string manually:
tvText.setText(Integer.toString(teams));
I'd use rawQuery() instead of simpleQueryForString():
public int countAllTeams(){
SQLiteDatabase db = this.getReadableDatabase();
List<Team> teams = new ArrayList<Team>();
Cursor c = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_TEAM, new String[]{});
c.moveToFirst();
return c.getInt(0);
}
.setText doesn't take in integers directly, instead try:
tvText.setText(String.valueOf(teams));
Integer value in TextView
Im trying to save the gcm message in database but everytime i send a message, the app closes.
Here is my GCMIntentService OnMessage method:
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("Memo");
displayMessage(context, message);
MemoDBAdapterHandler db = new MemoDBAdapterHandler(context);
db.saveMessage(message);
generateNotification(context, message);
}
Here is MemoDBAdapterHandler
public class MemoDBAdapterHandler {
public static final String KEY_BODY = "Body";
public static final String KEY_ROWID ="_id1";
private static final String TAG = "MemoDBAdapterHandler";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
/** CreateMemoDatabase **/
private static final String DATABASE_CREATE =
"create table memosTable1 (KEY_BODY integer primary key autoincrement, "
+ "Body string not null);";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "GCM2";
private static final String DATABASE_TABLE = "memosTable1";
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS memosTable");
onCreate(db);
}
}
public MemoDBAdapterHandler(Context ctx)
{
this.mCtx = ctx;
}
public MemoDBAdapterHandler open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long saveMessage(String msg)
{
//SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_BODY, msg);
//mDb.close();
return mDb.insert(DATABASE_TABLE, null, cv);
}
Update your code with below
private static final String DATABASE_CREATE =
"create table memosTable1 (KEY_ROWID integer primary key autoincrement, "
+ "Body string not null);";
You were giving same column name.
I am trying to add a simple int count which is set to count++ everytime a player wins it will increment by 1. I am trying to add this int count inside my SQLite Database. But I have no Idea how I can do that, the database is in one class, and my int value is in another class, How can I add the int inside the database. I have created a addScores method inside my class:
Database Code:
public class Database {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "number_of_wins";
private static final String DATABASE_NAME = "HIGHSCORES";
private static final String DATABASE_TABLE= "Total_Wins";
private static final int DATABASE_VERSION = 2;
private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " INTEGER);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Database(Context context) {
ourContext = context;
}
public Database open() {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public Cursor getScores() {
return ourDatabase.rawQuery("SELECT * FROM "+DATABASE_TABLE, null); //No Parameter
}
}
Someother Class:
int count =0;
count++;
//Adding HighScore to Database
public void addScore() {
}
How do I add the int count inside my database? I am trying to add it in the column number_of_wins?
You need to insert a value in the database using something like this.
ContentValues values = new ContentValues();
values.put("number_of_wins", counter);
id = ourDatabase.insertOrThrow("Total_Wins", null, values);
Create a method in your database class and add/modify this code, and finally call this new method from 'SomeOther' class.
This is a simple DBHelper that should work for you and get you started, create an instance of this and you should be able to add a score into your database, However I highly recommend you read the tutorial in comment, and really figure out how it works. So from here you should be able to complete all other CRUD operations.
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME= "HIGHSCORES";
private static final String DATABASE_TABLE = "TotalWins";
// The keys
private static final String KEY_ID = "id";
private static final String KEY_SCORE = "NumberOfWins";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY, " +
KEY_SCORE + " INTEGER);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Careful with this!
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public void addScore(int score) {
// Get a writable database handle
SQLiteDatabase db = getWritableDatabase();
// Put the coun into a ContentValues object, with correct key
ContentValues values = new ContentValues();
values.put(KEY_SCORE, score);
// Inserting Row
db.insert(DATABASE_TABLE, null, values);
// Closing database connection
db.close();
}
}
I assume you have the unique id for the particular count you'd like to increase. In that case, I'd write the following method inside of the Database class and call it when the count should increase.
public void addScore(long id) {
ourDatabase.execSQL(String.format("UPDATE %s SET %s=%s+1 WHERE %s=%d",
DATABASE_TABLE, KEY_NAME, KEY_NAME, KEY_ID, id));
}