GCM message error in saving in database - java

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.

Related

Creating SQLite database for Live magnetic sensor data

I am new in Android platform. I want to record the live magnetic sensor data directly to sQLite database in storage. I wrote code to get magnetic data but i am not able to create the database. I have pasted code below. Any help would be great.
Thank you in advance.
// code for Database Helper
public class DBHelper extends SQLiteOpenHelper{
private static final String DB_NAME = "Mag_Positioning.db";
private static final int DB_VERSION = 1;
private static final String COL_ID = "ID";
private static final String COL_XAXIS = "X-AXIS";
private static final String TABLE_NAME = "MAP_COORDINATES";
private static final String COL_YAXIS = "Y-AXIS";
private static final String COL_ZAXIS = "Z-AXIS";
public DBHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_XAXIS + " INTEGER," + COL_YAXIS + " INTEGER," + COL_ZAXIS + " INTEGER" + " )";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void insert(Integer xaxis, Integer yaxis, Integer zaxis){
SQLiteDatabase db = this.getWritableDatabase();
}
}
// code for getting magnetic sensor data
// Its just fragment of code
public class MainActivity extends AppCompatActivity implements SensorEventListener {
Sensor magnetometer;
SensorManager sm;
TextView magnetismx;
TextView magnetismy;
TextView magnetismz;
DBHelper dbHelper;
public float a;
public float b;
public float c;
boolean recording = false;
boolean stoprecord = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DBHelper(this);
// I have declared some button here...
#Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
a = event.values[0];
b = event.values[1];
c = event.values[2];
if (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magnetismx.setText(Float.toString(event.values[0]));
magnetismy.setText(Float.toString(event.values[1]));
magnetismz.setText(Float.toString(event.values[2]));
if (!recording) {
return;
}
if(stoprecord){
return;
}
}
try {
writeToCsv(Float.toString(a), Float.toString(b), Float.toString(c));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ps: The code for database is not working too.. The table is not created.
I sorted out the problem myself. There was some problem in database class. I have used the below code for database helper class.
ublic class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "Mag_Positioning.db";
private static final int DB_VERSION = 1;
//Table for measurement
private static final String ID = "id";
private static final String MAP_ID = "Mapid";
private static final String COLXAXIS = "X_AXIS";
private static final String TABLENAME = "Fingerprint";
private static final String COLYAXIS = "Y_AXIS";
private static final String COLZAXIS = "Z_AXIS";
private static final String MAPX = "X_CORD";
private static final String MAPY = "Y_CORD";
private static final String DIFF = "Diff";
private static final String FINAL = "FINAL";
private static final String KEY_FINGERPRINT_ID = "id";
private static final String KEY_MAP_NAME = "map_name";
private static final String KEY_POSITION_X = "position_x";
private static final String KEY_POSITION_Y = "position_y";
private static DBHelper mInstance;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
public static DBHelper getInstance() {
if (mInstance == null) {
synchronized (DBHelper.class) {
if (mInstance == null) {
mInstance = new DBHelper(BaseApp.getApp());
}
}
}
return mInstance;
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLENAME + "("
+ ID + " INTEGER PRIMARY KEY,"
+ MAP_ID + " INTEGER ," +
MAPX + " INTEGER, " +
MAPY + " INTEGER, " +
COLXAXIS + " REAL, " +
COLYAXIS + " REAL, " +
COLZAXIS + " REAL, " +
FINAL + " REAL )";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLENAME);
onCreate(db);
}
public void insert(int a, int b, int c, float x, float y, float z, float d) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentvalues = new ContentValues();
contentvalues.put("Mapid", a);
contentvalues.put("X_CORD", b);
contentvalues.put("Y_CORD", c);
contentvalues.put("X_AXIS", x);
contentvalues.put("Y_AXIS", y);
contentvalues.put("Z_AXIS", z);
contentvalues.put("FINAL", d);
db.insert("Fingerprint", null, contentvalues);
db.close();
}
public void deleteAllFingerprints() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLENAME, null, null); // delete all fingerprints
db.close();
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cur = db.rawQuery("select * from " + TABLENAME, null);
return cur;
}
}

Why does the program crash when I rename field DB_NAME or DB_TABLE?

Help, please!
public class DB {
private static final String DB_NAME = "mydb";
private static final int DB_VERSION = 1;
private static final String DB_TABLE = "mytab";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_IMG = "img";
public static final String COLUMN_TXT = "txt";
private static final String DB_CREATE =
"create table " + DB_TABLE + "(" +
COLUMN_ID + " integer primary key autoincrement, " +
COLUMN_IMG + " integer, " +
COLUMN_TXT + " text" +
");";
private final Context mCtx;
private DBHelper mDBHelper;
private SQLiteDatabase mDB;
public DB(Context ctx) {
mCtx = ctx;
}
// открыть подключение
public void open() {
mDBHelper = new DBHelper(mCtx, DB_NAME, null, DB_VERSION);
mDB = mDBHelper.getWritableDatabase();
}
// закрыть подключение
public void close() {
if (mDBHelper!=null) mDBHelper.close();
}
// получить все данные из таблицы DB_TABLE
public Cursor getAllData() {
return mDB.query(DB_TABLE, null, null, null, null, null, null);
}
// добавить запись в DB_TABLE
public void addRec(String txt, int img) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_TXT, txt);
cv.put(COLUMN_IMG, img);
mDB.insert(DB_TABLE, null, cv);
}
// класс по созданию и управлению БД
private class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
// создаем и заполняем БД
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATE);
ContentValues cv = new ContentValues();
for (int i = 1; i < 5; i++) {
cv.put(COLUMN_TXT, "sometext " + i);
cv.put(COLUMN_IMG, R.drawable.ic_launcher);
db.insert(DB_TABLE, null, cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
So the mistake comes if I rename field DB_NAME or DB_TABLE when intializing. If I do not touch the names - everything is ok, but I need to change them. Tried to change the emulator - didn't help.
You will have to upgrade the version of your database, so increment one on it, and if you want to save the previous informations of your database, implement it inside your onUpgrade:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//implement your logic of saving your infos here
}
If you don't mind on cleanning up your database, just do like that:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS '" + DATABASE_TABLE+"'");
onCreate(db);
}

SQLite database works on emulator but not on device

I am using sqlite database in my android application. I am pre-creating the database in the databases folder in android. The databases is created and works fine in the emulator but when I run the same code in my phone I get errors.
Here is the code on how I pre-create the database in the databases folder.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SavingData.mainActivity = this;
try {
String destPath = "/data/data/" + getPackageName() + "/databases";
File f = new File(destPath);
if (!f.exists()) {
f.mkdirs();
f.createNewFile();
// ---copy the db from the assets folder into
// the databases folder---
CopyDB(getBaseContext().getAssets().open("exercisedatedb"),
new FileOutputStream(destPath + "/ExerciseDateDB"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
// ---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
Here is the errors I get:
04-01 12:51:12.503: E/SQLiteLog(26823): (1) no such column: date
04-01 12:51:12.503: D/AndroidRuntime(26823): Shutting down VM
04-01 12:51:12.503: W/dalvikvm(26823): threadid=1: thread exiting with uncaught exception (group=0x40f722a0)
04-01 12:51:12.508: E/AndroidRuntime(26823): FATAL EXCEPTION: main
04-01 12:51:12.508: E/AndroidRuntime(26823): android.database.sqlite.SQLiteException: no such column: date (code 1): , while compiling: SELECT id, date FROM dates
04-01 12:51:12.508: E/AndroidRuntime(26823): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
04-01 12:51:12.508: E/AndroidRuntime(26823): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1013)
04-01 12:51:12.508: E/AndroidRuntime(26823): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:624)
Here is how I insert data to database:
public void insertDate(String date) {
// TODO Auto-generated method stub
db.open();
long id = db.insertDate(date);
db.close();
}
Here is my DBAdapter class:
public class DBAdapter {
static final String KEY_ROWID = "id";
static final String KEY_DATE = "date";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "ExerciseDateDB";
static final String DATABASE_TABLE = "dates";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE = "create table dates (id integer primary key autoincrement, "
+ "date text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#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 contacts");
onCreate(db);
}
}
// ---opens the database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close() {
DBHelper.close();
}
// ---insert a Date into the database---
public long insertDate(String date) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DATE, date);
return db.insert(DATABASE_TABLE, null, initialValues);
}
// ---deletes a particular date---
public boolean deleteDate(long rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
// ---retrieves all the score---
public Cursor getAllDate() {
return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_DATE}, null, null, null, null, null);
}
// ---retrieves a particular score---
public Cursor getDate(long rowId) throws SQLException {
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_DATE}, KEY_ROWID + "= " + rowId + "",
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
// ---updates a score---
public boolean updateDate(long rowId, String date) {
ContentValues args = new ContentValues();
args.put(KEY_DATE, date);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
This is my database solution. It is all contained in one class.
Too call it the syntax is...
DatabaseManager mDatabase = DatabaseManager.getInstance();
public class DatabaseManager {
private static DatabaseManager instance;
private final String DB_NAME = "singoff_database";
private final int DB_VERSION = 1;
private final String GAME_TABLE_NAME = "game_table";
private final String GAME_ID = "gameid";
private final String GAME_OPPONENT_ID = "opponent";
private final String GAME_TRACK = "track";
private final String GAME_FILE_PATH = "filepath";
private final String GAME_PICTURE = "picture";
private final String GAME_GUESSES = "guesses";
private final String GAME_DATE = "date";
private SQLiteDatabase mDb;
private Context context;
private DatabaseManager(Context context) {
this.context = context;
//create new or open database
DatabaseHelper helper = new DatabaseHelper(context);
this.mDb = helper.getWritableDatabase();
}
public synchronized static DatabaseManager getInstance() {
if (instance == null) {
Context context = Main.getInstance();
instance = new DatabaseManager(context);
}
return instance;
}
//__________________________________________________________________________________________//
//GAME LIST HANDLING STATEMENTS
public synchronized void addGame(String gID, String oID, String track,
String path, byte[] thumb, String datetime) {
ContentValues values = new ContentValues();
values.put(GAME_ID, gID);
values.put(GAME_OPPONENT_ID, oID);
values.put(GAME_TRACK, track);
values.put(GAME_FILE_PATH, path);
values.put(GAME_PICTURE, thumb);
values.put(GAME_DATE, datetime);
mDb.insert(GAME_TABLE_NAME, null, values);
}
public synchronized List<File> getGames() {
List<File> games = new ArrayList<File>();
Cursor cursor;
cursor = mDb.query(
GAME_TABLE_NAME,
new String[]{GAME_FILE_PATH},
null, null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
File file = new File(cursor.getString(0));
games.add(file);
} while (cursor.moveToNext());
}
cursor.close();
return games;
}
public synchronized Game getGame(String filepath) {
Cursor cursor;
//Game game = null;
Bitmap picture = null;
byte[] blob;
cursor = mDb.query(
GAME_TABLE_NAME,
new String[]{
GAME_OPPONENT_ID,
GAME_FILE_PATH,
GAME_PICTURE,
GAME_DATE},
GAME_FILE_PATH + "=?",
new String[]{filepath},
null, null, null);
if (cursor.moveToNext()) {
blob = cursor.getBlob(2);
if (blob != null) {
picture = BitmapFactory.decodeByteArray(blob, 0, blob.length);
}
//game = new Game(mContext, new File(filepath), cursor.getString(0), picture);
}
return null;
}
public void updateGame(String filepath, gameColumn col,
Object object) {
ContentValues values = new ContentValues();
switch (col) {
case GAME_PICTURE:
Bitmap picture = (Bitmap) object;
ByteArrayOutputStream out = new ByteArrayOutputStream();
picture.compress(Bitmap.CompressFormat.PNG, 100, out);
values.put(GAME_PICTURE, out.toByteArray());
break;
default:
return;
}
mDb.update(GAME_TABLE_NAME, values, GAME_FILE_PATH + "=?", new String[]{filepath});
}
public synchronized void removeGame(String filepath) {
mDb.delete(GAME_TABLE_NAME, GAME_FILE_PATH + "=?", new String[]{filepath});
}
public enum gameColumn {
GAME_TABLE_NAME, GAME_OPPONENT_ID, GAME_FILE_PATH,
GAME_PICTURE, GAME_DATE
}
//__________________________________________________________________________________________//
//--------------------------------------------------------------------------------------------------
private class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createGameTableQuery = " CREATE TABLE IF NOT EXISTS "
+ GAME_TABLE_NAME + " ("
+ GAME_ID + " INTEGER, "
+ GAME_OPPONENT_ID + " VARCHAR(20), "
+ GAME_TRACK + " VARCHAR(30), "
+ GAME_FILE_PATH + " VARCHAR(50), "
+ GAME_PICTURE + " BLOB, "
+ GAME_GUESSES + " VARCHAR, "
+ GAME_DATE + " VARCHAR(50)"
+ ");";
//create game table
db.execSQL(createGameTableQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//TODO
}
}
}
Create a Database Object :
public class Database extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Exampe.db";
private static final int DATABASE_VERSION = 1;
public static final String ID = "_id";
public static final String NAME = "name";
public static final String UUID = "uuid";
public static final String TABLE_NAME = "Example Something";
private static final String DATABASE_CREATE = "create table "
+ TABLE_NAME + "( " + ID
+ " integer primary key autoincrement, " + NAME
+ " text not null, " + UUID
+ " text not null);";
public Database(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(Database.class.getName(), "Upgrading database from version " + oldVersion + "to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
}
Now where you call it
private SQLiteDatabase database;
private Database dbHelper;
private String[] allColumns = { Database.ID, Database.NAME};
public String ExampleSaveName(String name) {
database = dbHelper.getReadableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("uuid", uuid);
long insertId = database.insert(Database.TABLE_NAME, null, values);
Cursor cursor = database.query(Database.TABLE_NAME, allColumns, Database.ID + " = " + insertId, null,null, null, null);
cursor.moveToFirst();
return cursorToName(cursor);
}
}
The problem was solved by uninstalling the application from my device.

Adding data into SQLite database from another class in android

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));
}

DatabaseHelper class, onCreate() not called

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.

Categories