Android won't save data entered to the SQLite database - java

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.

Related

how to use string variable in HTML.toHTML()?

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 :-

Android - SQLite issue with adding more tables to database

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

Android Studio, Java and SQLite issue creating a database

The issue im having is when I attempt to execute the query it doesn't have access to the execSQL part of the command, ive been stuck on this for around an hour.
package com.androstock.myweatherapp;
import android.database.sqlite.SQLiteDatabase;
import static android.database.sqlite.SQLiteDatabase.openOrCreateDatabase;
public class Database {
SQLiteDatabase mydatabase = openOrCreateDatabase("database.db", null);
public void onCreate() {
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
}
}
If somebody would be able to shed some light on where im going wrong with this that would be great thanks in advance
You are getting a little mixed up with your code.
I'd suggest making the Database class extend (be a subclass of) the SQLiteOpenHelper class and overriding the onCreate method to create the tables in the database.
e.g.
public class Database extends SQLiteOpenHelper {
// define constants so all names can be defined just once
public static final String DBNAME = "database.db"; // The database name
public static final int DBVERSION = 1; // The version (increase it to invoke the onUpgrade method to alter the DB structure)
public static final String TABLE_TUTORIALSPOINT = "tutorialspoint"; // The table name
public static final String COLUMN_USERNAME = "username"; // Columns
public static final String COLUMN_PASSWORD = "password";
SQLiteDatabase mDB; //Variable to hold the SqliteDatabase
//The Database class constructor
public Database(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase(); //<<<<<<<<<< store the Sqlite Database opening it, (if it doesn't exist then onCreate will be called)
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_tutorialspoint_table = "CREATE TABLE IF NOT EXISTS " + TABLE_TUTORIALSPOINT + "(" +
COLUMN_USERNAME + " VARCHAR, " +
COLUMN_PASSWORD + " VARCHAR" +
")";
db.execSQL(crt_tutorialspoint_table); // Create the table
// Preapre to insert a row using the SQLiteDatabase convenience insert method
ContentValues cv = new ContentValues();
cv.put(COLUMN_USERNAME,"admin");
cv.put(COLUMN_PASSWORD,"admin");
db.insert(TABLE_TUTORIALSPOINT,null,cv);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
}
You could then use this in an activity; something like :-
public class MainActivity extends AppCompatActivity {
Database mMYDatabaseHelper; // Declare a Database object called mMyDatabaseHelper <<< Note will be null untill instantiated (constructed)
SQLiteDatabase mMySQliteDatabase; // Declares an SQliteDatabase object again will be null
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mMYDatabaseHelper = new Database(this); // Construct the mMyDatabaseHelper (will create the database an insert the row)
mMySQliteDatabase = mMYDatabaseHelper.getWritableDatabase(); // Set/assign sqlite database from the helper to the SqliteDatabase object
// retrieve the rows in the table into a Cursor so the data can be extracted
// Note how the names are obtained from the constants as setup in the Database class.
Cursor mycursor = mMySQliteDatabase.query(Database.TABLE_TUTORIALSPOINT,null,null,null,null,null,null);
// loop through all rows of the cursor
while (mycursor.moveToNext()) {
String username = mycursor.getString(mycursor.getColumnIndex(Database.COLUMN_USERNAME)); // get the username from the current row
String password = mycursor.getString(mycursor.getColumnIndex(Database.COLUMN_PASSWORD)); // get the password from the current row
Log.d("TABLEINFO", "Row " + String.valueOf(mycursor.getPosition() + 1) + " has a username of " + username + " and a password of " + password);
}
mycursor.close(); // Done with the Cursor so close it
//ALL DONE if there are any rows in the table then there should be some output in the Log.
}
Note typically you would have a method in the the Database class (or elsewhere depedning upon coding conventions) such that returns a Cursor rather than access the database in the activities.
Output in the Log :-
D/TABLEINFO: Row 1 has a username of admin and a password of admin

Data from Database is not being displayed

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.

Android SQLite database sharing across activities

Background info: new to Android, not to Java.
I am writing an app that sends its own messages separately from the default Android sms app. Since my app is not the default, I can't write to Android's provider.sms.outbox, which is absolutely fine. To work around this, I am creating a SQLite database to store my app's outgoing messages (in message objects). I am struggling to find a good, detailed explanation/tutorial on how to create a SQLite database that is available across all of my activities. I only have 2 activities; one that reads the database, and one that reads/writes the database.
I know that I need to create a subclass of the SQLiteOpenHelper, and I have:
public class dbHelper extends SQLiteOpenHelper {
//Database Info
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "outgoingMsgs.db";
public static final String TABLE_MESSAGES = "messages";
//Table Info
public static final String COLUMN_ID = "id";
public static final String COLUMN_SEND_TO_NAME = "send_to_name";
public static final String COLUMN_SEND_TO_NUM = "send_to_num";
public static final String COLUMN_BODY = "msg_body";
public dbHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//table creation...
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_MESSAGES_TABLE = "CREATE TABLE " + TABLE_MESSAGES +
"(" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_SEND_TO_NAME + " TEXT," +
COLUMN_SEND_TO_NUM + " TEXT," + COLUMN_BODY + " TEXT" + ")";
db.execSQL(CREATE_MESSAGES_TABLE);
}
//database version upgrade... destroys old and recreates
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);
onCreate(db);
}
//adds single record
public void addRecord(myMessage msg){
SQLiteDatabase dbase = this.getWritableDatabase();
ContentValues vals = new ContentValues();
//fill vals with appropriate content
vals.put(COLUMN_SEND_TO_NAME, msg.get_name());
vals.put(COLUMN_SEND_TO_NUM, msg.get_number());
vals.put(COLUMN_BODY, msg.getBody());
//insert
dbase.insert(TABLE_MESSAGES, null, vals);
dbase.close();
}
public int getRecordCount(){
String countQuery = "SELECT * FROM " + TABLE_MESSAGES;
SQLiteDatabase dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
//deletes a single record
public void deleteRecord(myMessage msg){
SQLiteDatabase dbase = this.getWritableDatabase();
dbase.delete(TABLE_MESSAGES, COLUMN_ID + " = ?",
new String[] { String.valueOf(msg.get_id()) });
dbase.close();
}
}
Now, my problem is that I cannot figure out where (in which Activity or even in an Activity) or how I should create the instance of my dbHelper to make it available across my 2 activities. I know the singleton pattern is used frequently and the ContentProvider method is preferred. I don't feel that I'm ready to use ContentProviders with my very limited Android knowledge, so I would like to explore the singleton method. Can anyone please help me through this process?
how I should create the instance of my dbHelper to make it available
across my 2 activities
For what? You can just create a new instance for each Activity, since they use the very same database (outgoingMsgs.db).
For example, if you call addRecord in Activity A and use the different instance of dbHelper in Activity B to call getRecordCount, the inserted data will be selected.
You can use an Abstract class like this.
public abstract class DBAbstract extends Activity {
private DBHelper mDBHelper;
protected DBHelper getHelper(){
if(mDBHelper == null){
mDBHelper = OpenHelperManager.getHelper(this, DBHelper.class);
}
return mDBHelper;
}
protected int getDBVersion(){
return mDBHelper.getDatabaseVersion();
}
#Override
protected void onDestroy(){
super.onDestroy();
if(mDBHelper != null){
OpenHelperManager.releaseHelper();
mDBHelper = null;
}
}
And use it in your new activities.
public class YourActivity extends DBAbstract
I'm using this and it's working perfectly

Categories

Resources