In my app, after user logs in, database is created. When user logs out, I have to delete the database from the internal storage to save space. The problem is, after deleting the database and a user logs back in, database cannot be created anymore. I tried using .close() but it only makes the problem worse.
Here is my code.
DatabaseHelper
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_PATH = "/mnt/sdcard/Philpost/databases/";
private static final String DATABASE_NAME = "DeliveriesDB.sqlite";
private static final int DATABASE_VERSION = 1;
// the DAO object we use to access the SimpleData table
private Dao<DeliveriesDB, Integer> DeliveriesDbDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database,
ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, DeliveriesDB.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
try {
Log.i(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, DatabaseHelper.class, true);
onCreate(db, connectionSource);
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
Log.e(DatabaseHelper.class.getName(), "Cant drop database", e);
e.printStackTrace();
}
}
public Dao<DeliveriesDB, Integer> getDeliveriesDbDao() {
if (null == DeliveriesDbDao) {
try {
DeliveriesDbDao = getDao(DeliveriesDB.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return DeliveriesDbDao;
}
}
DatabaseManager
public class DatabaseManager {
static private DatabaseManager instance;
static public void init(Context ctx) {
if (null == instance) {
instance = new DatabaseManager(ctx);
}
}
static public DatabaseManager getInstance() {
return instance;
}
private DatabaseHelper helper;
public DatabaseManager(Context ctx) {
helper = new DatabaseHelper(ctx);
}
public DatabaseHelper getHelper(Context ctx) {
if(helper == null){
helper = OpenHelperManager.getHelper(ctx, DatabaseHelper.class);
}
return helper;
}
public void releaseDb(Context ctx) {
DatabaseConnection connect;
try {
connect = getHelper(ctx).getConnectionSource()
.getReadWriteConnection();
getHelper(ctx).getConnectionSource().releaseConnection(connect);
helper = null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeDb(){
helper.close();
}
public List<DeliveriesDB> getAllDeliveriesDB(Context ctx) {
List<DeliveriesDB> deliveriesdb = null;
try {
deliveriesdb = getHelper(ctx).getDeliveriesDbDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return deliveriesdb;
}
public void addDeliveriesDb(DeliveriesDB l, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().create(l);
} catch (SQLException e) {
e.printStackTrace();
}
}
public DeliveriesDB getDeliveriesDbWithId(int deliveriesDbId, Context ctx) {
DeliveriesDB deliveriesDb = null;
try {
deliveriesDb = getHelper(ctx).getDeliveriesDbDao().queryForId(
deliveriesDbId);
} catch (SQLException e) {
e.printStackTrace();
}
return deliveriesDb;
}
public void deleteDeliveriesDb(DeliveriesDB deliveriesDb, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().delete(deliveriesDb);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void refreshDeliveriesDb(DeliveriesDB deliveriesDb, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().refresh(deliveriesDb);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateDeliveriesDb(DeliveriesDB deliveriesDb, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().update(deliveriesDb);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The class where creation and deletion of database happens
public class DeliveryListActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DatabaseManager.init(this);
setContentView(R.layout.deliverylist_layout);
if (getLastNonConfigurationInstance() != null) {
deliveryIndex = (Integer) getLastNonConfigurationInstance();
}
if (PhilpostApplication.DELIVERIES == null) {
new RetrieveDeliveriesTask().execute();
} else {
updateCachedList(PhilpostApplication.DELIVERIES);
}
}
private void updateCachedList(List<Delivery> deliveries) {
File expath = context.getFilesDir();
String apppath = "/databases/DeliveriesDB.sqlite";
File path = new File(expath, apppath);
adapter = new DeliveryListAdapter(this,
R.layout.deliverylist_row_layout, deliveries);
setListAdapter(adapter);
PhilpostApplication.DELIVERIES = deliveries;
Log.d(TAG, "Updating UI list");
if (PhilpostApplication.firstDb) {
if (!path.exists()) {
createBackupDb();
Log.d(TAG, "DB first Creation");
}
}
}
public void createBackupDb() {
for (int i = 0; i < PhilpostApplication.DELIVERIES.size(); i++) {
// create db first
dId = PhilpostApplication.DELIVERIES.get(i).getId();
rId = PhilpostApplication.DELIVERIES.get(i).getRecipientId();
lastn = PhilpostApplication.DELIVERIES.get(i).getLastName();
firstn = PhilpostApplication.DELIVERIES.get(i).getFirstName();
addr = PhilpostApplication.DELIVERIES.get(i).getAddress();
dtype = PhilpostApplication.DELIVERIES.get(i).getType();
amount = PhilpostApplication.DELIVERIES.get(i).getCash();
pMan = PhilpostApplication.DELIVERIES.get(i).getPostman();
stats = PhilpostApplication.DELIVERIES.get(i).getStatus();
createNewDeliveriesDb(dId, rId, lastn, firstn, addr, dtype, amount,
pMan, stats);
keyNum[i] = PhilpostApplication.DELIVERIES.get(i).getId();
}
Log.d(TAG, "database created");
PhilpostApplication.firstDb = false;
}
public void logout() {
if (PhilpostApplication.listSynced == false) {
// if( checkIfSyncedList() ){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Sync data first before logging out.")
.setCancelable(false).setPositiveButton("OK", null);
final AlertDialog alert = builder.create();
alert.show();
} else {
dialog = ProgressDialog.show(this, "Logging out", "please wait");
try {
WebService.logout();
PhilpostApplication.SESSION_KEY = null; // clear Application
// Session
// Key
AccountStore.clear(this);
// clear cached list
PhilpostApplication.DELIVERIES = null;
MemoryUtils.deleteCache(this);
PhilpostApplication.incompleteSync = false;
PhilpostApplication.loggedIn = false;
PhilpostApplication.firstDb = true;
DatabaseManager.getInstance().closeDb();
deleteInternalDb();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (PhilpostApplication.canToggleGPS) {
turnGpsOff();
}
dialog.dismiss();
exitActivity();
}
}
}
Deleting Database
public void deleteInternalDb() {
File internalDb = new File(
Environment.getDataDirectory()
+ "/data/packagename/databases/DeliveriesDB.sqlite");
if (internalDb.exists()) {
internalDb.delete();
Log.d(TAG, "Internal Db deleted");
}
}
Check the example here this will give you an idea how to use existing database.
when your getting response from db follow following formate. it work fine bcz i had face this problem.we must have close db in finally block try this it may help you.
try
{
//Query
}
catch
{
}
finally
{
c.close();
db.close();
}
Related
I have problem which many have and I think, that I tried all solutions, but I have not found the right solution yet.
My existing database "base.sqlite3" is in "assets" folder, contains three tables.
When I want to do query, appears error, that table is not there.
(In code are possible syntax errors, cause I translated code)
public class Sqlite extends SQLiteOpenHelper {
private final Context myContext;
public SQLiteDatabase base;
private static String path ="/data/data/" + "com.example.myexample" + "/databases/";
private static String name = "base.sqlite3";
private static String p = path + name;
public Sqlite(Context context){
super(context, ime, null, 1);
this.myContext = context;
createDatabase();
}
#Override
public void onCreate(SQLiteDatabase base) {}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
#Override
public synchronized void close()
{
if(base != null)
base.close();
super.close();
}
public void createDatabase()
{
boolean exist1 = checkDatabase();
if(exist1){}
else
{
base = this.getReadableDatabase();
base.close();
copyDatabase();
}
}
private boolean checkDatabase()
{
SQLiteDatabase check = null;
try
{
check = SQLiteDatabase.openDatabase(p, null, SQLiteDatabase.OPEN_READONLY);
}
catch(SQLiteException e)
{ }
if(check != null)
{
check.close();
}
return check != null ? true : false;
}
private void copyDatabase()
{
InputStream dat = null;
try {
dat = myContext.getAssets().open(name);
} catch (IOException e) {
e.printStackTrace();
}
OutputStream dat2 = null;
try {
dat2 = new FileOutputStream(p);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];
int length;
try {
while ((length = dat.read(buffer))>0)
{
dat2.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
dat2.flush();
dat2.close();
dat.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void openDatabase()
{
base = SQLiteDatabase.openDatabase(p, null, SQLiteDatabase.OPEN_READONLY);
}
public Cursor SelectSomething(String sql)
{
base = SQLiteDatabase.openDatabase(p, null, SQLiteDatabase.OPEN_READONLY);
Cursor cursor = base.rawQuery(sql,null);
return cursor;
}
}
Thank you so much for all help!
As already was stated in the comment to this answer, the code from
this article is
" old, outdated, dreadful (concatenation to create file paths?), and problematic",
and it appears you are not the first to encounter problems with it.
Also, in the same comment to the same answer, it is proposed to use SQLiteAssetHelper. Consider trying it.
Here is my DatabaseHelper which saves everything. How do i erase/clean/clear all the tables?
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "user.db";
private static final int DATABASE_VERSION = 1;
private RuntimeExceptionDao<CurrentUserModel, Long> currentUserModelDao;
private RuntimeExceptionDao<Contact, String> contactDao;
private RuntimeExceptionDao<ChatModel, Long> chatDao;
private RuntimeExceptionDao<ChatMessage, Long> chatMessageDao;
private RuntimeExceptionDao<ChatContact, Long> chatContactDao;
private RuntimeExceptionDao<BroadcastMessage, Long> broadcastMessageDao;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource connection) {
try {
TableUtils.createTable(connection, CurrentUserModel.class);
TableUtils.createTable(connection, Contact.class);
TableUtils.createTable(connection, ChatModel.class);
TableUtils.createTable(connection, ChatMessage.class);
TableUtils.createTable(connection, ChatContact.class);
TableUtils.createTable(connection, BroadcastMessage.class);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connection, int arg2, int arg3) {
try {
TableUtils.dropTable(connection, CurrentUserModel.class, true);
TableUtils.dropTable(connection, Contact.class, true);
TableUtils.dropTable(connection, ChatModel.class, true);
TableUtils.dropTable(connection, ChatMessage.class, true);
TableUtils.dropTable(connection, ChatContact.class, true);
TableUtils.dropTable(connection, BroadcastMessage.class, true);
onCreate(db, connection);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
public RuntimeExceptionDao<CurrentUserModel, Long> getCurrentUserModelDao() {
if (currentUserModelDao == null) {
try {
currentUserModelDao = RuntimeExceptionDao.createDao(getConnectionSource(), CurrentUserModel.class);
currentUserModelDao.setObjectCache(true);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return currentUserModelDao;
}
public RuntimeExceptionDao<Contact, String> getContactDao() {
if (contactDao == null) {
try {
contactDao = RuntimeExceptionDao.createDao(getConnectionSource(), Contact.class);
contactDao.setObjectCache(true);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return contactDao;
}
public RuntimeExceptionDao<ChatModel, Long> getChatDao() {
if (chatDao == null) {
try {
chatDao = RuntimeExceptionDao.createDao(getConnectionSource(), ChatModel.class);
chatDao.setObjectCache(true);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return chatDao;
}
public RuntimeExceptionDao<ChatMessage, Long> getChatMessageDao() {
if (chatMessageDao == null) {
try {
chatMessageDao = RuntimeExceptionDao.createDao(getConnectionSource(), ChatMessage.class);
chatMessageDao.setObjectCache(true);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return chatMessageDao;
}
public RuntimeExceptionDao<ChatContact, Long> getChatContactDao() {
if (chatContactDao == null) {
try {
chatContactDao = RuntimeExceptionDao.createDao(getConnectionSource(), ChatContact.class);
chatContactDao.setObjectCache(true);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return chatContactDao;
}
public RuntimeExceptionDao<BroadcastMessage, Long> getBroadcastMessageDao() {
if (broadcastMessageDao == null) {
try {
broadcastMessageDao = RuntimeExceptionDao.createDao(getConnectionSource(), BroadcastMessage.class);
broadcastMessageDao.setObjectCache(true);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return broadcastMessageDao;
}
#Override
public void close() {
super.close();
if (currentUserModelDao != null) {
currentUserModelDao.clearObjectCache();
currentUserModelDao = null;
}
if (contactDao != null) {
contactDao.clearObjectCache();
contactDao = null;
}
if (chatDao != null) {
chatDao.clearObjectCache();
chatDao = null;
}
if (chatMessageDao != null) {
chatMessageDao.clearObjectCache();
chatMessageDao = null;
}
if (chatContactDao != null) {
chatContactDao.clearObjectCache();
chatContactDao = null;
}
if (broadcastMessageDao != null) {
broadcastMessageDao.clearObjectCache();
broadcastMessageDao = null;
}
}
}
I am trying to make some kind of logout, which would clear all the data. Here is what I have tried:
DatabaseHelper dh = new DatabaseHelper(getActivity().getBaseContext());
dh.close();
clearApplicationData();
This works only if after these 2 rows were done, I kill the app from recent and start it again, else the app tries to register again, and crashes when tries to use the database. how do I correctly reset all application data as it was when it was installed?
The easiest way to erase all tables is to actually delete whole database.
DatabaseHelper databaseHelper = getHelper();
databaseHelper.close();
while (databaseHelper.isOpen() == true) { // maybe you dont want to use while
Thread.sleep(500);
}
this.deleteDatabase("database.db"); // specified in DatabaseHelper class in the DATABASE_NAME field
After doing this you have to create a new database helper (it recreates database) otherwise you would get exception saying something like "unable to open already closed object":
OpenHelperManager.releaseHelper();
OpenHelperManager.setHelper(new DatabaseHelper(this));
In my android app I am using ormlite. Now I want to create some testcases for the db helper methods. I do not know how this should work properly. The database need to be created in my testcase before the concrete test can start. For example I want to test if a user will be created as expected. For this I have a addUser Method which should be tested, but how can this be done?
Currently I created a TestProject with a TestCase for my DBManager-Class.
Here is my DBHelper class
public class DBHelper extends OrmLiteSqliteOpenHelper{
private static final String DATABASE_NAME = "pdixattach.db";
private static final int DATABASE_VERSION = 4;
private static final String TAG = DBHelper.class.getSimpleName();
private static DBHelper _helperInstance;
private Dao<Attachment, Integer> attachmentDao = null;
private Dao<User, Integer> userDao = null;
private Dao<Comment, Integer> commentDao = null;
private Dao<Job, Integer> jobDao = null;
private Dao<Target, Integer> targetDao = null;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource source) {
Log.i(TAG, "onCreate");
try{
dropTables(source);
TableUtils.createTable(source, Attachment.class);
TableUtils.createTable(source, User.class);
TableUtils.createTable(source, Comment.class);
TableUtils.createTable(source, Target.class);
TableUtils.createTable(source, Job.class);
TableUtils.createTable(source, ConfigurationParameter.class);
} catch (Exception e){
Log.e(TAG, "error while creating tables " + e.getMessage());
throw new RuntimeException(e);
}
}
#Override
public void onUpgrade(final SQLiteDatabase db, final ConnectionSource connectionSource, final int oldVersion, final int newVersion) {
Log.i(TAG, "onUpgrade");
try {
dropTables(connectionSource);
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(TAG, "error while upgrading tables " + e.getMessage());
throw new RuntimeException(e);
}
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
}
private void dropTables(final ConnectionSource connectionSource)
throws SQLException {
TableUtils.dropTable(connectionSource, Attachment.class, true);
TableUtils.dropTable(connectionSource, User.class, true);
TableUtils.dropTable(connectionSource, Target.class, true);
TableUtils.dropTable(connectionSource, Job.class, true);
TableUtils.dropTable(connectionSource, Comment.class, true);
TableUtils.dropTable(connectionSource, ConfigurationParameter.class, true);
}
public Dao<Attachment, Integer> getAttachmentDao() throws SQLException {
if (this.attachmentDao == null) {
this.attachmentDao = getDao(Attachment.class);
}
return this.attachmentDao;
}
public Dao<User, Integer> getUserDao() throws SQLException {
if (this.userDao == null) {
this.userDao = getDao(User.class);
}
return this.userDao;
}
public Dao<Comment, Integer> getCommentDao() throws SQLException {
if (this.commentDao == null) {
this.commentDao = getDao(Comment.class);
}
return this.commentDao;
}
public Dao<Target, Integer> getTargetDao() throws SQLException {
if (this.targetDao == null) {
this.targetDao = getDao(Target.class);
}
return this.targetDao;
}
public Dao<Job, Integer> getJobDao() throws SQLException {
if (this.jobDao == null) {
this.jobDao = getDao(Job.class);
}
return this.jobDao;
}
/**
* Close the database connections and clear any cached DAOs.
*/
#Override
public void close() {
super.close();
_helperInstance = null;
this.attachmentDao = null;
this.commentDao = null;
this.jobDao = null;
this.targetDao = null;
this.userDao = null;
}
}
and my DBManager which I want to test, for example the storeUser Method
public class DBManager {
private DBHelper helper;
private static DBManager uniqueInstance;
private static final String TAG = DBManager.class.getSimpleName();
public DBManager(Context context) {
helper = new DBHelper(context);
}
public static void init(Context context) {
if (uniqueInstance == null) {
uniqueInstance = new DBManager(context);
}
}
public static DBManager getInstance() {
return uniqueInstance;
}
public boolean addUser(User u) {
boolean retVal = false;
if (u == null) {
throw new IllegalArgumentException("user must not be null");
}
try {
helper.getUserDao().create(u);
retVal = true;
} catch (SQLException e) {
Log.e(TAG, "error while adding user to db " + e.getMessage());
}
return retVal;
}
public boolean addServiceEndpoint(String endpoint) {
Log.d(TAG, "adding Service Endpoint " + endpoint);
boolean retVal = false;
if (endpoint == null) {
throw new IllegalArgumentException("endpoint must not be null");
}
try {
Target t = new Target(endpoint);
int result = helper.getTargetDao().create(t);
Log.d(TAG, "creating target entry resulted with value " + result);
retVal = (result == 1);
} catch (SQLException e) {
Log.e(TAG,"error while adding target to db, with service endpoint " + endpoint + "error" + e.getMessage());
}
return retVal;
}
public List<Target> getAllTargets() {
List<Target> retVal = new ArrayList<Target>();
try {
retVal = helper.getTargetDao().queryForAll();
} catch (SQLException e) {
Log.e(TAG,
"error while retrieving service endpoints, error" + e.getMessage());
}
return retVal;
}
public User storeUser(String username, String hashedPw, Target target,
boolean storeLogin) {
User loggedInUser = null;
int loginState = (storeLogin) ? 1 : 0;
if (username == null || hashedPw == null || target == null) {
throw new IllegalArgumentException(
"cannot store login with empty/null values");
}
try {
QueryBuilder<User, Integer> queryBuilder = helper.getUserDao().queryBuilder();
Where<User, Integer> where = queryBuilder.where();
where.eq(User.USERNAME, username)
.and().eq(User.TARGET_ID, target.getServiceEndpoint());
PreparedQuery<User> prepareStmt = queryBuilder.prepare();
List<User> userList = helper.getUserDao().query(prepareStmt);
if (userList.isEmpty()) {
Log.d(TAG, "no user found with this name in the db, need to store it");
User newUser = new User(username, hashedPw, target);
newUser.setStored(loginState);
addUser(newUser);
userList = helper.getUserDao().query(prepareStmt);
loggedInUser = userList.get(0);
} else {
Log.d(TAG, "found at least one user with username " + username + " target " + target);
for (User u : userList) {
if (u.getPassword().equals(hashedPw)) {
Log.d(TAG, "password is equal to the one in db");
}
else {
u.setPassword(hashedPw);
}
// setze diesen User als aktiv!
u.setStatus(1);
u.setStored(loginState);
helper.getUserDao().update(u);
loggedInUser = u;
}
}
} catch (SQLException e) {
Log.d(TAG, "error while storing login" + e.getMessage());
}
return loggedInUser;
}
public Comment addComment(Comment cmt) {
Comment retVal = null;
if (cmt == null) {
throw new IllegalArgumentException("cannot create a comment entry in database without comment");
}
try {
retVal = helper.getCommentDao().createIfNotExists(cmt);
} catch (SQLException e) {
e.printStackTrace();
}
return retVal;
}
public Attachment addAttachment(Attachment att) {
if (att == null) {
throw new IllegalArgumentException(
"cannot create attachment entry in database without attachment");
}
Attachment dbAttach = null;
try {
dbAttach = helper.getAttachmentDao().createIfNotExists(att);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dbAttach;
}
public Job addJob(Job job) {
Job dbJob = null;
if (job == null) {
throw new IllegalArgumentException(
"no job given, cannot create an entry");
}
try {
QueryBuilder<Job, Integer> queryBuilder = helper.getJobDao()
.queryBuilder();
Where<Job, Integer> where = queryBuilder.where();
if (job.getInstanceId() == null)
where.isNull(Job.INSTANCE_ID);
else
where.eq(Job.INSTANCE_ID, job.getInstanceId());
where.and().eq(Job.COMMENT_ID, job.getComment().getComment()).and()
.eq(Job.ATTACH_ID, job.getAtach().getAttUri()).and()
.eq(Job.STATUS, "0").and()
.eq(Job.TARGET_ID, job.getTarget().getServiceEndpoint());
PreparedQuery<Job> prepareStmt = queryBuilder.prepare();
Log.d(TAG, "querystring is " + prepareStmt.getStatement());
List<Job> jobList = helper.getJobDao().query(prepareStmt);
if (jobList.isEmpty()) {
Log.d(TAG, "no job with these parameters given, need to create one");
Log.d(TAG, "job id is " + job.getId());
dbJob = helper.getJobDao().createIfNotExists(job);
Log.d(TAG, "dbJob id is " + dbJob.getId());
} else {
Log.d(TAG,
"job does already exists for this parameters, wont create new");
dbJob = jobList.get(0);
// hier comment und status usw updaten
}
} catch (SQLException e) {
Log.d(TAG, "Exception during adding a job to db: " + e.getMessage());
}
return dbJob;
}
public void attachInstanceIdToJob(String instanceId, long jobId) {
Log.d(TAG, "attaching instance id " + instanceId + " to job with id " + jobId);
try {
Job job = helper.getJobDao().queryForId((int) jobId);
if (job != null){
job.setInstanceId(instanceId);
helper.getJobDao().update(job);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
Log.d(TAG, "error while attaching instance id " + instanceId + " to job with id " + jobId);
}
}
public List<Job> getAllOpenJobs() {
List<Job> jobList = null;
QueryBuilder<Job, Integer> queryBuilder;
try {
queryBuilder = helper.getJobDao()
.queryBuilder();
Where<Job, Integer> where = queryBuilder.where();
where.eq(Job.STATUS, JobStatusEnum.OPEN.getState())
.or().eq(Job.STATUS, JobStatusEnum.RETRY.getState());
;
PreparedQuery<Job> prepareStmt = queryBuilder.prepare();
Log.d(TAG, "querystring is " + prepareStmt.getStatement());
jobList = helper.getJobDao().query(prepareStmt);
} catch (SQLException e) {
Log.d(TAG, "error while retrieving open jobs from db" + e.getMessage());
}
return jobList;
}
public void getDataForJob(Job j, User u, Attachment att, Target target, Comment comment) {
try {
if (j != null){
helper.getUserDao().refresh(j.getUser());
helper.getAttachmentDao().refresh(j.getAtach());
helper.getTargetDao().refresh(j.getTarget());
helper.getCommentDao().refresh(j.getComment());
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public User getCurrentStoredUser(){
try {
List<User> users = helper.getUserDao().queryForAll();
for (User u: users){
if (u.getStored() == 1){
return u;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void updateJob(Job j) {
if (j != null){
try {
helper.getJobDao().update(j);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* The status of the given user will be configured to stored. All others will be set to unstored
* #param loggedInUser
*/
public void setUserStatusToStored(User loggedInUser) {
List<User> listOfUsers;
try {
listOfUsers = helper.getUserDao().queryForAll();
for (User u: listOfUsers){
if (u.equals(loggedInUser)){
u.setStatus(UserStatusEnum.STORED.getState());
}
else{
u.setStatus(UserStatusEnum.UNSTORED.getState());
}
helper.getUserDao().update(u);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and my TestClass
public class DBManagerTest
extends TestCase
{
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testDBManager() {
fail( "Not yet implemented" );
}
}
Can someone help me with shat, I guess once the first test is running the others should be clear.
Thanks
I am working on my database layer for my android app, I would like to use testcases for this but I do not know how to solve this in android development envrionement.
I have this DBHelper class
public class DBHelper extends OrmLiteSqliteOpenHelper{
private static final String DATABASE_NAME = "pdixattach.db";
private static final int DATABASE_VERSION = 1;
private static final String TAG = DBHelper.class.getSimpleName();
private static DBHelper _helperInstance;
private Dao<Attachment, Integer> attachmentDao = null;
private Dao<User, Integer> userDao = null;
private Dao<Comment, Integer> commentDao = null;
private Dao<Job, Integer> jobDao = null;
private Dao<Target, Integer> targetDao = null;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource source) {
Log.i(TAG, "onCreate");
try{
TableUtils.createTable(source, Attachment.class);
TableUtils.createTable(source, User.class);
TableUtils.createTable(source, Comment.class);
TableUtils.createTable(source, Target.class);
TableUtils.createTable(source, Job.class);
} catch (Exception e){
Log.e(TAG, "error while creating tables " + e.getMessage());
throw new RuntimeException(e);
}
}
#Override
public void onUpgrade(final SQLiteDatabase db, final ConnectionSource connectionSource, final int oldVersion, final int newVersion) {
Log.i(TAG, "onUpgrade");
try {
TableUtils.dropTable(connectionSource, Attachment.class, true);
TableUtils.dropTable(connectionSource, User.class, true);
TableUtils.dropTable(connectionSource, Target.class, true);
TableUtils.dropTable(connectionSource, Job.class, true);
TableUtils.dropTable(connectionSource, Comment.class, true);
} catch (SQLException e) {
Log.e(TAG, "error while upgrading tables " + e.getMessage());
throw new RuntimeException(e);
}
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
}
public Dao<Attachment, Integer> getAttachmentDao() throws SQLException {
if (this.attachmentDao == null) {
this.attachmentDao = getDao(Attachment.class);
}
return this.attachmentDao;
}
public Dao<User, Integer> getUserDao() throws SQLException {
if (this.userDao == null) {
this.userDao = getDao(User.class);
}
return this.userDao;
}
public Dao<Comment, Integer> getCommentDao() throws SQLException {
if (this.commentDao == null) {
this.commentDao = getDao(User.class);
}
return this.commentDao;
}
public Dao<Target, Integer> getTargetDao() throws SQLException {
if (this.targetDao == null) {
this.targetDao = getDao(User.class);
}
return this.targetDao;
}
public Dao<Job, Integer> getJobDao() throws SQLException {
if (this.jobDao == null) {
this.jobDao = getDao(User.class);
}
return this.jobDao;
}
/**
* Close the database connections and clear any cached DAOs.
*/
#Override
public void close() {
super.close();
_helperInstance = null;
this.attachmentDao = null;
this.commentDao = null;
this.jobDao = null;
this.targetDao = null;
this.userDao = null;
}
With this DBManager:
public class DBManager {
private Dao<User,Integer> userDao;
private Dao<Attachment,Integer> attachmentDao;
private Dao<Target,Integer> targetDao;
private Dao<Comment,Integer> commentDao;
private Dao<Job,Integer> jobDao;
private DBHelper helper;
private static DBManager uniqueInstance;
private static final String TAG = DBManager.class.getSimpleName();
public DBManager(Context context) {
helper = new DBHelper(context);
}
public static void init(Context context){
if (uniqueInstance == null) {
uniqueInstance = new DBManager(context);
}
}
public static synchronized DBManager getInstance(){
return uniqueInstance;
}
private void injectDBHelper(DBHelper dbhelper) {
if (this.helper == null)
this.helper = dbhelper;
else
Log.d(TAG, "DBHelper already available in DBManager");
}
public boolean addUser(User u){
boolean retVal = false;
if (u == null){
throw new IllegalArgumentException("user must not be null");
}
try {
helper.getUserDao().create(u);
retVal = true;
} catch (SQLException e) {
Log.e(TAG, "error while adding user to db " + e.getMessage());
}
return retVal;
}
public boolean addServiceEndpoint(String endpoint) {
boolean retVal = false;
if (endpoint == null){
throw new IllegalArgumentException("endpoint must not be null");
}
try {
Target t = new Target(endpoint);
int result = helper.getTargetDao().create(t);
retVal = (result == 1);
} catch (SQLException e) {
Log.e(TAG, "error while adding target to db, with service endpoint " + endpoint + "error" + e.getMessage());
}
return retVal;
}
I want to generate testcase for the addUser method, can someone help me with that. How can I achieve this in android development envrionment?
Thanks
This is my file dataSqliteHelper and when I run the first time, the data file is created but I don't know where is it to get it and open it with a tool and view the file.
public class DataSQLiteHelper extends OrmLiteSqliteOpenHelper {
public static final String DATABASE_NAME = "ventasdb.db";
private static final int DATABASE_VERSION = 1;
private Context mContext;
private Dao<Customer, Integer> customerDao;
public DataSQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource conections) {
try {
TableUtils.createTable(connectionSource, Customer.class);
} catch (Exception e) {
Log.e(DataSQLiteHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource, Customer.class, true);
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Returns the Database Access Object (DAO) for our UserData class. It will
* create it or just give the cached value.
*/
public Dao<Customer, Integer> getCustomerDao() {
if (customerDao == null) {
try {
customerDao = getDao(Customer.class);
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return customerDao;
}
public boolean updateCustomer(Customer p) {
boolean ret = false;
if (customerDao != null) {
try {
customerDao = getDao(Customer.class);
UpdateBuilder<Customer, Integer> updateBuilder = customerDao
.updateBuilder();
updateBuilder.updateColumnValue("name", "PIRIPIPI"); // p.getName());
updateBuilder.updateColumnValue("cel", p.getCel());
updateBuilder.updateColumnValue("email", p.getEmail());
updateBuilder.updateColumnValue("address", p.getAddress());
updateBuilder.updateColumnValue("City", p.getCity());
// but only update the rows where the description is some value
updateBuilder.where().eq("customerID", 0);
// actually perform the update
customerDao.update(p);
customerDao.refresh(p);
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
/**
* Close the database connections and clear any cached DAOs.
*/
#Override
public void close() {
super.close();
}
}
with this line I know that I give the file name
super(context, DATABASE_NAME, null, DATABASE_VERSION);
but where is it in the storage of the device?
By the way , can I change the path to store the file in the sd card ?
it will be stored at
/data/data/[package name]/databases
But unless your phone is rooted you cannot browse to it using file explorer or adb shell
It is saved here (as nandeesh says)
/data/data/[package name]/databases
You can only access it on a phone if it is rooted. Or you can install the app on an emulator, start up the DDMS tool and view the database file there.