Updating Information in SQLiteDatabase - java

I'm trying to update the informations on my listview by using sqlitedatabase, so in my update class I'm getting an error which is here on the pic http://prntscr.com/djbe3i
Here's the dbhelper method code:
public int updateInformation(String old_name, String new_name,String old_hours, String new_hours, String old_department,String new_department,SQLiteDatabase sqLiteDatabase) {
ContentValues contentValues = new ContentValues();
contentValues.put(UserContract.NewUserInfo.Name,new_name);
contentValues.put(UserContract.NewUserInfo.RenderedHours,new_hours);
contentValues.put(UserContract.NewUserInfo.Department,new_department);
String selection = UserContract.NewUserInfo.Name + " LIKE ?";
String[] selection_args = {old_name};
int count = sqLiteDatabase.update(UserContract.NewUserInfo.TABLE_NAME,contentValues,selection,selection_args);
return count;
}
Update class code:
public void updateContact(View view) {
userDBHelper = new UserDBHelper(getApplicationContext());
sqLiteDatabase = userDBHelper.getWritableDatabase();
String name,hours,department;
name = new_name.getText().toString();
hours = new_hours.getText().toString();
department = new_department.getText().toString();
int count = userDBHelper.updateInformation(search_id,NewName,NewHours,NewDepartment,sqLiteDatabase);
}
}
EDIT: I changed the code into:
public void updateContact(View view) {
userDBHelper = new UserDBHelper(getApplicationContext());
sqLiteDatabase = userDBHelper.getWritableDatabase();
String name,hours,department;
name = new_name.getText().toString();
hours = new_hours.getText().toString();
department = new_department.getText().toString();
int count = userDBHelper.updateInformation(search,name,hours,department,sqLiteDatabase);
}
and I'm still getting error I don't understand.
2ND EDIT: I get it now okay, I just mistyped the string and the arguments that i needed for the update contact i replaced the code into:
int count = userDBHelper.updateInformation(search_id,name,hours,department,sqLiteDatabase);
DBHelper.updateInformation code:
public int updateInformation(String old_name, String new_name, String new_hours,String new_department,SQLiteDatabase sqLiteDatabase)

I got it now my parameters doesn't match and I fixed it by changing the code into:
public int updateInformation(String old_name, String new_name, String new_hours,String new_department,SQLiteDatabase sqLiteDatabase)
Then changing the code in update class:
int count = userDBHelper.updateInformation(search_id,name,hours,department,sqLiteDatabase);

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

Retrieving data from sqlite into a texxtview/edittext

Its not compiling and i have no idea why... New to sqlite and tried to follow some question's answer on stack overflow but not able to figure it out. Modal class is MainDataHelper
Code
MainDataHelper myDatabaseHelper = new MainDataHelper(getActivity());
myDatabaseHelper.openDataBase();
String text = myDatabaseHelper.getMostMessagesSent(); //this is the method to query
myDatabaseHelper.close();
mMostMessagesSent.setText(text);
mMostMessagesSent.setTextColor(Color.WHITE);
Helper
public class MainDataHelper extends Activity {
private int TotalMessagesSent;
private int TotalMessagesRecieved;
private int TotalMessages;
private String TotalTimeSpent;
private String MostMessagesSent;
private String MostMessagesRecieved;
private String MostTexted;
private String MostTimeSpent;
private int QuizTaken;
private int QuizTakers;
private int Reviewed;
private int Reviews;
public MainDataHelper() {
TotalMessagesSent = 0;
TotalMessagesRecieved = 0;
TotalMessages = 0;
TotalTimeSpent = "";
MostMessagesSent = "";
MostMessagesRecieved = "";
MostTexted = "";
MostTimeSpent = "";
QuizTaken = 0;
QuizTakers = 0;
Reviewed = 0;
Reviews = 0;
}
public MainDataHelper( int TotalMessagesSent, int TotalMessagesRecieved, int TotalMessages, String TotalTimeSpent,String MostMessagesSent, String MostMessagesRecieved, String MostTexted, String MostTimeSpent,int QuizTaken, int QuizTakers, int Reviewed, int Reviews) {
TotalMessagesSent = TotalMessagesSent;
TotalMessagesRecieved = TotalMessagesRecieved;
TotalMessages = TotalMessages;
TotalTimeSpent = TotalTimeSpent;
MostMessagesSent = MostMessagesSent;
MostMessagesRecieved = MostMessagesRecieved;
MostTexted = MostTexted;
MostTimeSpent = MostTimeSpent;
QuizTaken = QuizTaken;
QuizTakers = QuizTakers;
Reviewed = Reviewed;
Reviews = Reviews;
}
public int getTotalMessagesSent() {
return TotalMessagesSent;
}
public int getTotalMessagesRecieved() {
return TotalMessagesRecieved;
}
public int getTotalMessages() {
return TotalMessages;
}
public String getTotalTimeSpent() {
return TotalTimeSpent;
}
public String getMostMessagesSent() {
return MostMessagesSent;
}
public String getMostMessagesRecieved() {
return MostMessagesRecieved;
}
public String getMostTexted() {
return MostTexted;
}
public String getMostTimeSpent() {
return MostTimeSpent;
}
public int getQuizTaken() {
return QuizTaken;
}
public int getQuizTakers() {
return QuizTakers;
}
public int getReviewed() {
return Reviewed;
}
public int getReviews() {
return Reviews;
}
public void setTotalMessagesSent(int TotalMessagesSent) {
TotalMessagesSent = TotalMessagesSent;
}
public void setTotalMessagesRecieved(int TotalMessagesRecieved) {
TotalMessagesRecieved = TotalMessagesRecieved;
}
public void setTotalMessages(int TotalMessages) {
TotalMessages = TotalMessages;
}
public void setTotalTimeSpent(String TotalTimeSpent) { TotalTimeSpent = TotalTimeSpent; }
public void setMostMessagesSent(String MostMessagesSent) {
MostMessagesSent = MostMessagesSent;
}
public void setMostMessagesRecieved(String MostMessagesRecieved) {
MostMessagesRecieved = MostMessagesRecieved;
}
public void setMostTexted(String MostTexted) {
MostTexted = MostTexted;
}
public void setMostTimeSpent(String MostTimeSpent) { MostTimeSpent = MostTimeSpent; }
public void setQuizTaken(int QuizTaken) {
QuizTaken = QuizTaken;
}
public void setQuizTakers(int QuizTakers) {
QuizTakers = QuizTakers;
}
public void setReviewed(int Reviewed) { Reviewed = Reviewed; }
public void setReviews(int Reviews) {
Reviews = Reviews;
}
}
......................................................................................................................................................................................................................
It's not compiling due to a few reasons.
First MainDataHelper does not have a constructor that accepts/takes an Activity. MainDataHelper has two constructors one takes no parameters, the other takes 12 parameters. You have to use one of the available constructors when instantiating a MainDataHelper object.
e.g. MainDataHelper myDatabaseHelper = new MainDataHelper(); would compile.
There is no openDatabase method in MainDataHelper, you would either have to add such a method or do away with the line myDatabaseHelper.openDataBase();
There is no close method in MainDataHelper, you would either have to add such a method or do away with the line myDatabaseHelper.close();
Considering that you want to use an SQLite database then you will use a sub-class of the SQLiteOpenHelper class that would be invoked from an Activity or a Fragment (or even many of these).
Before even considering writing a line of code you would need to understand you requirements for the database and have some sort of design (schema). Ignoring that and assuming (for demonstration) that you want a simple database with one table called questions and has one column called question then the following could be such a class (in this case MainDataBaseHelper.java) :-
public class MainDatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASENAME = "question.db"; //<<<<<<<<<< name of the database
public static final int DATABASEVERSION = 1; //<<<<<<<<<< version number of the database
public static final String TABLE_QUESTION = "question"; //<<<<<<<<<< name of the quiz table
public static final String COLUMN_QUESTION_QUESTION = "question";
public MainDatabaseHelper(Context context) {
super(context, DATABASENAME, null, DATABASEVERSION);
}
//<<<<<<<<<< Called ONCE when the database is first created (first time an attempt is made to open if)
#Override
public void onCreate(SQLiteDatabase db) {
String crt_questiontable_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUESTION + "(" +
COLUMN_QUESTION_QUESTION + " TEXT" +
")";
db.execSQL(crt_questiontable_sql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long addQuestion(String question) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_QUESTION_QUESTION,question);
return this.getWritableDatabase().insert(TABLE_QUESTION,null,cv);
}
public Cursor getAllQuestions() {
return this.getWritableDatabase().query(TABLE_QUESTION,null,null,null,null,null,null);
}
}
With the above class existing your code could then be (as a simple example) :-
MainDatabaseHelper myDBHlpr = new MainDatabaseHelper(getActivity()); // Instantiate a MainDatabasehelper object called myDBHlpr
// Add some questions to the questions table
myDBHlpr.addQuestion("This is the first question");
myDBHlpr.addQuestion("This is another question");
myDBHlpr.addQuestion("Yet another question");
// Now get all of the questions
Cursor csr = myDBHlpr.getAllQuestions();
Log.d("DBINFO","There are " + String.valueOf(csr.getCount()) + " questions in the database.");
// Loop through all the questions
while (csr.moveToNext()) {
Log.d("DBINFO",
"Question " +
String.valueOf(csr.getPosition() + 1) +
" is " + csr.getString(csr.getColumnIndex(MainDatabaseHelper.COLUMN_QUESTION_QUESTION))
);
mMostMessagesSent.setText(csr.getString(csr.getColumnIndex(MainDatabaseHelper.COLUMN_QUESTION_QUESTION));
}
csr.close(); //<<<<<<<<<< Should always close Cursor when done with it.
//mMostMessagesSent.setText(text); //<<<<<<<<<< done in the loop through the cursor (for demonstration very likely only the last question will be seen)
mMostMessagesSent.setTextColor(Color.WHITE);
When run (for the first time) the log would then include :-
11-12 20:17:16.345 1376-1376/? D/DBINFO: There are 3 questions in the database.
11-12 20:17:16.345 1376-1376/? D/DBINFO: Question 1 is This is the first question
11-12 20:17:16.345 1376-1376/? D/DBINFO: Question 2 is This is another question
11-12 20:17:16.345 1376-1376/? D/DBINFO: Question 3 is Yet another question
Additionally the last question (which may or may not be the last question added) will be displayed in the TextView.
Note 3 rows would be added to the table each time the above is run.
Note this is purely intended as an introduction/demonstration there is a great deal more that needs to be done, such as designing the database.

Android - How to access already created database from other class?

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

How to write score to SQLite db?

i'm a sqlite newbie. What I'm trying to do...I have a game and after the game ends it stores time result in a double variable named elapsedSeconds. I want to place that result in a db, and than in my dedicated activity show top 10 scores for the user. I have HighScoreDb class where I create a db (i used some code I found online, but I think it'll serve my purpose). Here's the code.
public class HighScoreDb {
private static class HighScoreDbHelper extends SQLiteOpenHelper {
public HighScoreDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(SCORE_TABLE_CREATE);
} catch (SQLException e) {
Log.i("Error", "Error making database");
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + SCORE_TABLE_NAME);
onCreate(db);
}
}
private static final int DATABASE_VERSION = 2;
private static final String SCORE_TABLE_NAME = "highscore";
private static final String SCORE_TABLE_CREATE = "CREATE TABLE "
+ SCORE_TABLE_NAME
+ " (_id INTEGER PRIMARY KEY autoincrement, "
+ "name TEXT NOT NULL, score DOUBLE NOT NULL)";
private static final String DATABASE_NAME = "highscores.db";
// The index (key) column name for use in where clauses.
public static final String KEY_ID = "_id";
// The name and column index of each column in your database.
public static final String KEY_NAME = "name";
public static final String KEY_SCORE = "score";
public static final int NAME_COLUMN = 1;
public static final int NUMBER_COLUMN = 2;
public static final int SCORE_COLUMN = 3;
SQLiteDatabase db;
private final Context ctx;
private final HighScoreDbHelper dbHelper;
public HighScoreDb(Context context) {
this.ctx = context;
ctx.deleteDatabase(SCORE_TABLE_NAME);
dbHelper = new HighScoreDbHelper(context);
db = dbHelper.getWritableDatabase();
}
public void close() {
if (db != null) {
db.close();
}
}
public void createRow(String name, int score) {
ContentValues intialValue = new ContentValues();
intialValue.put("name", name);
intialValue.put("score", score);
db.insertOrThrow(SCORE_TABLE_NAME, null, intialValue);
}
public void deleteRow(long rowId) {
db.delete(SCORE_TABLE_NAME, "_id=" + rowId, null);
}
public Cursor GetAllRows() {
try {
return db.query(SCORE_TABLE_NAME, new String[] { "_id", "name", "score" }, null,
null, null, null, "score DESC");
} catch (SQLException e) {
Log.i("Error on query", e.toString());
return null;
}
}
public void updateRow(long _id, String name, String score) {
ContentValues args = new ContentValues();
args.put("name", name);
args.put("number", score);
db.update(SCORE_TABLE_NAME, args, "_id=" + _id, null);
}
}
From this table I will not need column name, cause I will just have 10 places with scores. How to insert that result in this db after my game ends? I think I know how to read from it, i will do something like this:
HighScoreDb db = new HighScoreDb(this);
Cursor myCursor = db.GetAllRows();
myCursor.moveToPosition(0);
String Row1Value2 = myCursor.getString(2);
myCursor.close();
db.close();
I'm calling it in my games class like this:
HighScoreDb db = new HighScoreDb(this);
I'm not sure i've understand your question... To put some datas in your db, you just have to correctly use your functions wrote below (i assume your class is working fine), for example :
HighScoreDbHelper myDbHelper = new HighScoreDbHelper(yourContext);
myDbHelper.createRow(yourName, yourScore);
This tutorial is a good starter to sqlite concepts : http://www.vogella.com/articles/AndroidSQLite/article.html
The way you open the database is fine.
Instead of using a cursor to get the particular information about a row, make an entity that represents a row inside the table. Create a list of these objects using the information from the Cursor.
public UserScore {
String name;
Integer score; // don't know why you would use double here.
// getters + setters or make it immutable
}
What I would provide is some method inside HighScoreDb to add a new score. For example with signature
public void addScore(UserScore userScore);
Don't think about just adding 10 scores, add every score to the database. Whenever you want the top 10 scores. Just query the last 10 scores descending. Otherwise you are programming a lot of complexity which is easily done with a query. To do this look into top-N queries.
An example writing to the DB inside the helper is like this, (didn't test the SQL but it should be in this form)
this.getWritableDatabase().execSQL("insert into highscore (name, score) values (" + userScore.getName() + "," + userScore.getScore() + ")");

Categories

Resources