static database class to use with any activity
I am new to Android, and I haven't developed any app regarding databases on Android yet. So I have a few basic questions. I am after a good database class sample, that will let me to run the CRUD operations. I would like to use it as a static class like:
clsDB->Select("select * from clients");
or
objClient->Delete(clientid);
I am wondering if someone, can share his database classes, if more people share the best. Also I have in mind to reuse this class in multiple ways, I will have services, activities etc...
Regards,
Pentium10
Asked by: Eric320 | Posted: 25-01-2022
Answer 1
The SDK provided Notebook tutorial will walk you through the basics of using the SQLite database ORM provided on the system in the way you describe.
Answered by: Ned568 | Posted: 26-02-2022Answer 2
Dinedal's answer is a good one — the Notepad tutorial is a good starting place for you to learn about Android's database handling.
Check out the other code samples on the Android website too.
If you want to access your data in a simple and consistent manner from various activities and services, you should take a look at the ContentProvider
documentation.
There's also a class called SQLiteOpenHelper
that lets you do basic SQLite database management and versioning. Pretty simple to use.
Answer 3
You can do this way:
DBAdapter.java:
public class DBAdapter {
private final int DATABASE_VERSION = 1;
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public static final String DATABASE_NAME = "db_title";
public static final String COLUMN_AUTO_INCREMENT_ID = "auto_increment_id";
private onDBListeners mDbListener;
public static final int actionGetAllData = 1, actionInsert = 2, actionUpdate = 3, actionDelete = 4, actionDeleteAll = 5;
private Object object = null;
public DBAdapter(Context ctx, onDBListeners listener) {
context = ctx;
DBHelper = new DatabaseHelper(context);
mDbListener = listener;
}
private class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_MY_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Savedfiles");
onCreate(db);
}
}
// ---open database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
// ---closes database---
public void close() {
DBHelper.close();
}
public boolean isValidCursor(Cursor cur){
try {
if(cur!=null){
if(cur.getCount()>0){
return true;
}else{
return false;
}
}else{
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
// --- Table for Data ---
public static final String TABLE_NAME = "tbl_my_table", COLUMN_USER_ID = "user_id", COLUMN_USERNAME = "username";
private static String[] GET_ALL_DATA() {
String[] getMessagesData = new String[] {COLUMN_AUTO_INCREMENT_ID, COLUMN_USER_ID,COLUMN_USERNAME};
return getMessagesData;
}
private static final String CREATE_MY_TABLE = "create table "
+ TABLE_NAME + "(" + COLUMN_AUTO_INCREMENT_ID + " integer primary key autoincrement, "
+ COLUMN_USER_ID + " text not null, "
+ COLUMN_USERNAME + " text);";
// ---insert data in database---
public void insertData(DataModel dataModel) {
open();
ContentValues initialValues = DataModel.getContentValues(dataModel);
boolean var = db.insert(TABLE_NAME, null, initialValues)>0;
if(var){
mDbListener.onOperationSuccess(TABLE_NAME, actionInsert, object);
}else{
mDbListener.onOperationFailed(TABLE_NAME, actionInsert);
}
close();
}
// ---get all data---
public void getAllData() {
open();
Cursor cur = db.query(TABLE_NAME, GET_ALL_DATA(), null, null,null, null, null);
if(cur!=null&&cur.getCount()>0){
mDbListener.onOperationSuccess(TABLE_NAME, actionGetAllData, cur);
}else{
mDbListener.onOperationFailed(TABLE_NAME, actionGetAllData);
}
cur.close();
close();
}
// ---get all data by id---
public void getAllDataByUserId(String userId) {
open();
Cursor cur = db.query(TABLE_NAME, GET_ALL_DATA(), COLUMN_USER_ID+ " = ?", new String[] {userId},null, null, null);
if (cur != null && cur.getCount() > 0) {
mDbListener.onOperationSuccess(TABLE_NAME, actionGetAllData, cur);
} else {
mDbListener.onOperationFailed(TABLE_NAME, actionGetAllData);
}
cur.close();
close();
}
// ---deletes all data---
public void deleteAllData() {
open();
boolean var = db.delete(TABLE_NAME, null, null)>0;
if(var){
mDbListener.onOperationSuccess(TABLE_NAME, actionDeleteAll, object);
}else{
mDbListener.onOperationFailed(TABLE_NAME, actionDeleteAll);
}
close();
}
// ---deletes single data---
public void deleteSingleData(String userId) {
open();
boolean var = db.delete(TABLE_NAME, COLUMN_USER_ID + "=" + userId, null) > 0;
if(var){
mDbListener.onOperationSuccess(TABLE_NAME, actionDelete, object);
}else{
mDbListener.onOperationFailed(TABLE_NAME, actionDelete);
}
close();
}
// ---updates a data details---
public void updateData(DataModel dataModel) {
open();
ContentValues initialValues = DataModel.getContentValues(dataModel);
boolean var = db.update(TABLE_NAME, initialValues, COLUMN_USER_ID + "="+ dataModel.getUserId(), null) > 0;
if(var){
mDbListener.onOperationSuccess(TABLE_NAME, actionUpdate, object);
}else{
mDbListener.onOperationFailed(TABLE_NAME, actionUpdate);
}
close();
}
}
Add below method in DataModel.java class:
public static ContentValues getContentValues(DataModel dataModel){
ContentValues initialValues = new ContentValues();
if(dataModel.getUserId()!=null){
initialValues.put(DBAdapter.COLUMN_USER_ID, dataModel.getUserId());
}
if(dataModel.getUserName()!=null){
initialValues.put(DBAdapter.COLUMN_USERNAME, dataModel.getUserName());
}
return initialValues;
}
Now add below interface for DbOperationListener:
public interface onDBListeners {
public void onOperationSuccess(String tableName, int operation, Object obj);
public void onOperationFailed(String tableName, int operation);
}
Now implement interface in Activity or Fragment:
public class MyActivity implements onDBListeners{
private DBAdapter mDbAdapter;
// Other stuff
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbAdapter = new DBAdapter(MyActivity.this, this);
DataModel mDataModel = new DataModel();
mDataModel.setUserId("1");
mDataModel.setUserName("Hiren");
mDbAdpter.insertData(mDataModel);
}
@Override
public void onOperationSuccess(String tableName, int operation, Object obj) {
LogUtils.Log_e(TAG, "onOperationSuccess : Table Name - "+tableName+" : Table Operation - "+operation);
switch (operation) {
case DBAdapter.actionGetAllData:
Cursor cur = (Cursor) obj;
break;
case DBAdapter.actionInsert:
break;
case DBAdapter.actionUpdate:
break;
case DBAdapter.actionDelete:
break;
case DBAdapter.actionDeleteAll:
break;
default:
break;
}
}
@Override
public void onOperationFailed(String tableName, int operation) {
LogUtils.Log_e(TAG, "onOperationFailed : Table Name - "+tableName+" : Table Operation - "+operation);
switch (operation) {
case DBAdapter.actionGetAllData:
break;
case DBAdapter.actionInsert:
break;
case DBAdapter.actionUpdate:
break;
case DBAdapter.actionDelete:
break;
case DBAdapter.actionDeleteAll:
break;
default:
break;
}
}
}
That's It.
Answered by: Audrey884 | Posted: 26-02-2022Answer 4
Give ActiveAndroid a try. Here's a sample project: https://www.activeandroid.com/help/sample-project/
Answered by: Chelsea663 | Posted: 26-02-2022Answer 5
You can check android-active-record project at http://code.google.com/p/android-active-record/ Though it's focused rather on Java persistent models, you can look into sources and examples -- you can find there plenty of useful examples on how to use SQLite
Answered by: Catherine548 | Posted: 26-02-2022Similar questions
android - Count the number of rows in a database from an activity outside the adapter
Trying to get a count of the rows in a database from a separate activity. I have been messing with the methods to do so, but I can't seem to instantiate them from another activity if the method is built in the database adapter class. Ideally, I would like the method in the adapter to return an int that I can then use in a number of different activities down the chain. Is there a way to do this that I am not thinking of?...
android - Can't create a database in list activity
I am trying to create a database in listactivity on a button click.. but I am getting an error
The method
openOrCreateDatabase(String, int,
null) is undefined for the type new
View.OnClickListener(){}" and
"DefaultDBHelper cannot be resolved.
Is there any way doing this in a listactivity? Please help !!!
my code :
reset.setOnClickListener(new O...
how to get data from a database of another activity in android
in my app in the first activity i have created a database which stores the songs that are in my device SD card. I want play all those songs one by one. In another activity i have a play button when the button is clicked i want to play the songs stored in the database of my first activity.
now i have created the database and stored the songs but i don't know to get songs from that database.
Following is the code of ...
android - How to pass database adapter to another activity?
I'm having some trouble understanding the search dialog in the Android SDK.
The "main activity" of my application provides a button. If the user clicks this button the search dialog is called. The search itself is then done in an async task as it might need some time. So far so good.
The main activity also creates a database adapter object which is used to initialize the database, perform queries, etc. But ...
sqlite - How do I make two database query calls in one activity in android
I would like to make a sql query and puts it in a TextView. I am able to do it for a ListView by following tutorials/examples on using adapters/dbHelpers. I am getting CursorIndexOutOfBoundException will leads me to believe I am not using the Cursor properly.
This is the code in onCreate:
TextView summaryTV = (TextView) findViewById(R.id.summary);
sumAllAmounts = iouHelper.getS...
Android SQLite: Database empty in second activity
I've searched all over the net for a solution to this so lets hope someone here can help.
My app has a start up task which populates a SQLite database before loading the main menu. A second activity that can be accessed from the main menu needs access to this. Therefore I close the database in the first activity in order to stop locking errors.
For some reason, the database seems to have no rows as soon as ...
android - How can I call the Database (from another class) through the main activity class?
I want to make my code clean & simple, so I want to create DB but I want to call it from another class through the main activity... I tried to do this but it didn't works... So, how should it works ??
Note: I'm kind a newbie in the android development. So, sorry for this type of question...
This is the main activity:
package com.DataStorage.Excercise;
import android.app.Activity;
import...
java - Android SQLite database seems to clear every time i open a new activity
I've been trying to fix these two bugs for a while and I feel like it has to do with a fundamental misunderstanding of what happens when I open up a new activity. Basically the program is a task management program. It works fine when I add new tasks without modifying the category, and the database updates fine and the main page of the application updates as I add new tasks to display these new tasks.
However, I rec...
android - sending a column from database table to another activity
I am exctracting data from sqlite database and i need to transfer a column exctracted from select statment to other activity on a textview. How do i do it. Here's my code.
db=database.getReadableDatabase();
Cursor c = db.rawQuery("SELECT lusername, lpwd, lname FROM login WHERE
lusername=userfield.getText().toString(),lpwd=pwdfield.getText().toString()",null);
if(c!=null)
{
I...
database - Android parent Activity issue
I'm trying to add some info to a SQLite dB in mi app. The dB is formed by 3 columns. First is product, then goes quantity and finally price.
I've got one activity to send the data to the database thanks to a button, let's name this one DBCONFIRM. But my app can add data to the dB from more than one activity. The problem is that the "product" field which i need to pass to the D...
android - Adding data to a database cursor
Maybe I'm going about this the wrong way, but if so, please correct me.
Here is the situation: I have a query which returns URI strings for ringtones stored in a database.
I am trying to add a "column" to this cursor with the ringer "Title" (since this can change outside my program).
I can successfully use RingtoneManager to get the title, but I cannot figure out how to add this "column" to the...
Update Database Android
Can anyone tell me how to update the database in android. I created an app with an embedded database. I changed the version of the database in the manifest and created the on update method. I wanted to test it to see if the database was updating properly but when I use the adb command only the -r will allow me to do a reinstall but it keeps the database. Is there a way to run the adb command that will allow me to update th...
android - Backup and restore SQLite database to sdcard
How can I backup my database to the sdcard automatically in my app?
And afterward, how do I restore it?
Loading flat files into Android database table
In Android when you upgrade a database all data is lost.
I'm going through a phase of development right now that is forcing many database upgrades.
I don't want to lose all my data (and have to manually re-enter it) each time I upgrade my database.
I would like to store my data in flat files and load those flat files into their respective tables each time a database upgrade occurs.
Wha...
Select first SMS on Android database inbox
I am desperate to find the solution so I ask for help!
I am a new french programmer. My objective is to create a widget able to show SMS.
My problem is that I don't know how create a cursor which select the first SMS in content://sms/inbox
Excuse my bad English, I hope you will able to understand my wich.
Thank you for your answer.
this is my code:
package sfeir.monwidget;
import android.R.string;
import an...
android - where is database file in the device
iam trying to locate the database files on my nexus device..
is there anyway of doing it without rooting the device?
thanks
ray.
how to get macid and mobile number only in android mobile device not in database
how to get macid and mobile number only in android mobile device not in database
Correct path to sqlite database used by JAR imported into my Android app?
My Android app is using a database through an API packaged in an external JAR. Since the JAR is opening/updating/closing the SQLite database file, do I need to make sure it uses its own package name instead of my own? Im getting errors where it fails to open the database file and Im guessing its because the package name Im telling it to use is incorrect: should it be using the package name in the JAR file?
Code tha...
android import export database
there. I am trying to implement a feature into my app to copy the current database unto the sdcard. Are there any tutorials or code snippets to achieve this. I've already looked at this site, http://mgmblog.com/2009/02/06/export-an-android-sqlite-db-to-an-xml-file-on-the-sd-card/ ... but I wont be able t...
Android database backups
I'm looking for ways to back up the database of my app on an Android phone. I know that SQLite databases are just files, so I'd expect to be able to just copy the file to SD-card if one is available.
However, I'm unsure as to how I'd prepare my database/activity for backup/restore.
When starting, my main activity reads the entries from one table in the database and displays them in a ListView. ...
Still can't find your answer? Check out these communities...
Android Google Support | Android Community | Android Community (Facebook) | Dev.io Android