1

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");
    }
}
madz
  • 45
  • 9
  • An alternative solution for this would be creating and accessing my database from the sdcard so I won't have to delete it everytime a user logs in and out of the app. But i don't know how. – madz Mar 20 '12 at 06:50

2 Answers2

0

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();
}
Hasmukh
  • 4,632
  • 2
  • 30
  • 44
  • my db.close() is working fine. I'm having trouble creating the database back. thanks for the help – madz Mar 20 '12 at 07:11
0

Check the example here this will give you an idea how to use existing database.

Community
  • 1
  • 1
Yaqub Ahmad
  • 27,569
  • 23
  • 102
  • 149
  • I cannot use the previous database because I already deleted it permanently from the device. What I really need to do is create a new database every time a user logs in. This is because every user has different values inside the database. – madz Mar 20 '12 at 07:13
  • I guess somthing is wrong with your database structure!! You should keep data in your database for each user. – Yaqub Ahmad Mar 20 '12 at 07:23
  • I cant because number of users are dynamic. To keep all of it takes up very large space. Thanks for the answer. – madz Mar 20 '12 at 07:37