Using SQLite to record sensor data - java

I am new in Android. I am working on magnetic sensor in android phone. I am able to access the magnetic sensor and record the sensor data into the .csv file. But i want to record it in SQLite. The problem is that the magnetic sensor data can be obtained in onSensorChanged method in main activity and i dont know how to prepare insert class in SQLite which can obtain the data from the main activity. I have pasted the code for getting data and DBHelper class.
Any help will be useful . thank you in advance.
// For accessing and displaying magnetic data
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;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL);
magnetismx = (TextView) findViewById(R.id.magnetismx);
magnetismy = (TextView) findViewById(R.id.magnetismy);
magnetismz = (TextView) findViewById(R.id.magnetismz);
magnetometer = sm.getDefaultSensor(magnetometer.TYPE_MAGNETIC_FIELD);
if (magnetometer == null) {
Toast.makeText(this, "Magnetometer not available", Toast.LENGTH_SHORT).show();
finish();
}
#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]));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
// my dbHelper class
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 COLXAXIS = "X-AXIS";
private static final String TABLENAME = "MAP_COORDINATES";
private static final String COLYAXIS = "Y-AXIS";
private static final String COLZAXIS = "Z-AXIS";
public DBHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLENAME + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," +
COLXAXIS + " INTEGER, " +
COLYAXIS + " INTEGER, " +
COLZAXIS + " INTEGER )";
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(Integer x, Integer y, Integer z, SQLiteDatabase db ) {
ContentValues contentvalues = new ContentValues();
contentvalues.put("X-AXIS", x);
contentvalues.put("Y-AXIS", y);
contentvalues.put("Z-AXIS", z);
db.insert("MAP_COORDINATES", null, contentvalues);
}
}

You change your DB class as singleton like this, and change the data type Integer to REAL because you are going to store float value,
Note: "-" is not valid in sqlite name so I changed to "_", ex in X-AXIS I converted to X_AXIS.
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 COLXAXIS = "X_AXIS";
private static final String TABLENAME = "MAP_COORDINATES";
private static final String COLYAXIS = "Y_AXIS";
private static final String COLZAXIS = "Z_AXIS";
private static DBHelper mInstance;
private 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 + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," +
COLXAXIS + " REAL, " +
COLYAXIS + " REAL, " +
COLZAXIS + " 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(float x, float y, float z) {
ContentValues contentvalues = new ContentValues();
contentvalues.put("X-AXIS", x);
contentvalues.put("Y-AXIS", y);
contentvalues.put("Z-AXIS", z);
getWritableDatabase().insert("MAP_COORDINATES", null, contentvalues);
}
}
If you already had BaseApplication class just ignore the below code
public class BaseApp extends Application {
private static BaseApp mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static Application getApp() {
return mInstance;
}
}
check you added your base class in mainfest file or not,
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:name=".BaseApp"
android:theme="#style/AppTheme">
</application>
After getting sensor data you can call like this,
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) {
DBHelper.getInstance().insert(a, b, c);
}
}

Usually when working with a database helperclass you want to only have one instance of the object.
This can be realized like this:
DBHelper.java
public class DBHelper extends SQLiteOpenHelper{
....
private static DBHelper instance;
public static DBHelper getInstance (Context context) {
if (instance == null)
instace = new DBHelper (context);
return instance;
}
private DBHelper (Context context) // Notice the private constructor
....
}
....
}
Now the helper can be accessed with DBHelper.getInstance (this) from your Activity
Note: This is called a singleton pattern

Related

I cannot get the app to construct an sqlite database

Hello as the title says I cannot get the app to construct a small local sqlite database. I would appreciate some help as I m an amateur. Thanks in advance.
Below there are some pictures of my source code.
I tested this code on level 24 API device, but the database does not appear in the data/data/the_package/databases/ folder
Edited to include code
MainActivity.java
public class MainActivity extends AppCompatActivity {
private CrdDBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new CrdDBHelper(this);
boolean p1 = true;
int p11sc = 0;
int p12sc = 0;
Button btnMenu = (Button) findViewById(R.id.btnMenu);
Button btntrue = (Button) findViewById(R.id.btnTrue);
Button btnFalse = (Button) findViewById(R.id.btnFalse);
// All other available code commented out
}
#Override
protected void onDestroy() {
mydb.close();
super.onDestroy();
}
}
CrdDBContract.java
public final class CrdDBContract {
private CrdDBContract(){}
public static final class GameEntry implements BaseColumns {
public static final String TABLE_NAME = "Game";
public static final String COLUMN_KNOWN = "Known";
public static final String COLUMN_TBF = "TBF";
public static final String SQL_CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ _ID + " INTEGER PRIMARY KEY, "
+ COLUMN_KNOWN + " TEXT NOT NULL, "
+ COLUMN_TBF + " TEXT NOT NULL)";
}
}
CrdDBHelper.java
public class CrdDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "CardGame.db";
public static final int DATABASE_VERSION = 1;
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CrdDBContract.GameEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
CrdDBDataInsertion.java
public class CrdDBDataInsertion {
//??????????? Code not available from images
SQLiteDatabase mDB;
private void contentvalues(String Known, String TBF) {
ContentValues values = new ContentValues();
values.put(CrdDBContract.GameEntry.COLUMN_KNOWN,Known);
values.put(CrdDBContract.GameEntry.COLUMN_TBF,TBF);
long newid = mDB.insert(CrdDBContract.GameEntry.TABLE_NAME,null,values);
}
}
Main Activity part1Main Activity part2
Main Activity part3(final)
DB Contract class
DB Helper class
DB insert class part1
DB insert class part2 (final)
You aren't, according to the code, acessing(opening) the database. You are just instantiating the DatabseHelper in MainActivity i.e. mydb = new CrdDBHelper(this);
It is not until an attempt is made to open the database (which is frequently implicit) that the database is actually created.
A simple way would be to force an open when instantiating the database. e.g. call the getWritableDatabase() method in the constructor, like :-
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
getWritableDatabase();
}
Perhaps at that time set an SQLiteDatabase object with the returned SQLiteDatabase, so your Database Helper (CrdDBHelper.java) could be :-
public class CrdDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "CardGame.db";
public static final int DATABASE_VERSION = 1;
SQLiteDatabase mDB;
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mDB = this.getWriteableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CrdDBContract.GameEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
as the onCreate method is called when (and ONLY when) the database is created the Game table will then be created.

The retrieving of data from sqlite database is done through this code

I am not getting the add string returned back.
The android app takes input as food item and prints its respective calories.
here is the code for creating table:
public class dietclass extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "diet7.db";
public static final String TABLE_NAME = "Cal_val";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM";
public static final String COL3 = "QUANTITY";
public static final String COL4 = "CALORIES";
public dietclass(Context context) {
super(context,DATABASE_NAME,null,1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM TEXT,QUANTITY VARCHAR,CALORIES INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
}
And here is the code for retrieving data from my activity which is taking item and calories as input.
public class foodcal extends AppCompatActivity {
EditText item;
EditText quantity;
TextView calories;
Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foodcal);
item = (EditText)findViewById(R.id.etitem);
quantity = (EditText)findViewById(R.id.etquantity);
calories = (TextView)findViewById(R.id.calories);
calculate = (Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String itemstr = item.getText().toString();
printDatabase(itemstr);
//String dbstring = dietclass.databaseToString(itemstr);
//calories.setText(String.valueOf(dbstring));
}
});
}
public void printDatabase(String item){
String dbstring = dietclass.databaseToString(this,item);
//String label;
//label = dbstring + "calories";
calories.setText(String.valueOf(dbstring));
}
private static class dietclass extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.example.janhvik.dietapp/databases/";
private static String DB_NAME = "diet7.db";
private static String TABLE_NAME = "Cal_val";
private static SQLiteDatabase myDataBase;
private Context myContext;
public dietclass(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
private static String databaseToString(Context ctx, String item_name) {
String myDbPath;
int cal = 0 ;
String add="";
myDbPath = DB_PATH+DB_NAME;
myDataBase = SQLiteDatabase.openOrCreateDatabase(myDbPath, null);
String query = "SELECT * FROM "+TABLE_NAME+" WHERE ITEM='"+item_name+"'";
Cursor c = myDataBase.rawQuery(query,null);
if(c!= null && c.moveToFirst()){
add = c.getString(c.getColumnIndex("CALORIES"));
c.close();
}
add = add + " calories";
//Toast.makeText(ctx,add, Toast.LENGTH_LONG).show();
return add;
}
I am not getting any error but the code is not taking the value from the select query, can anyone help in this.
I think you've got rather mixed up and complicated matters by appearing to use multiple database helpers/methods to open the same database when you only need to use the database helper. I'm unsure what the exact issue was, there was insufficient code to build an exact replica.
Instead a created simplified working code.
Here's a rewrite/simplification based upon your code :-
First ONE databasehelper class namely dietclass :-
public class dietclass extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "diet7.db";
public static final String TABLE_NAME = "Cal_val";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM";
public static final String COL3 = "QUANTITY";
public static final String COL4 = "CALORIES";
//private static String DB_PATH = "/data/data/com.example.janhvik.dietapp/databases/";
//private static String DB_NAME = "diet7.db";
SQLiteDatabase myDataBase;
private Context myContext;
public dietclass(Context context) {
super(context,DATABASE_NAME,null,1);
myDataBase = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM TEXT,QUANTITY VARCHAR,CALORIES INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
public long insertCal_ValEntry(String item, String quantity, int calories) {
ContentValues cv = new ContentValues();
cv.put(COL2,item);
cv.put(COL3,quantity);
cv.put(COL4,calories);
return myDataBase.insert(TABLE_NAME,null,cv);
}
public String databaseToString(String item_name) {
//String myDbPath;
int cal = 0 ;
String add="";
//myDbPath = DB_PATH+DB_NAME;
//myDataBase = SQLiteDatabase.openOrCreateDatabase(myDbPath, null);
String query = "SELECT * FROM "+TABLE_NAME+" WHERE ITEM='"+item_name+"'";
Cursor c = myDataBase.rawQuery(query,null);
if(c.moveToFirst()){
add = c.getString(c.getColumnIndex("CALORIES"));
c.close();
}
add = add + " calories";
//Toast.makeText(ctx,add, Toast.LENGTH_LONG).show();
return add;
}
}
Notes
For testing purposes, method insertCal_ValEntry has been added.
Done away with any attempt to open Database rather this is done by the helper.
The check to see if the cursor is null has been removed, it is basically useless as SQLite will not return a null, it will always return a cursor, which may be empty. the Cursor move??? methods, such as moveToFirst return false if the move cannot be made.
Context isn't required by the databaseToString method so removed it.
databaseToString method made to be an instance method rather than class method (i.e not static) and made it public.
The activity in this case I've used MainActivity
public class MainActivity extends AppCompatActivity {
EditText item;
EditText quantity;
TextView calories;
Button calculate;
dietclass dbhelper; //<<<< we want an instance of the database helper
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foodcal);
item = (EditText)findViewById(R.id.etitem);
quantity = (EditText)findViewById(R.id.etquantity);
calories = (TextView)findViewById(R.id.calories);
calculate = (Button)findViewById(R.id.calculate);
dbhelper = new dietclass(this); //<<<< get the instance of the database helper
dbhelper.insertCal_ValEntry("Porridge", "100g",5000); //<<<< For testing
dbhelper.insertCal_ValEntry("Cake","500g", 20000); //<<<< For testing
calculate.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String itemstr = item.getText().toString();
printDatabase(itemstr);
//String dbstring = dietclass.databaseToString(itemstr);
//calories.setText(String.valueOf(dbstring));
}
});
}
public void printDatabase(String item){
String dbstring = dbhelper.databaseToString(item); //<<<<
//String label;wr
//label = dbstring + "calories";
calories.setText(String.valueOf(dbstring));
}
}
Notes
The principle used above could be used in any activity. That is get an instance of the database helper and then invoked methods within the helper to get/add/alter data in the database.
Results from the above:-
1) When App is started:-
2) Clicking without input (or inputting item not in table) :-
3) Clicking after inputting valid item :-
Additional Info
If you really want to get the database path the following is less prone to errors:-
String databasepath = getDatabasePath(dietclass.DATABASE_NAME).getPath();
((TextView) findViewById(R.id.dbpath)).setText(databasepath);
With the dbpath TextView (note run on 7.0.0 device):-
On a 4.1.1 device :-

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

Cannot resolve context method

I'm trying to use database in my app and have created an helper class with onCreate and onUpgrade method and an constructor. Then in another class I try to create an object of my helper class with getContext() as they do on the android development documentation. But I get an error saying "cannot resolve method getContext()". I have googled and try like getApplicationContext and that doesn't work. This in the argument doesn't work either. Here is the class I try to write it:
public class SearchResultItem {
DbHelper dbHelper = new DbHelper(getContext());
#JsonKey("Title") // You need to write this so the jsonparser knows which value to get
private String mTitle;
#JsonKey("Year")
private String mYear;
#JsonKey("imdbID")
private String mImdbId;
#JsonKey("Type")
private String mType;
public String getTitle()
{
return mTitle;
}
public String getYear()
{
return mYear;
}
public String getImdbId()
{
return mImdbId;
}
public String getType()
{
return mType;
}
}
And my DbHelper class looks like this if it's needed:
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "movies.db";
//Table name
private static final String MOVIE_TABLE = "movies";
//Column names
private static final String COLUMN_ID = "id";
private static final String COLUMN_TITLE = "title";
private static final String COLUMN_YEAR = "year";
private static final String COLUMN_PLOT = "plot";
Context context;
public DbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) { // Called when the database is created for the first time
final String SQL_MOVIE_TABLE = "CREATE TABLE IF NOT EXISTS " + MOVIE_TABLE + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_TITLE + " TEXT NOT NULL," +
COLUMN_YEAR + " REAL," + COLUMN_PLOT + " TEXT" + ")";
sqLiteDatabase.execSQL(SQL_MOVIE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { // Called when the database needs to be upgraded/changed or dropped
//Drop older table if it exists
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + MOVIE_TABLE);
//Create table again
onCreate(sqLiteDatabase);
}
private boolean haveNetworkConnection()
{
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for(NetworkInfo ni : netInfo)
{
if(ni.getTypeName().equalsIgnoreCase("WIFI"))
{
if(ni.isConnected())
{
haveConnectedWifi = true;
}
}
if(ni.getTypeName().equalsIgnoreCase("MOBILE"))
{
if(ni.isConnected())
{
haveConnectedMobile = true;
}
}
}
return haveConnectedWifi || haveConnectedMobile;
}
Anyone have any clues on how I can solve this?
try this
context = getApplicationContext();
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
Hope it helps

Access SQLiteOpenHelper onCreate Method from wrapping class

Right now i am calling an insertSomeContacts() function in the onCreate method of the MainActivity which obviously adds the given contacts every time the app is restarted (including screen roation)...since my SQLiteOpenHelper Sub-Class is part of my ContactsDBAdapter Class (which carries the insertSomeContacts() method) - how do i get this function to execute in the SQLiteOpenHelper onCreate so that it only executes once at creation of the database?
Really having problems understanding the scope of this and passing that scope around properly.
MainActivity.java:
public class MainActivity extends Activity {
Intent intent;
private ContactsDBAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new ContactsDBAdapter(this);
dbHelper.open();
//dbHelper.deleteAll();
//dbHelper.insertSomeContacts();
displayListView();
}
private void displayListView(){
Cursor cursor = dbHelper.getAll();
String[] fromColumns = new String[]{
ContactsDBAdapter.COLUMN_TYPE,
ContactsDBAdapter.COLUMN_CLTYP,
ContactsDBAdapter.COLUMN_NAME,
ContactsDBAdapter.COLUMN_VNAME
};
int[] toViews = new int[]{
R.id.contactType,
R.id.contactCltype,
R.id.contactName,
R.id.contactVname
};
dataAdapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor, fromColumns, toViews, 0);
ListView listview = (ListView) findViewById(R.id.list);
listview.setAdapter(dataAdapter);
}
ContactsDBAdapter.java:
public class ContactsDBAdapter{
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_CLTYP = "cltyp";
public static final String COLUMN_MDT = "mdt";
public static final String COLUMN_OBJ = "obj";
public static final String COLUMN_VTR = "vtr";
public static final String COLUMN_FKZ = "fkz";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_VNAME = "vname";
public static final String COLUMN_TEL = "tel";
public static final String COLUMN_FAX = "fax";
public static final String COLUMN_MOBIL = "mobil";
public static final String COLUMN_EMAIL = "email";
private static final String TAG = "ContactsDBAdapter";
private DBTools mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "hvkontakte.db";
private static final String DATABASE = "hvkontakte";
private static final String TABLE_NAME = DATABASE;
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_TYPE + ", " + COLUMN_CLTYP + ", " + COLUMN_MDT + ", " + COLUMN_OBJ + ", "
+ COLUMN_VTR + ", " + COLUMN_FKZ + ", " + COLUMN_NAME + ", " + COLUMN_VNAME + ", "
+ COLUMN_TEL + ", " + COLUMN_FAX + ", " + COLUMN_MOBIL + ", " + COLUMN_EMAIL + ")";
private static class DBTools extends SQLiteOpenHelper{
public DBTools(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
Log.w(TAG, DATABASE_CREATE);
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
database.execSQL("DROP TABLE IF EXISTS" + DATABASE);
onCreate(database);
}
}
public ContactsDBAdapter(Context ctx){
this.mCtx = ctx;
}
public ContactsDBAdapter open() throws SQLException{
mDbHelper = new DBTools(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close(){
if(mDbHelper != null){
mDbHelper.close();
}
}
public long createContact(String type, String cltyp, String mdt, String obj, String vtr,
String fkz, String name, String vname, String tel, String fax,
String mobil, String email) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_TYPE, type);
initialValues.put(COLUMN_CLTYP, cltyp);
initialValues.put(COLUMN_MDT, mdt);
initialValues.put(COLUMN_OBJ, obj);
initialValues.put(COLUMN_VTR, vtr);
initialValues.put(COLUMN_FKZ, fkz);
initialValues.put(COLUMN_NAME, name);
initialValues.put(COLUMN_VNAME, vname);
initialValues.put(COLUMN_TEL, tel);
initialValues.put(COLUMN_FAX, fax);
initialValues.put(COLUMN_MOBIL, mobil);
initialValues.put(COLUMN_EMAIL, email);
return mDb.insert(TABLE_NAME, null, initialValues);
}
public boolean deleteAll() {
int doneDelete = 0;
doneDelete = mDb.delete(TABLE_NAME, null , null);
return doneDelete > 0;
}
public Cursor getAll() {
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {COLUMN_ID,
COLUMN_TYPE, COLUMN_CLTYP, COLUMN_NAME, COLUMN_VNAME},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public void insertSomeContacts(){
createContact("vtr","Tenant","1","82","1","2","Bennett","Tony","0911-123456","0911-123457","01577-12345678","info#email.com");
createContact("vtr","Owner","1","82","","","Smith","Brad","0911-1234567","0911-1234567","01577-84368365","info#email.com");
//createContact("","","","","","","","","","","","");
//createContact("","","","","","","","","","","","");
//createContact("","","","","","","","","","","","");
//createContact("","","","","","","","","","","","");
}
}
work with SharedPreferences. Set a init boolean. if init is false insert the contacts -> set the init to true. after restarting do noting when init is true.
But this is maybe not the best solution for your usecase...

Categories