First of all I created my prescription_table and that worked.
Then I tried to add a second table to the database called patient_table.
However I am getting this error "
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(no such table: patient_table (code 1): , while compiling: INSERT INTO patient_table(PPS,CARINGID,DOB,ADDRESS,SNAME,PATIENTTYPE,PATIENTMEDCON,FNAME) VALUES (?,?,?,?,?,?,?,?))
I tried changing the database version number from 1 to 2 however this made my app crash. I have also tried to uninstall the application from my android device however it is still giving me the same error.
Any help would be grateful.
package com.example.medicationmanagementsystem.DAO;
//code below is based on AndroidSQLite Tutorial Android CRUD Tutorial with SQLite (Create, Read, Update, Delete), ProgrammingKnowledge, https://www.youtube.com/watch?v=kDZES1wtKUY
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
//Create Database
public static final String DATABASE_NAME = "ManagementSystem.db";
//Create patient table
public static final String TABLE_PATIENT = "patient_table";
public static final String COL_PATIENT_PATIENTID = "PATID";
public static final String COL_PATIENT_FNAME = "FNAME";
public static final String COL_PATIENT_SNAME = "SNAME";
public static final String COL_PATIENT_PPS = "PPS";
public static final String COL_PATIENT_DOB = "DOB";
public static final String COL_PATIENT_ADDRESS = "ADDRESS";
public static final String COL_PATIENT_TYPE = "PATIENTTYPE";
public static final String COL_PATIENT_MEDCOND = "PATIENTMEDCON";
public static final String COL_PATIENT_CARINGID = "CARINGID";
//Create prescription table
public static final String TABLE_PRESCRIPTION = "prescription_table";
public static final String COL_PRESCRIPTION_ID = "PRESCRIPTIONID";
public static final String COL_PRESCRIPTION__PATIENTID = "PATIENTID";
public static final String COL_PRESCRIPTION__DATE = "DATE";
public static final String COL_PRESCRIPTION__DRUGNAME = "DRUGNAME";
public static final String COL_PRESCRIPTION__CONCENTRATION = "CONCENTRATION";
public static final String COL_PRESCRIPTION__DOSAGE = "DOSAGE";
public static final String COL_PRESCRIPTION__PREPARATION = "PREPARATION";
public static final String COL_PRESCRIPTION__STARTDATE = "STARTDATE";
public static final String COL_PRESCRIPTION__ENDDATE = "ENDDATE";
public static final String COL_PRESCRIPTION__DOCTORID = "DOCTORID";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate (SQLiteDatabase db) {
String patienttable = "CREATE TABLE " + TABLE_PATIENT + "(PATID INTEGER PRIMARY KEY AUTOINCREMENT, FNAME TEXT, SNAME TEXT, PPS TEXT, DOB TEXT, ADDRESS TEXT, PATIENTTYPE TEXT, PATIENTMEDCON TEXT, CARINGID INTEGER)";
String prescriptiontable = "CREATE TABLE " + TABLE_PRESCRIPTION + "(PRESCRIPTIONID INTEGER PRIMARY KEY AUTOINCREMENT, PATIENTID INTEGER, DATE TEXT, DRUGNAME TEXT, CONCENTRATION TEXT, DOSAGE TEXT, PREPARATION TEXT, STARTDATE TEXT, ENDDATE TEXT, DOCTORID INTEGER)";
db.execSQL(patienttable);
db.execSQL(prescriptiontable);
this.getReadableDatabase();
this.getWritableDatabase();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_PATIENT);
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_PRESCRIPTION);
onCreate(db);
}
//insert patient data
public boolean insertPatientData(String fname, String sname, String pps, String dob, String address, String patienttype, String patientmedcon, String caringid) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put(COL_PATIENT_FNAME, fname);
contentValues1.put(COL_PATIENT_SNAME, sname);
contentValues1.put(COL_PATIENT_PPS, pps);
contentValues1.put(COL_PATIENT_DOB, dob);
contentValues1.put(COL_PATIENT_ADDRESS, address);
contentValues1.put(COL_PATIENT_TYPE, patienttype);
contentValues1.put(COL_PATIENT_MEDCOND,patientmedcon);
contentValues1.put(COL_PATIENT_CARINGID, caringid);
long result= db.insert(TABLE_PATIENT,null, contentValues1);
if (result == 1)
return false;
else
return true;
}
//insert prescription data
public boolean insertData(String patientid, String date, String drugname, String concentration,String dosage, String preparation, String startdate, String enddate, String doctorid) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues2 = new ContentValues();
contentValues2.put(COL_PRESCRIPTION__PATIENTID, patientid);
contentValues2.put(COL_PRESCRIPTION__DATE, date);
contentValues2.put(COL_PRESCRIPTION__DRUGNAME, drugname);
contentValues2.put(COL_PRESCRIPTION__CONCENTRATION, concentration);
contentValues2.put(COL_PRESCRIPTION__DOSAGE, dosage);
contentValues2.put(COL_PRESCRIPTION__PREPARATION, preparation);
contentValues2.put(COL_PRESCRIPTION__STARTDATE, startdate);
contentValues2.put(COL_PRESCRIPTION__ENDDATE, enddate);
contentValues2.put(COL_PRESCRIPTION__DOCTORID, doctorid);
long result= db.insert(TABLE_PRESCRIPTION,null, contentValues2);
if (result == 1)
return false;
else
return true;
//END
}
//Coding with mitch tutorial
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_PRESCRIPTION, null);
return data;
}
}
You should not be trying to open the database (using this.getReadableDatabase or this.getWritableDatabase) in the onCreate method as at this stage a getWritableDatabase is underway and as such you will get an java.lang.IllegalStateException: getDatabase called recursively.
That is when you get an instance of the DatabaseHelper, the database is not created or opened. It's not until you invoke getWritableDatabase (implicitly (e.g. via an insert) or explicitly) that an attempt is made to open the database and create it if it doesn't already exist. Thus calling get????ableDatabase will be a recursion since it is already getting the database.
I tried changing the database version number from 1 to 2 however this
made my app crash.
As onUpgrade is also invoked when getting the database, it calling onCreate also fails because of the recursion.
As such change the onCreate method to be :-
#Override
public void onCreate (SQLiteDatabase db) {
String patienttable = "CREATE TABLE " + TABLE_PATIENT + "(PATID INTEGER PRIMARY KEY AUTOINCREMENT, FNAME TEXT, SNAME TEXT, PPS TEXT, DOB TEXT, ADDRESS TEXT, PATIENTTYPE TEXT, PATIENTMEDCON TEXT, CARINGID INTEGER)";
String prescriptiontable = "CREATE TABLE " + TABLE_PRESCRIPTION + "(PRESCRIPTIONID INTEGER PRIMARY KEY AUTOINCREMENT, PATIENTID INTEGER, DATE TEXT, DRUGNAME TEXT, CONCENTRATION TEXT, DOSAGE TEXT, PREPARATION TEXT, STARTDATE TEXT, ENDDATE TEXT, DOCTORID INTEGER)";
db.execSQL(patienttable);
db.execSQL(prescriptiontable);
//this.getReadableDatabase(); //<<<<< MUST NOT BE USED In onCreate
//this.getWritableDatabase(); //<<<<< MUST NOT BE USED in onCreate
}
Of cousre you would likely delete the lines rather than comment them out.
Before running the App it would be best to uninstall the App (this should overcome the initial issue which is due to onCreate only being called once for the lifetime of the database).
As such, if you change the schema, when developing the App, you would typicaly delete the database (uninstalling the App or deleting the App's data will do this).
Making the amendments above to the onCreate method would also allow increasing the version number to work as it calls onCreat.
P.S. checking the return value from the insert for 1 will only return true for the very fist insert, as only at that stage is the return value (the rowid (PATID and PRESCRIPTIONID will be aliases of the rowid)), for subsquent inserts the value be will be greater than 1.
I'd suggest that instead of using :-
long result= db.insert(.........);
if (result == 1)
return false;
else
return true;
That you use :-
return (db.insert(......) > 0);
or
return (db.insert(......) != -1)
(-1 indicates that no row was inserted).
TESTING
The above has been tested using you Database helper with rows being succesfully inserted.
The following code in an activity was used for the test :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDBHlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHlpr = new DatabaseHelper(this);
mDBHlpr.insertData("1234567890","2018-01-01","X","50","4 times daily","Shake","2018-01-01","2018-03-01","DOC001");
mDBHlpr.insertPatientData("Fred","Bloggs","pps001","1974-01-01","1 Somewhere Street","X","MECON001","001");
Cursor csr = mDBHlpr.getListContents();
while (csr.moveToNext()) {
Log.d("SCRIPTINFO","ID is " +csr.getString(csr.getColumnIndex(DatabaseHelper.COL_PRESCRIPTION_ID)));
}
csr = mDBHlpr.getWritableDatabase().query(DatabaseHelper.TABLE_PATIENT,null,null,null,null,null,null);
while (csr.moveToNext()) {
Log.d("PATIENTINFO","Patient Name is " + csr.getString(csr.getColumnIndex(DatabaseHelper.COL_PATIENT_FNAME)));
}
}
}
The result (from an initial run after uninstalling the App) was :-
2019-11-18 12:57:10.362 D/SCRIPTINFO: ID is 1
2019-11-18 12:57:10.363 D/PATIENTINFO: Patient Name isFred
Okay so I've followed a few tutorials and created a databaseHelper class after following a tutorial. However I don't fully understand or get how to actually create the database in the first place.
In my mainActivity I've added this to my onCreate but it doesn't create any database or at least nothing shows up in my Android Device Monitor.
Basically how do I actually get the database to be created?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
dbHelper = new databaseHelper(this);
}
Java
public class databaseHelper extends SQLiteOpenHelper {
static final String DATABASEHELPER = "DATABASE HELPER";
static final String dbName="chefs";
//User Table Fields
static final String userTable="user";
static final String userColID="userID";
static final String userColName="firstName";
static final String userColLast="lastName";
static final String userColDOB="DOB";
static final String userColGend="gender";
static final String userColAddr="address";
static final String userColPost="postcode";
static final String userColBio="bio";
static final String userColUser="username";
static final String userColEmail="email";
static final String userColPass="password";
static final String userColPic="picture";
static final String userColLastLog="lastlogin";
static final String userColLastLogIP="lastloginIP";
static final String userColRegisteredIP="registeredIP";
static final String userColCreatedOn="createdOn";
//Recipe Table Fields
static final String recipeTable="recipe";
static final String recipeColID="recipeID";
static final String recipeColName="name";
static final String recipeColCate="category";
static final String recipeColDesc="description";
static final String recipeColUserID="user_userID";
//Ingredient Table Fields
static final String ingredientTable="ingredient";
static final String ingredientColID="ingredientID";
static final String ingredientColRecipeID="recipe_recipeID";
static final String ingredientColName="name";
static final String ingredientColAmount="amount";
static final String ingredientColUnit="unit";
//Step Table Fields
static final String stepTable="step";
static final String stepColID="stepID";
static final String stepColRecipeID="recipe_recipeID";
static final String stepColNumber="stepNumber";
static final String stepColDesc="description";
public databaseHelper(Context context) {
super(context, dbName, null,1);
Log.d(DATABASEHELPER, "Database Created");
}
#Override
public void onCreate(SQLiteDatabase db) {
// Creating User Table
db.execSQL("CREATE TABLE "+userTable+" ("+userColID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+userColName+" TEXT, "+userColLast+" TEXT, "
+userColDOB+" NUMERIC, "+userColGend+" TEXT, "+userColAddr+" TEXT, "+userColPost+" TEXT, "+userColBio+" TEXT, "
+userColUser+" TEXT, "+userColEmail+" TEXT, "+userColPass+" TEXT, "+userColPic+" TEXT, "+userColLastLog+" NUMERIC, "
+userColLastLogIP+" TEXT, "+userColRegisteredIP+" TEXT, "+userColCreatedOn+" NUMERIC)");
// Creating Recipe Table
db.execSQL("CREATE TABLE "+recipeTable+" ("+recipeColID+" INTEGER AUTOINCREMENT, "+recipeColName+" INTEGER, "+recipeColCate+" TEXT, "
+recipeColDesc+" TEXT, "+recipeColUserID+" INTEGER");
// Creating Ingredient Table
db.execSQL("CREATE TABLE "+ingredientTable+" ("+ingredientColID+" INTEGER AUTOINCREMENT, "+ingredientColRecipeID+" TEXT ,"+ingredientColName+" TEXT, "
+ingredientColAmount+" INTEGER, "+ingredientColUnit+" TEXT");
db.execSQL("CREATE TABLE "+stepTable+" ("+stepColID+" INTEGER AUTOINCREMENT, "+stepColRecipeID+" INTEGER, "+stepColNumber+" INTEGER, "
+stepColDesc+" TEXT");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(DATABASEHELPER, "Upgrading Database");
}
}
Any help is appreciated.
As given in the android documentation, the database is not actually created or opened until one of getWritableDatabase() or getReadableDatabase() is called.
Link: http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
Here is my SQLiteOpenHelper class :
public class MySQLiteHelper extends SQLiteOpenHelper {
...
//all the code
SQLiteDatabase db;
String url;
String title;
String init_price;
String cur_price;
byte[] image;
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "ProductsDB";
// Products table name
private static final String TABLE_NAME = "products";
// Products Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_URL = "url";
private static final String KEY_TITLE = "title";
private static final String KEY_INIT_PRICE = "init_price";
private static final String KEY_CUR_PRICE = "cur_price";
private static final String KEY_IMAGE = "image";
private static final String[] COLUMNS = {KEY_ID, KEY_URL, KEY_TITLE, KEY_INIT_PRICE,KEY_CUR_PRICE, KEY_IMAGE};
//An array of database
String[][] table = new String[10][5];
byte[][] images = new byte[10][1];
int len = 0; //no.of rows in the table
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
// SQL statement to create a products table
String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_NAME + " ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT, " +
"title TEXT, " +
"init_price TEXT," +
"cur_price TEXT," +
"image BLOB" +
" );";
// create products table
db.execSQL(CREATE_PRODUCTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
// Create tables again
onCreate(db);
}
void read() {
int i = 0;
// 1. build the query
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
table[i][0] = cursor.getString(0);
table[i][1] = cursor.getString(1);
table[i][2] = cursor.getString(2);
table[i][3] = cursor.getString(3);
table[i][4] = cursor.getString(4);
images[i] = cursor.getBlob(5);
i++;
} while (cursor.moveToNext());
}
}
String[][] getTable() {
return table;
}
}
My List class :
Here in this class, I want to create a listview from the values in the database.
How do I access those values?
List.java :
public class List extends Activity {
MySQLiteHelper obj = new MySQLiteHelper(this);
// I have all the methods to get required data from database.
// But I'm unable to call those methods directly. Why?
// I actually can access those methods from a service.
// But now, I'm getting "Cannot resolve method" error.
MySQLiteHelper obj = new MySQLiteHelper(this);
obj.getLength(); //I'm getting error here
obj.read(); // It says that it cannot resolve the method.
}
Why is that? I put the same code in a thread inside List.java class and then I'm able to access those methods.
MySQLiteHelper has no method for getLength() but that is ok. (more on this at the end)
the read() method is not public, and it really does nothing other than populate the table member/field of the MySQLiteHelper class.
You aren't leveraging the getTable() method you created (which also is not public).
lets go ahead and make getTable public (consider renaming this as it is really returning table data and not an actual database table, up to you tho), and anytime it is called, lets also call read() anytime this method is called
// renamed from getTable
public String[][] getTableData() {
read();
return table;
}
With this small modification, your usage should look something like this:
MySQLiteHelper obj = new MySQLiteHelper(this);
String[][] tabledata = obj.getTableData();
// get the Length (no getLength() method needed as we will poll the tabledata length property.
int length = tabledata.length;
I'm going to assume (and I apologize if I'm incorrect) that this your first crack at doing android databases. So it might be good to read a tutorial like this one:
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
HTHS :)
I have a set of constant like this:
private static final transient String NOME_FILE_RC = "blabla1.xml";
private static final transient String NOME_FILE_NS = "blabla2.xml";
private static final transient String NOME_FILE_NE = "blabla3.xml";
private static final transient String NOME_FILE_DT = "blabla4.xml";
private static final transient String NOME_FILE_MC = "blabla5.xml";
private static final transient String NOME_FILE_NR = "blabla6.xml";
I want to replace FILE with DOCUMENT in eclipse
I set find with \w{4}_(FILE)_\w{2}
I know that $1 catches FILE string but I don't know how to replace it with DOCUMENT.
Use (\w{4}_)FILE(_\w{2}) instead and replace with $1DOCUMENT$2.
capture the rest of the string
(.*?)FILE(.*)
and replace with
$1DOCUMENT$2
Hi all i am writing simple app to train my ContentProvider skills .So i wrote Contract class that specifies all the meta data for all the tale her it is
public class StoreContract {
public static String AUTHORITY = "com.ura.store.intentProvider";
public static String DATABASE_NAME = "Store.db";
public static class Customer{
public static final String TABLE_NAME ="tblCustomers";
public static final String COLUMN_AUTO_ID = "_id";
public static final String COLUMN_NAME="First Name";
public static final String COLUMN_LAST_NAME = "Last name";
public static final String COLUMN_PHONE_NUMBER = "Phone number";
public static final String CREAT_STRING = "create table "+TABLE_NAME+
" ( "+COLUMN_AUTO_ID+" INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLUMN_NAME+" TEXT , "
+COLUMN_LAST_NAME+" TEXT , "
+COLUMN_PHONE_NUMBER+" TEXT);";
}
static class Seller{
public static final String TABLE_NAME = "tblEmployes";
public static final String COLUMN_AUTO_ID = "_id";
public static final String COLUMN_NAME="First Name";
public static final String COLUMN_LAST_NAME = "Last name";
public static final String COLUMN_EMPLOY_TYPE = "Type";
public static final String CREAT_STRING = "create table "+TABLE_NAME+
" ( "+COLUMN_AUTO_ID+" INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLUMN_NAME+" TEXT , "
+COLUMN_LAST_NAME+" TEXT , "
+COLUMN_EMPLOY_TYPE+" TEXT);";
}
static class Buy{
public static final String TABLE_NAME = "tblBuys";
public static final String COLUMN_AUTO_ID = "_id";
public static final String COLUMN_CUSTOMER_ID = "Customer";
public static final String COLUMN_SELLER_ID = "Seller";
public static final String COLUMN_INFO = "Info";
public static final String COLUMN_PRICE = "Price";
public static final String CREAT_STRING = "create table "+TABLE_NAME+
" ( "+COLUMN_AUTO_ID+" INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLUMN_CUSTOMER_ID+" TEXT, "
+COLUMN_SELLER_ID+" TEXT , "
+COLUMN_INFO+" TEXT "
+COLUMN_PRICE+" REAL"
+"FOREIGN KEY("+COLUMN_CUSTOMER_ID+") REFERENCES "+Customer.TABLE_NAME+"("+Customer.COLUMN_AUTO_ID+")"
+"FOREIGN_KEY("+COLUMN_SELLER_ID+") REFERENCES "+Seller.COLUMN_AUTO_ID+"("+Seller.COLUMN_AUTO_ID+")";
}
public static void main(String []args){
System.out.println(StoreContract.Customer.CREAT_STRING);
}
Notice the main method i wrote it to see how my Table creation String looks like of course the method didn't work probably be cause it is Android Project .So my question is simple what do you suggest to do in such cases i mean a except of copying and passing all class in to other project i am pretty sure that there is a standard solution for this stuff some unit-test or something.
Thank :)
The Android equivalent of the main method is onCreate() in Activities (and pretty much everywhere else)
Unlike pure java applications, Android apps will not call main() as their starting point, but instead the onCreate() method of their top level activity. This activity needs to be specified by name through <action android:name="android.intent.action.MAIN" /> in the manifest section defining that activity.
To go about this, you would make a class that inherits from activity, add the code from your current main method in the onCreate() method, and access the class you have currently from there.
Also, there is a lot more to how android handles the lifespan of activities, and the method calls in them. I recommend this link as a starting point to look into how android code runs.