Creating SQLite database for Live magnetic sensor data - java

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

Related

Using SQLite to record sensor data

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

join tables sqlite android [duplicate]

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

Invalid int "" at SQLiteDatabase

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

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...

Why I am not getting any result from rawQuery method in android

I am doing a simple SQlite Apps where I want to save group name in a table and show it on a listview as soon as user click on the add button.
Can any body help me why I am not getting null value from rawQuery result?
public class AddData {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "Grup.db";
public static final int DB_VERSION = 1;
public static final String TABLE = "Grups";
public static final String C_ID = BaseColumns._ID;
public static final String C_CREATED_AT = "easy_ass_created_At";
public static final String C_NAME = "name";
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public class DbHelper extends SQLiteOpenHelper {
// public static final String TAG = DbHelper.class.getSimpleName();
// public static final String DB_NAME = "Grup.db";
// public static final int DB_VERSION = 1;
// public static final String TABLE = "Grups";
// public static final String C_ID = BaseColumns._ID;
// public static final String C_CREATED_AT = "easy_ass_created_At";
// public static final String C_NAME = "name";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = ("create table " + TABLE + " ( " + C_ID
+ " integer primary key autoincrement, " + C_NAME
+ " text not null" + ");");
db.execSQL(sql);
Log.d(TAG, "OnCreate sql" + sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE);
this.onCreate(db);
Log.d("TAG", "********On Upgrate Drop Table*****");
}
}
public AddData(Context context) {
ourContext = context;
}
public AddData open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getReadableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name) {
ContentValues cv = new ContentValues();
cv.put(C_NAME, name);
return ourDatabase.insert(TABLE, null, cv);
}
public String getData() {
String[] columns = new String[] { C_ID, C_NAME };
Cursor c = ourDatabase.query(TABLE, columns, null, null, null, null,
null);
String result = "";
// int iRow=c.getColumnIndex(C_ID);
int iName = c.getColumnIndex(C_NAME);
// for(c.moveToFirst();!c.isAfterLast();c.moveToLast()){
for (boolean hasItem = c.moveToFirst(); hasItem; hasItem = c
.moveToNext()) {
result = result + " " + c.getString(iName) + "\n";
c.moveToNext();
}
c.close();
return result;
}
public ArrayList<String> fatchData() {
ArrayList<String> results = new ArrayList<String>();
try {
Cursor c = ourDatabase.rawQuery("SELECT * from Grups;", null);
if (c != null) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("name"));
results.add("Project: " + firstName);
} while (c.moveToNext());
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (ourDatabase != null)
ourDatabase.execSQL("DELETE FROM Grups");
ourDatabase.close();
}
return results;
}
}
Try removing c.close() and use startManagingCursor(c) (after creating the cursor) in your getData() method

Categories