Android SQLiteDatabase table does not exists - android

I am having a class named GameDb and it's extending SQLiteOpenHelper. I don't know why, but onCreate it's not called, the table is not created !
Having a singelton for all my activities and fragments:
public MyApp extends Application
{
// .... Code
private GameDb gameDb;
public GameDb getGameDb()
{
if (gameDb == null)
gameDb = new GameDb(this);
return this.gameDb;
}
}
Getting all games from database, calling from an activity
public class MyActivity extends FragmentActivity
{
#Override
protected void onCreate(Bundle bundle)
{
// Code....
// Get all games
ArrayList<Game> allGames = getMyApp().getGameDb().getAllGames();
}
}
Class which contains all necessary methods for querying the database (writing and reading). This methods are not written below because it's not necessary.
public class GameDb
{
private SQLiteDatabase db;
private GameDbHelper dbHelper;
public GameDb(Context context)
{
this.dbHelper = new GameDbHelper(context);
this.db = dbHelper.getWritableDatabase();
}
public ArrayList<Games> getAllGames()
{
// return db.query(....);
}
public void insertNewGame(int id, String name)
{
// db.query(....);
}
// Static inner class which extends SQLiteOpenHelper
private static class GameDbHelper extends SQLiteOpenHelper
{
public GameDbHelper(Context context)
{
super(context, "DB_NAME", null, 1);
}
// On create not called !
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE my_table(_id INTEGER AUTOINCREMENT, date TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
dropTable(db);
onCreate(db);
}
public void dropTable(SQLiteDatabase db)
{
db.execSQL("DROP TABLE IF EXISTS my_table");
}
}
}
When I'm trying to get all games, or add a new game I'm getting a FATAL EXCEPTION, (1) no such table: my_table

You may have a old database present on your device and database doesn't always get deleted when you reinstall the app using IDE. Thus you must uninstall the app manually and the reinstall your app using IDE.

I don't believe onCreate() gets implicitly called when you instantiate your database object. You need to explicitly call your Activity's openOrCreateDatabase() method.

Related

Passing database class object from main activity to another activity

I am trying to implement simple database CRUD operations, in case of UPDATE operation user moves to another screen where he inputs the new and old values for the column he wants to update, So while moving to next activity I want to pass the object of database class created in MainActivity to UpdateActivity, I tried it by implementing the Database class Serializbale but it crashes.
java.lang.RuntimeException: Parcelable encountered IOException reading a Serializable object
Here is the code i tried
MainActivity
MyDbHandler dbObj = new MyDBHandler(this, null, null, 1);
public void updateBtnClicked(View view)
{
Intent intent = new Intent(MainActivity.this, ActivityUpdate.class);
intent.putExtra("Object", dbObj);
startActivity(intent);
}
ActivityUpdate
intent = getIntent();
dbObj2 = (MyDBHandler) intent.getSerializableExtra("Object");
public void doneButtonClicked(View view)
{
String str1 = newValue.getText().toString();
String str2 = oldValue.getText().toString();
dbObj2.updateProduct(str1, str2);
finish();
}
So how could the database class object be passed from one to another activity? Thanks
how could the database class object be passed from one to another activity
You don't serialize Database objects. You request them again.
MyDbHandler dbHandler = new MyDbHandler(MainActivity.this); // pass your Activity here
dbHandler.update(new Foo(42));
Where MyDbHandler is some extension of SQLiteOpenHelper written like so
public class MyDbHandler extends SQLiteOpenHelper {
// Database Info
private static final String DATABASE_NAME = "DatabaseName";
private static final int DATABASE_VERSION = 1;
public MyDbHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
// TODO
}
/**
* Update method defined here
**/
public void update(Foo bar) {
SQLiteDatabase db = getWritableDatabase();
// TODO: Write to & close the database
}
}
MyDbHandler must extend Serializable to be correctly serialized.

i want to insert a record to my db in second activity

I am new on Android programming. So that, I'll use wrong technical words, sorry for that ;)
i ve an app. in this app, onCreate, im checking if my db is created ( this check is for first time use ), if my db isn't created yet I'm routing user to a second layout( or activty. i couldnt be sure whch one is right word ). in this activity, when i try to create a SQLiteDatabase parameter im having a null pointer exception.
Here is a part of MainActivity.java
public class MainActivity extends Activity
{
VeriTabani veritabani; // vertiabani means database in turkish
#Override
protected void onCreate(Bundle savedInstanceState)
{
if(db_flag==0)
{
Intent intent = new Intent(MainActivity.this, SecondClass.class);
startActivity(intent);
//...
}
}
}
Here is my VeriTabani.java;
public class VeriTabani extends SQLiteOpenHelper
{
static final String VeriTabani="DATABASENAME";
static final int version=1;
public VeriTabani(Context context) {
super(context, VeriTabani, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE TABLENAME ( id INTEGER PRIMARY KEY AUTOINCREMENT, xxx STRING,yyy STRING );");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST TABLENAME");
onCreate(db);
}
}
And, here is my SecondClass.java;
public class SecondClass extends Activity
{
VeriTabani veritabani;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SQLiteDatabase db=veritabani.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put("xxx", another_parameter);
//...
}
//...
}
}
}
im having error on this line;
SQLiteDatabase db=veritabani.getWritableDatabase();
I'm using same VeriTabani class to insert records to DB in MainActivity and it works perfectly. i couldnt undertand what is wrong when i use same code block in another activity.
i guess solve is simple but i couldnt get it.
Thanks for your help.
you have just declared your variable
VeriTabani veritabani;
you haven't initialized that variable. you need to initialize it on onCreate() method.
veritabani = new VeriTabani(YourActivityName.this);
im having error on this line;
SQLiteDatabase db=veritabani.getWritableDatabase();
Looks like you didn't initialize your veritabani variable.
Add the following to that activity's onCreate():
veritabani = new VeriTabani(this);

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.

Android/SQLite right way to open/close db?

Im a bit new to OOP so i want to know if im doing things correctly. For communication with database i have created a class SQLiteHelper witch does all the usual stuff (onCreate, onUpdate) and also opens and closes connection.
Here is the class, at the moment it has just on table but more will be added:
public class SQLiteHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "notebook";
public static final int DATABASE_VERSION = 2;
public static final String TABLE_LIST = "list";
public static final String TABLE_LIST_ID = "_id";
public static final String TABLE_LIST_NAME = "name";
public SQLiteDatabase db;
public SQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table " + TABLE_LIST + "(" + TABLE_LIST_ID
+ " integer primary key autoincrement, " + TABLE_LIST_NAME
+ " text not null);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LIST);
onCreate(db);
}
public void open(){
db = getWritableDatabase();
}
public void close(){
db.close();
}
}
And next for each table i will create a new class witch extends previous class andd where i do all the operations relevant to that specific table.
For example ListSQL:
public class ListSQL extends SQLiteHelper {
public ListSQL(Context context) {
super(context);
}
public void delete(int id) {
open();
db.delete(TABLE_LIST, TABLE_LIST_ID + " = " + id, null);
close();
}
}
My question is that in OOP is this the correct way of doing things? Espesially the usage of open/close methods and db and TABLE variables in ListSQL seem kind of strange to me?
I always open the db connection in onResume() and close it in onPause(). In this way database is always open for each activity.
The reason I am not doing it in onCreate() and onDestroy() is once user go to other activity onCreate() of new activity will be called first then onDestroy() of old activity so if I perform any operation(ex:- search in my list or changing the status of user etc) on places other then onCreate() it will crash the app with reason database already closed.
Note: You have to open and close the connection, even if you are using SQLiteHelper class.
According to the Android manual, you do not need to close a database when using an SQLiteOpenHelper. The system will do it for you.
As #Dan mentioned above, you do no need to open and close the database every time you do a read/write operation if you are using SQLiteOpenHelper. The best way to use the database is :
1.
Declare and initialize an instance of SQLiteHelper in your Application base class like this :
public class App extends Application {
public static SQLiteHelper db;
#Override
public void onCreate() {
super.onCreate();
db = new SQLiteHelper(getApplicationContext());
db.open();
}
}
2.
In you activity, or any other place you want to use the DB, initialize the SQLiteHelper object like this :
SQLiteHelper db = App.db;
And then you can use the database anyway you want without having to worry about opening and closing it (:

SQLite database handling with android application

Hi i am going to create a SQLite database and insert records. but my database does not create.
following is the code. Cant understand why. trying this for a long time
If someone can help its a great help
public class DatabaseHelper extends SQLiteOpenHelper{
static final String dbName="MyDatabase";
public DatabaseHelper(Context context) {
super(context, dbName, null,33);
}
#Override
public void onCreate(SQLiteDatabase db) {
String qry = "CREATE TABLE DEPT(dept_id INTEGER PRIMARY KEY, deptName TEXT)";
db.execSQL(qry);
}
}
I am calling the constructor like this
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatabaseHelper dp = new DatabaseHelper(this);
Toast.makeText(this, "Finish Execution", Toast.LENGTH_LONG).show();
}
}
create your database by using this sample
http://marakana.com/forums/android/examples/55.html

Categories

Resources