Adding data into SQLite database from another class in android - java

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

Related

Adding a new column in SQLite Database

I am pretty new to Android development and I am trying to implement a database for my app.
I started with only having one column in the database (COLUMN_DATE) and then added another column (COLUMN_REPEAT). This worked fine and printed the results as expected. However, when I tried adding another column (COLUMN_ACCOUNT), printDatabase() in MainActivity did not print anything.
I understand you can view what is in your database by using Android Device Monitor, but I keep getting an error when I click on that so I cannot use it (That is a separate issue which I haven't been able to solve). Hence, I am unsure if it is just an issue with printing the database or if there is actually any data in the database at all.
Any help would be much appreciated
----MainActivity.java----
dbHandler = new DatabaseHandler(this, null, null, 1);
printDatabase();
//Print the database
public void printDatabase() {
String dbString = dbHandler.databaseToString();
recordsTextView.setText(dbString);
}
//Add an item to the database
public void addButtonClicked(View view){
Income date = new Income(dateView.getText().toString());
Income repeat = new Income(repeatSpinner.getSelectedItem().toString());
Income account = new Income(accountSpinner.getSelectedItem().toString());
dbHandler.addData(date, repeat, account);
printDatabase();
}
//Delete items with input date from database
public void deleteButtonClicked(View view){
String inputText = dateView.getText().toString();
dbHandler.deleteData(inputText);
printDatabase();
}
----DatabaseHandler.java----
public class DatabaseHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "IncomeExpenseDB.db";
public static final String TABLE_NAME = "income_expense";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DATE = "date";
public static final String COLUMN_REPEAT = "repeat";
public static final String COLUMN_ACCOUNT = "account";
public DatabaseHandler(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_DATE + " TEXT, " + COLUMN_REPEAT + " TEXT, " +
COLUMN_ACCOUNT + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//Add a new row to the database
public void addData(Income date, Income repeat, Income
account){
ContentValues values = new ContentValues();
values.put(COLUMN_DATE, date.get_item());
values.put(COLUMN_REPEAT, repeat.get_item());
values.put(COLUMN_ACCOUNT, account.get_item());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();
}
//Delete data from the database
public void deleteData(String date){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_DATE + "=\""
+ date + "\";");
}
// Create a string to print out in MainActivity
public String databaseToString() {
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE 1";
//Cursor points to a location in results
Cursor c = db.rawQuery(query, null);
//Move to first row in results
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("date")) != null &&
c.getString(c.getColumnIndex("repeat")) != null &&
c.getString(c.getColumnIndex("account")) != null) {
dbString += c.getString(c.getColumnIndex("date"));
dbString += " ";
dbString += c.getString(c.getColumnIndex("repeat"));
dbString += " ";
dbString += c.getString(c.getColumnIndex("account"));
dbString += "\n";
}
c.moveToNext();
}
db.close();
return dbString;
}
}
----Income.java----
public class Income {
private int _id;
private String _item;
public Income(){
}
public Income(String item) {
this._item = item;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_item() {
return _item;
}
public void set_item(String _item) {
this._item = _item;
}
}
Uninstalling and reinstalling is very naive approach which will only work in development phase. When your app goes on to play store, users are not going to uninstall and reinstall the app.
Correct way to update the database for published apps is to increase your db version and use onUpgrade method to update your database.
look at this method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
In current scenario if you just increase your db version, it will drop existing table and create a new one with new columns and specifications. The downside is that you'll lose all of your existing data.
If you want to save existing data and add new column to db, you have to do something like this -
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
//add new column
sqLiteDatabase.execSQL("ALTER TABLE "+ TABLE_NAME + " ADD COLUMN "+ NEW_COLUMN + " INTEGER/TEXT ");
}
}
Just update your version of database when you add any column or make any update in the table. ... this helps me hope it will also work for you.

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

GCM message error in saving in database

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.

SimpleCursorAdapter does not load external sqlite database: "_id" error

The error says: column _id does not exists but the column is in the database (set as primary key) and this one is located in the external SD folder. I'm trying to return the values contained in the database on the initial load of the activity but it seems like the cursor is not returning anything.
public class ComponentsDbAdapter {
public static final String COLUMN_ID = "_id";
public static final String COLUMN_SUBSTRUCTURE = "substructure";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_ORDERNUM = "ordernum";
public static final String COLUMN_INSTALLATION = "installation";
private static final String TAG = "ComponentsDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_PATH = Environment.getExternalStorageDirectory().getAbsoluteFile()+ "/DATABASE_BACKUP/IMPORTED/";
private static final String DATABASE_NAME = "android.db";
private static final String TABLE_NAME = "TAB_WORKSCPE";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
public ComponentsDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_PATH+DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.query(TABLE_NAME, new String[] {COLUMN_ID, COLUMN_SUBSTRUCTURE, COLUMN_TYPE, COLUMN_ORDERNUM, COLUMN_INSTALLATION}, null, null, null, null, null);
}
#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 " + TABLE_NAME);
onCreate(db);
}
}
public ComponentsDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public Cursor fetchComponentsByName(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(TABLE_NAME, new String[] {COLUMN_ID, COLUMN_SUBSTRUCTURE, COLUMN_TYPE, COLUMN_ORDERNUM, COLUMN_INSTALLATION}, null, null, null, null, null);
} else {
mCursor = mDb.query(true, TABLE_NAME, new String[] {COLUMN_ID, COLUMN_SUBSTRUCTURE, COLUMN_TYPE, COLUMN_ORDERNUM, COLUMN_INSTALLATION}, COLUMN_TYPE + " like '%" + inputText + "%'", null, null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllComponents() {
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {COLUMN_ID, COLUMN_SUBSTRUCTURE, COLUMN_TYPE, COLUMN_ORDERNUM, COLUMN_INSTALLATION}, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
public class AndroidListViewCursorAdaptorActivity extends Activity {
private ComponentsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dbHelper = new ComponentsDbAdapter(this);
dbHelper.open();
//Generate ListView from SQLite Database
displayListView();
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllComponents();
// The desired columns to be bound
String[] columns = new String[] {
ComponentsDbAdapter.COLUMN_SUBSTRUCTURE,
ComponentsDbAdapter.COLUMN_TYPE,
ComponentsDbAdapter.COLUMN_ORDERNUM,
ComponentsDbAdapter.COLUMN_INSTALLATION
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.inst,
R.id.subdt,
R.id.type,
R.id.ordernum,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this,
R.layout.country_info,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String compSubdt = cursor.getString(cursor.getColumnIndexOrThrow("subdt"));
Toast.makeText(getApplicationContext(), compSubdt, Toast.LENGTH_SHORT).show();
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,int count, int after) {
}
public void onTextChanged(CharSequence s, int start,int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchComponentsByName(constraint.toString());
}
});
}
}
It doesn't appear from your code that you've created the table yet, so no columns will be found.
You do this within the onCreate method by creating a query to create the table. In your code you appear to be doing a select rather than create.
private static final String TABLE_CREATE = "create table "
+ TABLE_NAME
+ "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_TYPE + " text not null default '', "
+ COLUMN_ORDERNUM + " integer not null default 0, "
+ COLUMN_INSTALLATION + " integer not null default 0, "
+ COLUMN_SUBSTRUCTURE + " text not null default ''"
+ ");";
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(TABLE_CREATE);
}
To store this on the external storage, you'll need to override getDatabasePath(...). A similar solution is here https://stackoverflow.com/a/8385537/935779
#Override
public File getDatabasePath(String name) {
// reference where you would like the file to be here.
File result = new File(getExternalFilesDir(null), name);
return result;
}
I believe you'll want to override this with your Application class since it's a member of ContextWrapper.
The method getDatabaseFile(...) is used inside of openOrCreateDatabase(...) to determine the location.
Alternatively you could just override openOrCreateDatabase(...) and set the file location there.
I don't think you can change or even specify the location of the database, only the name.
Leave off the path and don't try to put it in External Storage - let Android determine the path.
Ok, this took me almost week and a lot of stress but here is the solution. I started to go through a lot of tutorials and got it working in this one:
http://www.mysamplecode.com/2012/11/android-database-content-provider.html
I extracted the database from the virtual device and manually added more data. Then copied the database to the desired folder on my device folder (Its just to make sure the database consistency/columns are exactly the same). Then changed MyDatabaseHelper class as follows:
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_PATH = Environment.getExternalStorageDirectory().getAbsoluteFile()+ "/MYFOLDER/";
private static final String DATABASE_NAME = "TheWorld.db";
private static final int DATABASE_VERSION = 1;
MyDatabaseHelper(Context context) {
super(context, DATABASE_PATH+DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
CountriesDb.onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
CountriesDb.onUpgrade(db, oldVersion, newVersion);
}
}
Don't forget to add permissions to your manifest:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Done!
If you read through the posts above the answer is based on Kirks advice so reading his recommended link helps. I still have more tests to do just in case my database structure was wrong before.

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