[Android]SQLite DB cannot be accessed from others activities than one - android

I'm facing some issues with my SQLite Database. I have about 5activities in my application, but i can access to it from only one activity.
On this activity, i can fully use my DB and do all i want to.
On other activities, i cannot use it. I get an empty DB.
Of course, i use the same code to access my DB, regardless of the activity.
I use a homemade class to access the DB, derivated from SQLiteOpenHelper, and another class to manipulate the first one. The DB is downloaded from an online server into the "/data/data/com.example.btc_pe/databases/" folder.
My first class, to access the DB.
public final class BtcDb extends SQLiteOpenHelper
{
public BtcDb(Context context, String name, CursorFactory factory, int version)
{
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
Log.d("BTC","Db created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
//db.execSQL("DROP TABLE "+ TABLE_PRODUITS +";");
//onCreate(db);
}
}
And my manipulation class :
public final class DbHelper
{
public static int version=1;
private static final String nomDb="basesqlite.db";
private int num_id=0;
private int num_tension=1;
private int num_typeRacc=2;
private int num_nbCond=3;
private int num_technique=4;
private int num_typeConn=5;
private int num_conn=6;
private int num_desiConn=7;
private int num_refProd=8;
private int num_desiProd=9;
private int num_diamMin=10;
private int num_diamMax=11;
private int num_section=12;
private int num_diamConnMax1=13;
private int num_diamConnMax2=14;
private int num_diamConnMax3=15;
private int num_diamConnMax4=16;
private int num_diamConnMax5=17;
private String tableProduits = "produit";
private SQLiteDatabase bdd;
private BtcDb btcDb1;
public DbHelper(Context context)
{
btcDb1=new BtcDb(context,nomDb,null,version);
}
public void open()
{
bdd=btcDb1.getReadableDatabase();
}
public void close()
{
bdd.close();
}
public SQLiteDatabase getBdd()
{
return bdd;
}
public int getCountDb()
{
Cursor c = bdd.rawQuery("SELECT COUNT(*) FROM"+ tableProduits, null);
return cursorToCount(c);
}
public int cursorToCount(Cursor c)
{
c.moveToFirst();
int i=c.getInt(0);
return i;
}
}
In my activity, I have to instanciate the DBHelper Class, which instanciate BtcDB.
So all I should have to do is this :
DBHelper dbHelper1 = new DBHelper(this);
dbHelper1.open();
//Manipulation of the DB
int i=dbHelper1.getCountDB(); //In example...
Log.d("BTC","DB Count : "+i);
//Other manipulations of the DB.
dbHelper1.closer();
As i said, it works pretty well on one of my activities but not on the others.
I'm pretty lost here ^^".

So, in short, the problem came from my SQL syntaxe. Really frustrating thing when you see how many time i spent on it.
Thanks everyone for your time.

Related

Android: getContext() error

just a simple error I have but I am really having a hard time trying to solve this problem. why is this getContext() are not applied?
public void ClearRecentPlayer() {
mDbHelper = new DataConn(getContext()); //<---getContext() in redline(not applied)
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues v = new ContentValues();
v.put(FeedReaderContract.FeedEntry.COLUMN_NAME_STATS, 0);
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_STATS + " = ?";
String[] selectionArgs = { "0" };
int c = db.update(
FeedReaderContract.FeedEntry.TABLE_NAME_PLAYER,
v,
selection,
selectionArgs);
}
and with this...
public class DataConn extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "db_egame.db";
DataConn mDbHelper;
public DataConn(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_EASY_ENTRIES);
db.execSQL(SQL_CREATE_HARD_ENTRIES);
db.execSQL(SQL_CREATE_DIFF_ENTRIES);
db.execSQL(SQL_CREATE_PLAYER_ENTRIES);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_EASY_ENTRIES);
db.execSQL(SQL_DELETE_HARD_ENTRIES);
db.execSQL(SQL_DELETE_DIFF_ENTRIES);
db.execSQL(SQL_DELETE_PLAYER_ENTRIES);
onCreate(db);
}
#Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
onCreate(db);
}
As explained here (https://stackoverflow.com/a/10641257/2319627)
•View.getContext(): Returns the context the view is currently
running in. Usually the currently active Activity.
•Activity.getApplicationContext(): Returns the context for the
entire application (the process all the Activities are running inside
of). Use this instead of the current Activity context if you need a
context tied to the lifecycle of the entire application, not just the
current Activity.
•ContextWrapper.getBaseContext(): If you need access to a Context
from within another context, you use a ContextWrapper. The Context
referred to from inside that ContextWrapper is accessed via
getBaseContext.
So, it will be better to use getApplicationContext() when you are trying to use a DataBaseHelper.
And, you can call getApplicationContext from activity or service only, or from an instance of context. Like activity.getApplicationContext()
You need an application context for a Database helper class. So, pass a context to the database on initialization
ClearRecentPlayer method is in an activity? else, you have to pass the application context to the class from which you call ClearRecentPlayer method.
you can either create a member variable .Context in that class, or you can call the ClearRecentPlayer method as ClearRecentPlayer (Context context)
getContext() is only an available method of a View.
If your method is in that database class, you don't actually need the Context. Or any instance of DataConn within its own class.
public class DataConn extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "db_egame.db";
private Context mContext;
public DataConn(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mContext = context;
}
public void clearRecentPlayer() {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues v = new ContentValues();
v.put(FeedReaderContract.FeedEntry.COLUMN_NAME_STATS, 0);
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_STATS + " = ?";
String[] selectionArgs = { "0" };
int c = db.update(
FeedReaderContract.FeedEntry.TABLE_NAME_PLAYER,
v,
selection,
selectionArgs);
}
Try getApplicationContext() instead of getContext() for activity/AppCompactActivity,

Sorting an SQLite database

In my app, I have a database with a table that contains several user made entries. Here's a simplified version of my SQLite database helper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "data.db";
public static final String TABLE_NAME = "log";
public static final String COL_1 = "ID"; //autoincrement in oncreate
...
public static final String COL_12 = "NUMBER"; //set through getCount()
public DatabaseHelper(Context context) {
...
}
#Override
public void onCreate(SQLiteDatabase db) {
...
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
...
}
public long getCount() {
...
}
public boolean insertData(...) {
...
}
public void update(long id, String param) {
...
}
public Cursor getAllData() {
...
}
//for when an entry is deleted and thus COL_12 numbering is not fixed
public void consolidate() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("ALTER TABLE log ORDER BY NUMBER ASC");
}
}
However, whenever I call myDb.consolidate(), my app crashes. From what I've read from other posts, this should work, but it only throws error code 1: missing database. Anyone know why? Any help is appreciated.

How to save with onclicklistener - Android

I'm new to android. Here's one of my OnClickListeners. The thing is I don't know how to make it save when clicking the button. When I call createEventT(Event event), it says "non-static method cannot be referenced from a static context". Sometimes there's no error message, but the app crashes when clicking this button. Any ideas? Thanks.
OnClickListener:
OnClickListener doneT = new OnClickListener(){
#Override
public void onClick(View v) {
event.setTitle(inputToday.toString());
event.setYY(bearsCalendar.get(Calendar.YEAR));
event.setMM(bearsCalendar.get(Calendar.MONTH));
event.setDD(bearsCalendar.get(Calendar.DAY_OF_MONTH));
dateToday.setText(EventDBAdapter.createEventT(event));
}
};
And the event class:
public class Event {
int YY,MM,DD;
private String title;
public void setYY(int YY){this.YY=YY;}
public void setMM(int MM){this.MM=MM;}
public void setDD(int DD){this.DD=DD;}
public void setTitle(String title){this.title=title;};
public int getYY(){return YY;}
public int getMM(){return MM;}
public int getDD(){return DD;}
public String getTitle(){return title;}
}
public class EventDBAdapter{
private final Context mCtx;
static final String dbName="BearDatabase";
static final String eventTable="Events";
static final int dbVersion=1;
static final String colID="EventId";
static final String colTitle="Title";
static final String colDetails="Details";
static final String colYear="YY";
static final String colMonth="MM";
static final String colDay="DD";
static final String colHour="HH";
static final String colMinute="TT";
public DatabaseHelper mDbHelper;
public SQLiteDatabase mDb;
public EventDBAdapter(Context context){
mCtx=context;
}
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context){
super(context,dbName,null,dbVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+eventTable+" ("+colID+" INTEGER PRIMARY KEY , "
+colTitle+" TEXT NOT NULL , "+colDetails+" TEXT , "
+colYear+" INTEGER , "+colMonth+" INTEGER , "+colDay+" INTEGER , "
+colHour+" INTEGER , "+colMinute+" INTEGER );");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + eventTable);
onCreate(db);
}
}
public EventDBAdapter open() throws SQLException{
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public void upgrade(){
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
mDbHelper.onUpgrade(mDb, 1, 0);
}
public long createEventT(Event event){
ContentValues values = new ContentValues();
values.put(colTitle,event.getTitle());
values.put(colYear,event.getYY());
values.put(colMonth, event.getMM());
values.put(colDay, event.getDD());
return mDb.insert(eventTable,null,values);
}
public long createEventI(Event event){
ContentValues values = new ContentValues();
values.put(colTitle,event.getTitle());
return mDb.insert(eventTable,null,values);
}
}
Update:
Any problems in the database? After I made the changes, the whole thing crush.
change below to
dateToday.setText(EventDBAdapter.createEventT(event));
with below and it will work.
dateToday.setText(String.valueOf(EventDBAdapter.createEventT(event)));
I hope you are initializing event object before using it in onClick. if not, then initialize it like event = new Event(); before
event.setTitle(inputToday.toString());
Unless EventDBAdapter in your question is an instance of the EventDBAdapter class, then you are attempting to use a non-static method (public long createEventT()) in a static way (by accessing it through the class name).
To access it, you first need to create an instance of EventDBAdapter. One way to achieve this would probably be (assuming you are calling this method from inside an Activity):
long date = new EventDBAdapter(this).createEventT(event);
dateToday.setText(String.valueOf(date));
There are more answers on this topic here.

How to call methods of an external class from Activity?

First let you know I am new in Android.
Trying to create multiple classes to handle database table operations. Created a database helper as follow:
public class WSDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "wsemp";
private static final int DATABASE_VERSION = 5;
public WSDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
.............
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
................
}
}
Created a class to handle database table operation:
public class CustomerBean {
private WSDatabaseHelper database;
#Override
public boolean onCreate() {
database = new WSDatabaseHelper(getContext());
return false;
}
public boolean insertObject(valObj) {
SQLiteDatabase db = database.getWritableDatabase();
db.insert(.......);
}
}
But now I am not sure how I can call this insertObject function from my activity or session file. I tried by CustomerBean.isnertObject(obj) but it's asking to change the method to static.
There are two ways to call method in this situation
Create the object of the class and call method
// Create object
CustomerBean customerBean = new CustomerBean();
// call the method
customerBean.insertObject(<insert object here>);
Make the method static and call it from class name
// In CustomerBean class
public static boolean insertObject(valObj) {
SQLiteDatabase db = database.getWritableDatabase();
db.insert(.......);
}
//In WSDatabaseHelper class
CustomerBean.insertObject(<object name here>);
On more thing to correct here is that in CustomerBean class you have written
#Override
public boolean onCreate() {
database = new WSDatabaseHelper(getContext());
return false;
}
Which is not correct. onCreate() method of Activity class of Android and
you can put #Override Annotation for this method only if your class is extending Activity class
Hope this will help you
Add the static modifier to your method. Then you should be able to access it between classes.

To create permanent buttons programmatically

Hi I am new to android and I want to know how I can add buttons to my app programmatically . Actually the scenario is like this: In my app, I am having several default categories(given as buttons) to save data. I must provide an option add categories. When I click on the add categories button I must get an option to specify the category name and the sub category name(which i can do). But the thing is that I must get a new button with the entered name and it should not get deleted when i leave the application. Any help is highly appreciated.
To create database: refer How do I create a database in android?
Then you need to use DatabaseHelper class to insert,update or delete data on your database.
refer http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
Now you must be able to manage your data using DatabaseHelper class's object in your activity.
1.DatabaseCreator.java
public class DatabaseCreator extends SQLiteOpenHelper{
private static final String DB_NAME="database_name";
private static final int DB_VER=1;
private static final String TABLE_NAME="create table table_name(_id integer primary key autoincrement,field1 text not null,field2 text not null)";
public DatabaseCreator(Context context)
{
super(context,DB_NAME, null, DB_VER);
}
#Override
public void onCreate(SQLiteDatabase database)
{
database.execSQL(TABLE_NAME);
}
#Override
public void onUpgrade(SQLiteDatabase database, int arg1, int arg2) {
database.execSQL("DROP TABLE IF EXISTS table_name");
onCreate(database);
}
}
2.DatabaseHelper.java
public class DatabaseHelper
{
public static final String TABLENAME_DB="table_name";
public static final String KEY_ID="_id";
public static final String KEY_FIELD1="field1";
public static final String KEY_FIELD2="field2";
Context context;
SQLiteDatabase sqdb;
DatabaseCreator dbcreator;
public DatabaseHelper(Context context)
{
this.context=context;
}
public DatabaseHelper open() throws SQLException
{
dbcreator=new DatabaseCreator(context);
sqdb=dbcreator.getWritableDatabase();
return this;
}
public void close()
{
dbcreator.close();
}
public long addItem(String field1,String field2)
{
ContentValues values=new ContentValues();
values.put(KEY_FIELD1,field1);
values.put(KEY_FIELD2,field2);
return sqdb.insert(TABLENAME_DB,null,values);
}
public long deletItem(long _id)
{
return sqdb.delete(TABLENAME_DB, "_id="+_id,null);
}
}
Use this in your activity like:
DatabaseHelper db_helper=new DatabaseHelper(getApplicationContext());
db_helper.open();
db_helper.addItem("field1_value","field2_value");
db_helper.close();

Categories

Resources