关闭后创建/打开数据库

时间:2012-03-20 06:45:03

标签: android database ormlite

在我的应用中,用户登录后,会创建数据库。当用户注销时,我必须从内部存储中删除数据库以节省空间。问题是,在删除数据库并且用户重新登录后,无法再创建数据库。我尝试使用.close()但它只会让问题变得更糟。 这是我的代码。 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();
    }
}

    }

发生和删除数据库的类

    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();
    }
}
    }

删除数据库

    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");
    }
}

2 个答案:

答案 0 :(得分:0)

当您从db获得响应时,请遵循以下格式。它工作正常bcz我遇到了这个问题。我们必须在finally块中关闭db尝试这可能对你有帮助。

try
{
   //Query
}
catch
{
}
finally
{
   c.close();
   db.close();
}

答案 1 :(得分:0)

检查example here这将让您了解如何使用现有数据库。

相关问题