How to call methods of an external class from Activity? - android

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.

Related

Static object has separate instance in BroadCastReceiver execution?

I have a static, singleton instance of a SQLiteOpenHelper implementation.
public class MyDbHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 5;
public static final String DATABASE_NAME = "myapp.db";
public static SQL_CREATE_MY_TABLE ="some correct table creation sql";
public static SQL_DELETE_MY_TABLE="some correct table delete sql";
...
public MyDbHelper (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_MY_TABLE);
db.execSQL(SQL_CREATE_OTHER_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_MY_TABLE);
db.execSQL(SQL_DELETE_OTHER_TABLE);
onCreate(db);
}
}
I have another wrapper over the helper as:
public class MyAppDb {
private static MyDbHelper mydbHelper;
public static MyDbHelper getDbHelper(){
if(null == mydbHelper){
mydbHelper= new MyDbHelper(ctx);
return mydbHelper;
}else{
return mydbHelper;
}
}
}
I am using the mydbHelper from this getDbHelper() in my main Ui code(at various places), as well as in a BroadcastReceiver of an Alarmmanager that executes every 5 mins, and in another system BroadcastReceiver.
Sample usage:
SQLiteDatabase db = MyAppDb.getDbHelper().getReadableDatabase();
Intermittently, I get SQLiteDatabaseLockedException and SQLiteException on the the db implementations from the above mydbHelper.
It seems as though although static, there are two different instances of the MyDbHelper occuring at the same time.
What is happening? Can a static object have a separate instance created from BroadCastReceiver?
Or I am doing it wrong?

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.

Android SQLiteDatabase table does not exists

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.

Database initialization error in static method

I have database class. The class and its constructor are shown below.
public class LatLogDBAdapter {
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
I want to use the database in the static method. So that I declare as private static LatLogDBAdapter dbHelper;. Then when i initialize, i have problem. dbHelper = new LatLogDBAdapter(this); dbHelper = new LatLogDBAdapter(DetailMapView.this); make compile error. How can I use this in static method?
If you want to create static method that returns your dbhelper i suggest you to create normal subclass of SQLiteOpenHelper and in this class create public static method that will return new instance. This also is sounds like good reason to use design pattern Singleton
Update:
I mean I want to use this database class inside another java class.
That class has static method and use the database.
Here i create for you basic snippet of code:
public class AdapterWrapper {
private static SQLiteOpenHelper instance;
public static SQLiteOpenHelper getInstance(Context c) {
if (instance == null) {
instance = new DatabaseHelper(c);
}
return instance;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "Example";
private static final int DB_START_VERSION = 1;
public DatabaseHelper(Context cntx) {
super(cntx, DB_NAME, null, DB_START_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating tables
}
#Override
public void onUpgrade(SQLiteDatabase db, int old, int new) {
/// drop an upgrading db
}
}
}

Android Database Instance Class

I need a suggestions how to achieve something in android and Java. I have a big project which has more than 50 activities and I use two different database classes to query sqlite statements and retrieve information from my system and user database. Here is an example how I am using and initializing my database :
SystemDatabaseHelper dbHelper = new SystemDatabaseHelper(this, null, 1);
dbHelper.initialize(this);
I am doing that in activity and the last few days I read a lot for memory leaks in android and the whole information about giving Context to a non-activity classes and the leaks which this can cause. My question is which is the best way to create some class and initialize it only from main activity and than use it in all other activities without initializing it again and again.
Any suggestions which is the best way to achieve this...i have some ideas,but want to hear your suggestions and best practices.
if you are trying to initialize your database helper class only once you're looking for singleton right?? here is an example how you can make it
public class ContactDBHelper extends SQLiteOpenHelper {
private ContactDBHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
private static ContactDBHelper mInstance;
public static synchronized ContactDBHelper getInstance() {
if (mInstance == null) {
mInstance = new ContactDBHelper(Util.getApplicationContext(),
ContactDB.DB_NAME, null, ContactDB.DB_VERSION);
}
return mInstance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ContactDB.Contact.CREATE_STMT);
db.execSQL(ContactDB.Contact.CREATE_PHONE_NUMBER_INDEX);
db.execSQL(ContactDB.Contact.CREATE_REVERSE_PHONE_NUMBER_INDEX);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
#Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
if you call ContactDBHelper.getInstance(); the first time , it will initialize the instance , after that any application component or any method will call it , it wont initialize it will return the singleton initialized instance .
note : for the Util.getApplicationContext it is a static helper method that returns application context which is set in the main Activity .
for memory leaks , you can avoid or protect your app from it using WeakReference or SoftRerference
here is the Util class
public class Util {
private static WeakReference<Context> applicationContext;
public static Context getApplicationContext() {
return applicationContext.get();
}
public static void setApplicationContext(Context context) {
applicationContext = new WeakReference<Context>(context);
}
}
You could extend the application class and use a single global reference. This also has the advantage of not using an Activity context.
public class NameOfApp extends Application {
public static SQLiteDatabase db;
#Override
public void onCreate() {
super.onCreate();
try{
// this will create the database if required (e.g. new install or db deleted)
db=new Database(this.getBaseContext()).getWritableDatabase();
} catch (Exception e) {
// TODO add alert and quit
Log.e(TAG,"Error creating DB:" + e.getMessage());
Toast.makeText(getApplicationContext(), "Error creating DB:" + e.getMessage(), Toast.LENGTH_LONG).show();
}
} // onCreate
#Override
public void onTerminate(){
Log.d(TAG, "Application.onTerminate() database closed");
super.onTerminate();
savePreferences();
db.close();
}
public void closeDB(){
db.close();
Log.d(TAG,"Database closed on request");
}
protected SQLiteDatabase getwritableDatabase(){
return db;
}
}
Use MyAppName.getWritableDatabase().

Categories

Resources