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
Related
I have one EditText in my application, which is used for storing its content as HTML to a SQLite DB.
When I put an apostrophe in the text (e.g. Ajinkya's application), the EditText data is not getting inserted into the database because it treats the first apostrophe as a query break.
I tried many different suggested solutions here, but without success. For example I replaced "'" with "\'" but still the code (see next code block) is not replacing that symbol after converting to html.
String NotesContent = Html.toHtml(notes_content.getText());
String Notestitle = Html.toHtml(notes_title.getText());
if (Notestitle.contains("'")) {
Notestitle = Notestitle.replace("'", "\'");
}
if (NotesContent.contains("'")) {
NotesContent = NotesContent.replace("'", "\'");
}
So I tried replacing "'" with "\'" first when I save the EditText data to a string variable to then convert it into HTML (see next code block). But the function HTML.toHTML() is not accepting string variables.
String NotesContent = notes_content.getText().toString();
String Notestitle = notes_title.getText().toString();
if (Notestitle.contains("'")) {
Notestitle = Notestitle.replace("'", "\'");
}
if (NotesContent.contains("'")) {
NotesContent = NotesContent.replace("'", "\'");
}
Notestitle = Html.toHtml(Notestitle); // does not accept Strings!
Please help me in solving this issue.
If you use the insert conveniece method this will escape the string.
As an example (using When I put an apostrophe in the text (e.g. Ajinkya's application), the EditText data is not getting inserted into the database because it treats the first apostrophe as a query break. (note with some HTML added) as the data to store and retrieve) :-
The Database Helper DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TABLE = "htmlstore";
public static final String IDCOLUMN = BaseColumns._ID;
public static final String HTMLCOLUMN = "html";
SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_htmlstore_table = "CREATE TABLE IF NOT EXISTS " + TABLE + "(" +
IDCOLUMN + " INTEGER PRIMARY KEY," +
HTMLCOLUMN + " TEXT" +
")";
db.execSQL(crt_htmlstore_table);
}
public long insert(String html) {
ContentValues cv = new ContentValues();
cv.put(HTMLCOLUMN,html);
return db.insert(TABLE,null,cv); //<<<< does the escaping for you
}
public String getHTML(long id) {
String rv = "";
Cursor csr = db.query(TABLE,new String[]{HTMLCOLUMN},IDCOLUMN+"=?",new String[]{String.valueOf(id)},null,null,null);
if (csr.moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(HTMLCOLUMN));
}
csr.close();
return rv;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
The invoking activity MainActivity.java :-
public class MainActivity extends AppCompatActivity {
TextView NotesTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NotesTitle = this.findViewById(R.id.notesview);
DatabaseHelper databaseHelper = new DatabaseHelper(this);
// Inserts into the database
databaseHelper.insert(
"When I put an apostrophe in the text <b>(e.g. Ajinkya's application)</b>, " + //<<<< BOLD ADDED
"the EditText data is not getting inserted into the database " +
"<i><strong>because it treats the first apostrophe as a query break</strong></>." //<<<< Italic String ADDED
);
// Extracts from the database and sets the notesview TextView with the extracted text from the HTML (if any)
NotesTitle.setText(Html.fromHtml(databaseHelper.getHTML(1L)));
}
}
The result :-
I am creating an app which manages ingredients. I want to create an SQLite database which will save all the ingredients which a user enters when they click the save button. However, for some reason my data won't save to the SQLite database. I cannot see what is wrong with the code at all.
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper
{
private static final String tag = "Database Helper";
private static final String TABLE_NAME = "products_registered";
private static final String col1 = "Name";
private static final String col2 = "Weight";
private static final String col3 = "Price";
private static final String col4 = "Description";
#Override
public void onCreate(SQLiteDatabase db)
{
String createTable = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
" (_id INTEGER PRIMARY KEY AUTOINCREMENT," +
col1 + " TEXT NOT NULL," +
col2 + " DOUBLE NOT NULL," +
col3 + " DOUBLE NOT NULL," +
col4 + " TEXT);";
db.execSQL(createTable);
}
public DatabaseHelper(Context context)
{
super(context, TABLE_NAME, null, 1);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int j)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item1, String item2, String item3, String item4)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col1, item1);
contentValues.put(col2, item2);
contentValues.put(col3, item3);
contentValues.put(col4, item4);
Log.d(tag,"Adding name " + item1 + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
db.close();
if(result == -1)
{
return false;
}
else
{
return true;
}
}
}
The Register Product Activity
public class RegisterProduct extends AppCompatActivity
{
DatabaseHelper databaseHelper;
private Button saveProductButton;
private EditText productName;
private EditText productWeight;
private EditText productPrice;
private EditText productDescription;
DatabaseHelper mDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_product);
saveProductButton = (Button) findViewById(R.id.saveButton);
productName = (EditText) findViewById(R.id.enterName);
productWeight = (EditText) findViewById(R.id.enterWeight);
productPrice = (EditText) findViewById(R.id.enterPrice);
productDescription = (EditText) findViewById(R.id.enterDescription);
mDatabaseHelper = new DatabaseHelper(this);
try
{
saveProductButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String nameEntered = productName.getText().toString();
String weightEntered = productWeight.getText().toString();
String priceEntered = productPrice.getText().toString();
String descriptionEntered = productDescription.getText().toString();
addData(nameEntered, weightEntered, priceEntered, descriptionEntered);
productName.setText("");
}
});
}
finally
{
mDatabaseHelper.close();
}
}
public void addData(String newEntry1, String newEntry2, String newEntry3, String newEntry4)
{
mDatabaseHelper.addData(newEntry1, newEntry2, newEntry3, newEntry4);
}
I created a seperate class to create the database and table itself and then created the activity where I called the methods to save the data input in the activity displayed below.
Image of activity display
Your issue is most likely that you have changed the structure/schema of the database probably adding a column since running the App.
Typically you would get an SQLite exception when running the App indicating that the column was not found. However, as you have wrapped the addData in a try/finally construct the exception has been suppressed thus it appears that all is fine as the App doesn't crash or show anything in the log.
Wrapping database code in try constructs and trapping errors, as you have found can be confusing and it is suggested that you don't.
The reason why changing the schema/structure within the code for the onCreate method (the likely root cause of the issue), is that the onCreate method ONLY RUNS automatically when the database is created.
If the schema/structure of the database is changed then you need some way of either forcing the structure change or when developing an App, as the underlying data, should not need to be saved, then the easiest way is to delete the database and then rerun the App.
The database can be deleted by either deleting the App's data or by uninstalling the App (noting that any existing data will be lost).
An alternative, is to DROP the respective table(s) and recreate them. Frequently the onUpgrade method will written to do this. If this is the case (it is in your case) then another way of changing the structure is to trigger the onUpgrage method by increasing the version number pass to the SQLiteOpenHelper constructor (the super call). In your case you could change super(context, TABLE_NAME, null, 1); to be super(context, TABLE_NAME, null, 2);
After deleting the database or increasing the version number (preferably removing the try/finally construct from around the call to addData) and reunning the App, it may well just work. If not then the log should show any exceptions and problems can then be pinpointed.
Not too sure how to explain this but will give it my best.
I have created a database within my Android project:
public class FootySortItDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "FootySortItDatabase";
private static final int DATABASE_VERSION = 1;
public FootySortItDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_PLAYER_TABLE = "CREATE TABLE " +
PlayerDetails.PlayerTableEntry.TABLE_NAME + "(" +
PlayerDetails.PlayerTableEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
PlayerDetails.PlayerTableEntry.COLUMN_PLAYER_NAME + " TEXT NOT NULL, " +
PlayerDetails.PlayerTableEntry.COLUMN_PLAYER_NUMBER + " TEXT NOT NULL, " +
PlayerDetails.PlayerTableEntry.COLUMN_IS_PLAYING + " INTEGER NOT NULL " +
");";
db.execSQL(SQL_CREATE_PLAYER_TABLE);
}
I have set the following contract:
public static final class PlayerTableEntry implements BaseColumns{
public static final String TABLE_NAME = "playerTable";
public static final String COLUMN_PLAYER_NAME = "playerName";
public static final String COLUMN_PLAYER_NUMBER = "playerNumber";
public static final String COLUMN_IS_PLAYING = "isPlaying";
}
I call a method which passes a DB and an array of details:
private SQLiteDatabase playerDatabase;
private Cursor getAllPlayers(){
playerDatabase = ComposeMessage.addPlayerToTheDatabase(playerDatabase, playerDataSet);
return playerDatabase.query(PlayerDetails.PlayerTableEntry.TABLE_NAME,
null,null,null,
null,null,null);
}
public static SQLiteDatabase addPlayerToTheDatabase(SQLiteDatabase playerDatabase, ArrayList<PlayerDetails> listGame) {
for (PlayerDetails i : listGame) {
ContentValues cv = new ContentValues();
cv.put(PlayerDetails.PlayerTableEntry.COLUMN_PLAYER_NAME, i.name);
cv.put(PlayerDetails.PlayerTableEntry.COLUMN_PLAYER_NUMBER, i.number);
playerDatabase.insert(PlayerDetails.PlayerTableEntry.TABLE_NAME, null, cv);
}
return playerDatabase;
}
Then, I pass the cursor into my RecyclerView :
public PlayerListRecyclerViewAdapter(Context context, Cursor cursor, ArrayList<PlayerDetails> aPlayerList,
int count) {
playerDataSet = aPlayerList;
this.pCursor = cursor;
pContext = context;
But my pCursor = 0. Which means that their are no rows in the table??
Via the terminal I use adb to navigate to the database, use SQLite3 on the DB to search the data of the table but it does not return anything:
sqlite> .tables
android_metadata playerTable
sqlite> select * from playerTable;
sqlite>
when I debug I can see during the insert part, that i.name and i.number has data to it and "it looks to be inserting it" but then why is cursor 0 and when I search the data, why is it not returning anything?
Not sure how to over come this...
There are 3 columns in the table. None of them can be null. When you write into the database, you are writing to 2 columns instead of 3. As a result, the insertion will fail.
To create a database, I recommend Schematic and use Stetho for debugging.
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 get this error when adding data to a table in my Sqlite database.
12-21 17:31:19.345: E/SQLiteLog(24127): (1) no such table: accessory_data
12-21 17:31:19.345: E/DB ERROR(24127): android.database.sqlite.SQLiteException:
no such table: accessory_data (code 1): ,
while compiling: SELECT aid, name, image, url, price
FROM accessory_data
Note that the Database is previously created by another method in order to add data to another table. What I'm doing here is simply adding data to a different table in the same database. Is that the root of the problem?
DBOperations Class:
public class DBOps extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "jezzadb";
public String CREATE_ACC_QUERY = "CREATE TABLE " + AccessoriesTableInfo.TABLE_NAME + " (" + AccessoriesTableInfo.AID + " VARCHAR, " +
AccessoriesTableInfo.NAME + " VARCHAR, " + AccessoriesTableInfo.IMAGE + " VARCHAR, " + AccessoriesTableInfo.PRICE + " VARCHAR, " +
AccessoriesTableInfo.URL + " VARCHAR);";
public DBOps(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_ACC_QUERY);
}
public void insertAccessories(DBOps dop, Accessories a)
{
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(AccessoriesTableInfo.AID, a.ID);
cv.put(AccessoriesTableInfo.NAME, a.Name);
cv.put(AccessoriesTableInfo.URL, a.URL);
cv.put(AccessoriesTableInfo.IMAGE, a.Image);
cv.put(AccessoriesTableInfo.PRICE, a.PRICE);
SQ.insert(AccessoriesTableInfo.TABLE_NAME, null, cv);
Log.d("Database Operations", "Inserted Accessories succesfully!");
}
public ArrayList<Accessories> getAccessories(DBOps dop)
{
ArrayList<Accessories> arr = new ArrayList<Accessories>();
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] columns = {AccessoriesTableInfo.AID,AccessoriesTableInfo.NAME,AccessoriesTableInfo.IMAGE,AccessoriesTableInfo.URL,
AccessoriesTableInfo.PRICE};
Cursor CR = SQ.query(AccessoriesTableInfo.TABLE_NAME, columns, null, null, null, null, null);
CR.moveToFirst();
for(int i=0;i<CR.getCount();i++)
{
while (!CR.isAfterLast()) {
Accessories a= new Accessories();
a.ID = CR.getString(0);
a.Name = CR.getString(1);
a.URL = CR.getString(2);
a.Image = CR.getString(3);
a.PRICE = CR.getString(4);
arr.add(a);
CR.moveToNext();
}
CR.close();
break;
}
return arr;
}
AccessoriesTableInfo Class:
public class AccessoriesTableData {
public AccessoriesTableData()
{
}
public static abstract class AccessoriesTableInfo implements BaseColumns
{
public static final String AID = "aid";
public static final String NAME = "name";
public static final String IMAGE = "image";
public static final String URL = "url";
public static final String PRICE = "price";
public static final String TABLE_NAME = "accessory_data";
}
}
What am I doing wrong?
Note that the Database is previously created by another method in order to add data to another table. What I'm doing here is simply adding data to a different table in the same database. Is that the root of the problem?
Yes, that's the problem. Use only one SQLiteOpenHelper subclass per database file.
What happens is that the database file with the requested version 1 already exists, so no database helper lifecycle callbacks like onCreate() or onUpgrade() get invoked.
Further reading: When is SQLiteOpenHelper onCreate() / onUpgrade() run?