I'm extending DaoMaster.OpenHelper to manage assets folder database. Since it's not user related data the changes can be huge the only one thing I want to achieve is delete and recreate the database when there is a new version. What I don't understand is that this code works when i'm debugging my app on the emulator or even if i generate the apk and install it on my device manually. But when I deploy my app on the market and I install it on my device from there it looks like the it can't find the database.
Exception java.lang.RuntimeException: Unable to resume activity {com.livos.companionplants/com.livos.companionplants.main.MainActivity}: android.database.sqlite.SQLiteException: no such column: T.definition (code 1): , while compiling: SELECT T."_id",T."plant_id",T."definition" FROM "plant_definition" T ################################################################# Error Code : 1 (SQLITE_ERROR) Caused By : SQL(query) error or missing database. (no such column: T.definition (code 1): , while compiling: SELECT T."_id",T."plant_id",T."definition" FROM "plant_definition" T) #################################################################
#ApplicationScope
public class DatabaseOpenHelper extends DaoMaster.OpenHelper {
private String TAG = DatabaseOpenHelper.class.getSimpleName();
private static final String SP_KEY_DB_VER = "db_ver";
private static final int DATABASE_VERSION = 1;
private Context context;
private SharedPreferences sharedPreferences;
private SQLiteDatabase sqliteDatabase;
private static String DB_PATH;
private static String DB_NAME;
public DatabaseOpenHelper(Context context, SharedPreferences sharedPreferences, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
this.context = context;
this.sharedPreferences = sharedPreferences;
DB_NAME = name;
DB_PATH = context.getFilesDir().getAbsolutePath().replace("files", "databases") + File.separator;
try {
createDataBase();
} catch (Exception ioe) {
throw new Error("Unable to create database");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
/** Open Database for Use */
public void openDatabase() {
String databasePath = DB_PATH + DB_NAME;
sqliteDatabase = SQLiteDatabase.openDatabase(databasePath, null,
(SQLiteDatabase.OPEN_READWRITE));
}
/** Close Database after use */
#Override
public synchronized void close() {
if ((sqliteDatabase != null) && sqliteDatabase.isOpen()) {
sqliteDatabase.close();
}
super.close();
}
/** Get database instance for use */
public SQLiteDatabase getSqliteDatabase() {
return sqliteDatabase;
}
/** Create new database if not present */
public void createDataBase() {
SQLiteDatabase sqliteDatabase;
if (databaseExists()) {
int dbVersion = sharedPreferences.getInt(SP_KEY_DB_VER, 1);
// If different version then delete current database and copy the new one from assets
if (DATABASE_VERSION != dbVersion) {
File dbFile = context.getDatabasePath(DB_NAME);
boolean dbFileDeleted = dbFile.delete();
if (!dbFileDeleted) {
Log.w(TAG, "Unable to update database");
} else {
createDataBase();
}
}
/* Check for Upgrade */
} else {
/* Database does not exists create blank database */
sqliteDatabase = this.getReadableDatabase();
sqliteDatabase.close();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(SP_KEY_DB_VER, DATABASE_VERSION);
editor.apply();
copyDataBase();
}
}
/** Check Database if it exists */
private boolean databaseExists() {
SQLiteDatabase sqliteDatabase = null;
try {
String databasePath = DB_PATH + DB_NAME;
sqliteDatabase = SQLiteDatabase.openDatabase(databasePath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
e.printStackTrace();
}
if (sqliteDatabase != null) {
sqliteDatabase.close();
}
return sqliteDatabase != null;
}
/**
* Copy existing database file in system
*/
public void copyDataBase() {
int length;
byte[] buffer = new byte[1024];
String databasePath = DB_PATH + DB_NAME;
try {
InputStream databaseInputFile = this.context.getAssets().open(DB_NAME);
OutputStream databaseOutputFile = new FileOutputStream(databasePath);
while ((length = databaseInputFile.read(buffer)) > 0) {
databaseOutputFile.write(buffer, 0, length);
databaseOutputFile.flush();
}
databaseInputFile.close();
databaseOutputFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean isRoboUnitTest() {
return "robolectric".equals(Build.FINGERPRINT);
}
Solution using Kuffs proposition
#ApplicationScope
public class DatabaseOpenHelper extends DaoMaster.OpenHelper {
private String TAG = DatabaseOpenHelper.class.getSimpleName();
private static final String SP_KEY_DB_VER = "db_ver";
private static final int DATABASE_VERSION = 2;
private Context context;
private SharedPreferences sharedPreferences;
private SQLiteDatabase sqliteDatabase;
private static String DB_PATH;
private static String DB_NAME;
public DatabaseOpenHelper(Context context, SharedPreferences sharedPreferences, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
this.context = context;
this.sharedPreferences = sharedPreferences;
DB_NAME = name;
try {
createDataBase();
} catch (Exception ioe) {
throw new Error("Unable to create database");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
/** Open Database for Use */
public void openDatabase() {
String databasePath = context.getDatabasePath(DB_NAME).toString();
sqliteDatabase = SQLiteDatabase.openDatabase(databasePath, null,
(SQLiteDatabase.OPEN_READWRITE));
}
/** Close Database after use */
#Override
public synchronized void close() {
if ((sqliteDatabase != null) && sqliteDatabase.isOpen()) {
sqliteDatabase.close();
}
super.close();
}
/** Get database instance for use */
public SQLiteDatabase getSqliteDatabase() {
return sqliteDatabase;
}
/** Create new database if not present */
public void createDataBase() {
SQLiteDatabase sqliteDatabase;
if (databaseExists()) {
int dbVersion = sharedPreferences.getInt(SP_KEY_DB_VER, 1);
/* If different version then delete current database and copy the new one from assets*/
if (DATABASE_VERSION != dbVersion) {
File dbFile = context.getDatabasePath(DB_NAME);
boolean dbFileDeleted = dbFile.delete();
if (!dbFileDeleted) {
Log.w(TAG, "Unable to update database");
} else {
createDataBase();
}
}
} else {
/* Database does not exists create blank database */
sqliteDatabase = this.getReadableDatabase();
sqliteDatabase.close();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(SP_KEY_DB_VER, DATABASE_VERSION);
editor.apply();
copyDataBase();
}
}
/** Check Database if it exists */
private boolean databaseExists() {
SQLiteDatabase sqliteDatabase = null;
try {
String databasePath = context.getDatabasePath(DB_NAME).toString();
sqliteDatabase = SQLiteDatabase.openDatabase(databasePath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
e.printStackTrace();
}
if (sqliteDatabase != null) {
sqliteDatabase.close();
}
return sqliteDatabase != null;
}
/**
* Copy existing database file in system
*/
public void copyDataBase() {
int length;
byte[] buffer = new byte[1024];
String databasePath = context.getDatabasePath(DB_NAME).toString();
try {
InputStream databaseInputFile = this.context.getAssets().open(DB_NAME);
OutputStream databaseOutputFile = new FileOutputStream(databasePath);
while ((length = databaseInputFile.read(buffer)) > 0) {
databaseOutputFile.write(buffer, 0, length);
databaseOutputFile.flush();
}
databaseInputFile.close();
databaseOutputFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
I am trying to create a quiz app where a category can be selected by clicking on a listView item. Each category has code like 0,1,2. For football, it is 0. After clicking on the football item, the app keeps on going to the home screen instead of logging the data I want. Please help me with the error.
Quiz Category Selection Class
String quizCategory = intent.getStringExtra("QuizCategory");
//Deciding which database to Open and choose
switch (quizCategory) {
case "0":
Log.i("Category", "Football");
Football football = new Football(this);
football.createDatabase();
football.openDatabase();
football.getWritableDatabase();
long x=football.getRowCount();
break;
default:
Log.i("Message", "Error");
}
}
Football Class
public class Football extends SQLiteOpenHelper {
private static final String Database_path = "/data/data/com.google.quiz/databases/";
private static final String Database_name = "football.db";
private static Context context;
private static final int version = 1;
public SQLiteDatabase sqlite;
public Football(Context context) {
super(context, Database_name, null, version);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public void createDatabase() {
createDB();
}
private void createDB() {
boolean dbexist = DBexists();
if (!dbexist) {
this.getReadableDatabase();
copyDBfromResource();
}
}
private void copyDBfromResource() {
InputStream is;
OutputStream os;
String filePath = Database_path + Database_name;
try {
is = context.getAssets().open(Database_name);//reading purpose
os = new FileOutputStream(filePath);//writing purpose
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);//writing to file
}
os.flush();//flush the outputstream
is.close();//close the inputstream
os.close();//close the outputstream
} catch (IOException e) {
throw new Error("Problem copying database file:");
}
}
public void openDatabase() throws SQLException {
String myPath = Database_path + Database_name;
sqlite = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
private boolean DBexists() {
SQLiteDatabase db = null;
try {
String databasePath = Database_path + Database_name;
db = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
db.setLocale(Locale.getDefault());
db.setVersion(1);
db.setLockingEnabled(true);
} catch (SQLException e) {
Log.e("Sqlite", "Database not found");
}
if (db != null)
db.close();///close the opened file
return db != null ? true : false;
}
public long getRowCount() {
SQLiteDatabase db = this.getReadableDatabase();
long x = DatabaseUtils.queryNumEntries(db, "football");
db.close();
return x;
}
}
Sorry for the post but I didn't find something in the web. I use an existing database in my directory "assets". When I want to update a column the function returns that the column has changed, but in reality nothing happened. I tried with execSQL but nothing again.
Αny opinion will be appreciated!
Here is my DatabaseHelper code :
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "program.db";
public static String DBLOCATION = "";
public static final String TableName="ProgramTable";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, 1);
this.mContext = context;
if(android.os.Build.VERSION.SDK_INT >= 17){
DBLOCATION = context.getApplicationInfo().dataDir + "/databases/";
}
else
{
DBLOCATION = "/data/data/" + context.getPackageName() + "/databases/";
}
}
#Override
public void onCreate(SQLiteDatabase db) {
}
private boolean checkDataBase()
{
File dbFile = new File(DBLOCATION + DBNAME);
return dbFile.exists();
}
//Copy the database from assets
public void copyDataBase() throws IOException
{
InputStream mInput = mContext.getAssets().open(DBNAME);
String outFileName = DBLOCATION + DBNAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void openDatabase() {
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if (mDatabase != null && mDatabase.isOpen()) {
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if (mDatabase != null) {
mDatabase.close();
}
}
public long Like(int id) {
ContentValues contentValues = new ContentValues();
contentValues.put("Favourite",1);
mDatabase=this.getWritableDatabase();
openDatabase();
long k=mDatabase.update(TableName, contentValues, "ID =" +Integer.valueOf(id),null);
closeDatabase();
return k;
}
public long Unlike(int id) {
ContentValues contentValues = new ContentValues();
contentValues.put("Favourite",0);
mDatabase=this.getWritableDatabase();
openDatabase();
long k =mDatabase.update(TableName, contentValues, "ID ="+Integer.valueOf(id),null);
closeDatabase();
return k;
}
}
You need to open first your database before calling the getWritableDatabase();
try to swap your code.
from:
mDatabase=this.getWritableDatabase();
openDatabase();
to:
openDatabase();
mDatabase=this.getWritableDatabase();
Solution
I forgot to use the checkDatabase. In the constructor of DatabaseHelper must include:
if(!checkDataBase())
{
copyDataBase();
}
I want to show my data from sqlite to Custom ListView (java , Android studio , sqlite ).
But it's force stop.
picture from my Main Activity:
picture from my Database class:
Please Help me!!!!
(my English is not good sorry but can i understand your words)
first you have to create a custom adapter for your listview and populate that adapter with listview and your code should be like this
and to get the data from database create a method in database class name getdata() take it in a form of cursor
public class UserDbHelper extends SQLiteOpenHelper {
public static final String DATABASENAME = "DATABASENAME2";
public static final int DB_VERSION = 3;
public static final String TABLE_NAME = "student";
public static final String DEVICE = "device"; //your coloumn
public static final String ADDRESS = "address";//your coloumn
public static final String Date = "Date"; //your coloumn
public String CREATE_QUERY = "CREATE TABLE "+TABLE_NAME+"("+DEVICE+" TEXT,"+ADDRESS+" TEXT,"+Date+"TEXT);";
public UserDbHelper(Context context)
{
super(context,DATABASENAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_QUERY);
}
public List<Datalist> getdata()
{
List<Datalist> result = new ArrayList<>();
Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM Table_name,null";);
while (c.moveToNext()) {
result.add(
new Datalist(
c.getString(c.getColumnIndex("YOUR COLOUMN")),
c.getString(c.getColumnIndex("YOUR COLOUMN")),
date
)
);
}
c.close();
return result;
}
and populate your database with listview
this will be in your button click that button which retrive the data
List<Datalist> itemFromDatabase = getItemFromDatabase();
MyAdapter adapter = new MyAdapter(getApplicationContext(), 0, itemFromDatabase);
listOfDatabaseObject.setAdapter(adapter);
adapter.notifyDataSetChanged();
MainActivity.java
public class MainActivity extends AppCompatActivity {
DataBaseHelper myDbHelper;
List<String> stringList;
ListView listView;
List<Mivejat> mivejatList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDbHelper = new DataBaseHelper(this);
stringList = new ArrayList<>();
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
myDbHelper = new DataBaseHelper(this);
mivejatList = myDbHelper.MiveName();
for (int i = 0 ; 0 < mivejatList.size() ; i++) {
stringList.add(mivejatList.get(i).name);
}
listView = (ListView) findViewById(R.id.listViewMive);
mainListViewClass mainListViewClass = new mainListViewClass(MainActivity.this , stringList);
listView.setAdapter(mainListViewClass);
mainListViewClass.notifyDataSetChanged();
myDbHelper.close();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DataBaseHelper myDbHelper;
List<String> stringList;
ListView listView;
List<Mivejat> mivejatList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDbHelper = new DataBaseHelper(this);
stringList = new ArrayList<>();
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
myDbHelper = new DataBaseHelper(this);
mivejatList = myDbHelper.MiveName();
for (int i = 0 ; 0 < mivejatList.size() ; i++) {
stringList.add(mivejatList.get(i).name);
}
listView = (ListView) findViewById(R.id.listViewMive);
mainListViewClass mainListViewClass = new mainListViewClass(MainActivity.this , stringList);
listView.setAdapter(mainListViewClass);
mainListViewClass.notifyDataSetChanged();
myDbHelper.close();
}
}
DataBaseHelper.java
public class DataBaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/mivejat.rezaahmadpour.ir.mivejat/databases/";
private static String DB_NAME = "KhavasMiveha.db";
public static final int DB_VERS = 1;
private SQLiteDatabase myDataBase;
private final Context myContext;
private static String TAG = "KhavasMiveha.db";
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* #param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERS);
this.myContext = context;
}
/**
* Creates an empty database on the system and rewrites it with your own
* database.
*/
public boolean createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
Log.d(TAG, "database already exist");
//Running this method causes SQLite class checking for if New DB Version Exists and runs upgrade method
getReadableDatabase();
close();
return true;
} else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
return false;
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transferring bytestream.
*/
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "UPGRADING Database...");
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
public List<Mivejat> MiveName() {
String query = "SELECT Name FROM tbl_mive";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
List<Mivejat> result = new ArrayList<>();
Mivejat m;
while (cursor.moveToNext()) {
m = new Mivejat();
m.name = cursor.getString(0);
result.add(m);
}
return result;
}
yoh...
I was trying to retrieve data from my external database in assets
but when I run the app, seems like it created another database in /data/data/packagename/databases/ :-( not the external database from assets I inserted and causing an error(Unfortunately, App has stopped). Here's my Code:
ingameinterface .java*
public class ingameinterface extends Activity {
DBHelper dbhelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ingameinterface);
String[] from = new String[] { "CtrlNo", "Prima", "Key_Word", "Val" };
int[] to = new int[] { R.id.itmCc1, R.id.itmCc2, R.id.itemCc3, R.id.itemCc4};
dbhelper = new DBHelper(this);
try {
dbhelper.createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Cursor c = dbhelper.getData();
if (c.getCount() == 0) {
showmessage("Error!", "Nothing found.");
return;
}
StringBuffer buff = new StringBuffer();
while (c.moveToNext()) {
buff.append("Controlnum: " + c.getString(0) + "\n");
buff.append("Prima: " + c.getString(1) + "\n");
buff.append("Word: " + c.getString(2) + "\n");
buff.append("Value: " + c.getString(3) + "\n\n");
}
showmessage("Data", buff.toString());
}
public void showmessage(String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
}
}
and
DBHelper.Java*
public class DBHelper extends SQLiteOpenHelper {
private static String DB_NAME = "db_vocabulary";
private SQLiteDatabase db;
private final Context context;
private String DB_PATH;
public DBHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
// throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException {
InputStream myInput = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public Cursor getData() {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
Cursor c = db.rawQuery("SELECT * FROM TblWords WHERE Prima = 1", null);
return c;
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
use this in your DBHelper.java file:
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists "+TABLE_NAME+"(PHONENUMBER VARCHAR,NAME VARCHAR)");
}
so that it will wont create another table if already that table exits in database.
I'm using a premade database and I seem to be getting an error when I try to update a row. The exact error from logcat is: (1) no such table: AUD. Heres what my dbhelper class looks like:
public class DataBaseHelper extends SQLiteOpenHelper {
private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
//destination path (location) of our database on device
private static String DB_PATH = "/data/data/com.example.simplecurrency3/databases/";
private static String DB_NAME ="Currencies";// Database name
private SQLiteDatabase mDataBase;
private final Context mContext;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 2);// 1? its Database Version
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
}
else
{
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
this.mContext = context;
}
public void createDataBase() throws IOException {
//If database not exists copy it from the assets
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist)
{
this.getReadableDatabase();
this.close();
try
{
//Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
}
catch (IOException mIOException)
{
throw new Error("ErrorCopyingDataBase");
}
}
}
//Check that the database exists here: /data/data/your package/databases/Da Name
private boolean checkDataBase()
{
File dbFile = new File(DB_PATH + DB_NAME);
//Log.v("dbFile", dbFile + " "+ dbFile.exists());
return dbFile.exists();
}
//Copy the database from assets
private void copyDataBase() throws IOException
{
InputStream mInput = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
//Open the database, so we can query it
public boolean openDataBase() throws SQLException
{
String mPath = DB_PATH + DB_NAME;
//Log.v("mPath", mPath);
mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
//mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return mDataBase != null;
}
#Override
public synchronized void close()
{
if(mDataBase != null)
mDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
And when I try to update a row:
Context context = getActivity().getApplicationContext();
DataBaseHelper dbHelper = new DataBaseHelper(context);
dbHelper.openDataBase();
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.execSQL("UPDATE AUD SET AUD = 2.0")
You have never called createDataBase() method! You can put it into onCreate() method.
Good luck
Instead of updating a row, first check whether the table really exists by using the following query.
SELECT name FROM sqlite_master WHERE type='table'