Im new to android and I want to create kind of CRUD with SQLite.
I have a public class DataBaseHelper
which have a constructor:
public DataBaseHelper(Context context) { this.context = context; }
and a getter for datebase:
public SQLiteDatabase getDataBase() { if (dataBase == null) { try { dataBase = context.openOrCreateDatabase(DataBaseHelper.dbName, Context.MODE_PRIVATE, null); dataBase.execSQL("CREATE TABLE " + DataBaseHelper.accountTblName + " " + "(ID integer PRIMARY KEY AUTOINCREMENT" + ",name TEXT" + ",address TEXT" + ",password TEXT)"); } catch(Exception e) { Log.e(context.toString(), e.getMessage()); if (dataBase != null) { dataBase.close(); } } } return dataBase; }
If I start a program for the first time - everything seems to be okay. database is null and I create it (with a table). But when I restart my app database is null again and table cannot be created.
I've decided to write a checkDB function, which tries to open a database. But where can I get a path for it? I dont want it to be "hardcoded".
Or may be I'm doing some kind of anti-pattern?
getDatabasePath("YourDbName"); String db_path=path. getAbsolutePath(); Log. i("Path:",db_path); even you will see the both code ...then both code is same, 1st one is the shortcut method to get the database path, and it's occupy the less memory compare to second option.
In Windows Explorer, navigate to the drive or folder containing the Access database file you want to open and double-click the database. Access starts and the database is opened.
A DB file is a generic database file. It stores data in a structured format, usually comprised of a set of tables, table fields, field data types, and field values. Many applications create and use different, application-specific types of DB files.
You can get path by context.getDatabasePath(DataBaseHelper.dbName)
here I am writing two ways to get the path.
(1) using custom method
public String getDbPath(Context context,String YourDbName) { return context.getDatabasePath(YourDbName).getAbsolutePath(); }
(2) using File class
File path=context.getDatabasePath("YourDbName"); String db_path=path.getAbsolutePath(); Log.i("Path:",db_path);
even you will see the both code ...then both code is same, 1st one is the shortcut method to get the database path, and it's occupy the less memory compare to second option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With