Where is my database file created - android

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.

Related

Running DatabaseConfigUtility as Main class in Android Studio

I am trying to create a DatabaseConfigUtil which extends OrmLiteConfigUtil in Android Studio. I followed the steps specified here but since it mentions steps to follow in Eclipse, I got lost in the middle.
public class DatabaseConfigUtility extends OrmLiteConfigUtil {
public static void main(String[] args) {
try {
writeConfigFile("ormlite_config.txt");
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I tried to Edit configuration for the class still it throws an error because I have defined the path to the config file in my DatabaseHelper class
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "notes.db";
private static final int DATABASE_VERSION = 1;
private Dao<Note, Integer> noteDao = null;
private RuntimeExceptionDao<Note, Integer> noteRunTimeDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
try {
// TableUtils.clearTable will create Table having attribute equals to Note class
TableUtils.createTable(connectionSource, Note.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i2) {
try {
// first drop the table and then create the table again.
TableUtils.dropTable(connectionSource, Note.class, true);
onCreate(sqLiteDatabase, connectionSource);
} catch (SQLException e) {
e.printStackTrace();
}
}
public Dao<Note, Integer> getNoteDao() throws SQLException {
if (noteDao == null) {
noteDao = getDao(Note.class);
}
return noteDao;
}
public RuntimeExceptionDao<Note, Integer> getNoteRunTimeDao() {
if (noteRunTimeDao == null) {
noteRunTimeDao = getRuntimeExceptionDao(Note.class);
}
return noteRunTimeDao;
}
}
The gradle execution fails and throws this error which is because I have declared the path to config file and it does not exist.
Error:Gradle: Execution failed for task ':app:compileDebugJava'.
Compilation failed; see the compiler error output for details.
C:\Users\Pavitra\Documents\AndroidStudio\ORMLiteDemo\app\src\main\java\orm\entities\DatabaseHelper.java
Error:(24, 64) Gradle: error: cannot find symbol variable raw
In order to create ormlite_config.txt file, I have to run the DatabaseConfigUtil class.
How to run the DatabaseConfigUtil to generate the ormlite_config.txt file?
Any help or advice is much appreciated.
Thanks in advance.

Using OrmLite in AppWidget RemoteViewFactory

I need to load data from database in RemoteViewFactory class, I'm using OrmLite.
I've this Helper class:
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "gfkksa.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, Issue.class);
TableUtils.createTable(connectionSource, IssuePriority.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database.");
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource, Issue.class, true);
TableUtils.dropTable(connectionSource, IssuePriority.class, true);
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't drop databases.");
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
public HashMap<String, Dao> getDaoFactory() {
HashMap<String, Dao> hashFactory = new HashMap<String, Dao>();
try {
hashFactory.put("issue", getDao(Issue.class));
hashFactory.put("issuePriority", getDao(IssuePriority.class));
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return hashFactory;
}
}
Everything works ok, in Activity class (extends OrmLiteBaseActivity<DatabaseHelper>), for example i'm getting list of data from DB like this:
ArrayList items = (ArrayList) getHelper().getDaoFactory().get("issue").queryForAll();
But if I do the same at class implementing RemoteViewsService.RemoteViewsFactory (Remote views factory for AppWidget's ListView) app crashes with this exception message:
03-18 16:13:29.244: E/AndroidRuntime(28500): java.lang.RuntimeException: Unable to bind to service cz.testbrana.widget.WidgetService#41e34110 with Intent { dat=intent: cmp=cz.testbrana.ebranasystem/cz.testbrana.widget.WidgetService (has extras) }: java.lang.IllegalStateException: A call has not been made to onCreate() yet so the helper is null
How can I use OrmLite in AppWidget's RemoteViewFactory?
I've found the anwser, everything works great when using methods getHelper() and onDestroy() from oficial documentation (http://ormlite.com/docs/android) instead of extending DBHelper.
private DatabaseHelper databaseHelper = null;
#Override
protected void onDestroy() {
super.onDestroy();
if (databaseHelper != null) {
OpenHelperManager.releaseHelper();
databaseHelper = null;
}
}
private DBHelper getHelper() {
if (databaseHelper == null) {
databaseHelper =
OpenHelperManager.getHelper(this, DatabaseHelper.class);
}
return databaseHelper;
}

android: SQLite Exception: no suche table in existing database with three tables

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.

Ormlite database helper - onCreate() not called

I am using ormlite.android.4.31.jar
I have typical DatabaseHelper
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "realestate.db";
private static final int DATABASE_VERSION = 1;
private Dao<TabKraj, Integer> krajDao;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, TabKraj.class);
initData();
} catch (Exception e) {
Log.e(DatabaseHelper.class.getName(), "Unable to create datbases", e);
}
}
#Override
public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource, int oldVer, int newVer) {
try {
TableUtils.dropTable(connectionSource, TabKraj.class, true);
onCreate(sqliteDatabase, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Unable to upgrade database from version " + oldVer + " to new " + newVer, e);
}
}
public Dao<TabKraj, Integer> getKrajDao() throws SQLException{
if (krajDao == null) {
krajDao = getDao(TabKraj.class);
}
return krajDao;
}
private void initData(){
Log.d(Constants.DEBUG_TAG, "data initiating");
TabKraj k1 = new TabKraj();
TabKraj k2 = new TabKraj();
k1.setNazov("Kosicky kraj");
k1.setId(1);
try {
getKrajDao().create(k1);
} catch (SQLException e) {
Log.e(Constants.DEBUG_TAG, "Data initialing ERROR");
}
}
}
app is uninstalled, data cleared ...
I am running app in debug mode from eclipse, constructor of DatabaseHleper is called but onCreate() is not called.
Where could the problem be?
As #k-mera said:
Database file will be created only if you did some operations in Database like "insert".
Although you say the data is cleared, I suspect that Android thinks it has not. To completely remove the data, I would remove the application and re-install it.
Since your onUpgrade calls onCreate you could also increase the DATABASE_VERSION value which will cause the data to be dropped and re-created.

create / open database after closing

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

Categories

Resources