I am not getting the add string returned back.
The android app takes input as food item and prints its respective calories.
here is the code for creating table:
public class dietclass extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "diet7.db";
public static final String TABLE_NAME = "Cal_val";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM";
public static final String COL3 = "QUANTITY";
public static final String COL4 = "CALORIES";
public dietclass(Context context) {
super(context,DATABASE_NAME,null,1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM TEXT,QUANTITY VARCHAR,CALORIES INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
}
And here is the code for retrieving data from my activity which is taking item and calories as input.
public class foodcal extends AppCompatActivity {
EditText item;
EditText quantity;
TextView calories;
Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foodcal);
item = (EditText)findViewById(R.id.etitem);
quantity = (EditText)findViewById(R.id.etquantity);
calories = (TextView)findViewById(R.id.calories);
calculate = (Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String itemstr = item.getText().toString();
printDatabase(itemstr);
//String dbstring = dietclass.databaseToString(itemstr);
//calories.setText(String.valueOf(dbstring));
}
});
}
public void printDatabase(String item){
String dbstring = dietclass.databaseToString(this,item);
//String label;
//label = dbstring + "calories";
calories.setText(String.valueOf(dbstring));
}
private static class dietclass extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.example.janhvik.dietapp/databases/";
private static String DB_NAME = "diet7.db";
private static String TABLE_NAME = "Cal_val";
private static SQLiteDatabase myDataBase;
private Context myContext;
public dietclass(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
private static String databaseToString(Context ctx, String item_name) {
String myDbPath;
int cal = 0 ;
String add="";
myDbPath = DB_PATH+DB_NAME;
myDataBase = SQLiteDatabase.openOrCreateDatabase(myDbPath, null);
String query = "SELECT * FROM "+TABLE_NAME+" WHERE ITEM='"+item_name+"'";
Cursor c = myDataBase.rawQuery(query,null);
if(c!= null && c.moveToFirst()){
add = c.getString(c.getColumnIndex("CALORIES"));
c.close();
}
add = add + " calories";
//Toast.makeText(ctx,add, Toast.LENGTH_LONG).show();
return add;
}
I am not getting any error but the code is not taking the value from the select query, can anyone help in this.
I think you've got rather mixed up and complicated matters by appearing to use multiple database helpers/methods to open the same database when you only need to use the database helper. I'm unsure what the exact issue was, there was insufficient code to build an exact replica.
Instead a created simplified working code.
Here's a rewrite/simplification based upon your code :-
First ONE databasehelper class namely dietclass :-
public class dietclass extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "diet7.db";
public static final String TABLE_NAME = "Cal_val";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM";
public static final String COL3 = "QUANTITY";
public static final String COL4 = "CALORIES";
//private static String DB_PATH = "/data/data/com.example.janhvik.dietapp/databases/";
//private static String DB_NAME = "diet7.db";
SQLiteDatabase myDataBase;
private Context myContext;
public dietclass(Context context) {
super(context,DATABASE_NAME,null,1);
myDataBase = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM TEXT,QUANTITY VARCHAR,CALORIES INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
public long insertCal_ValEntry(String item, String quantity, int calories) {
ContentValues cv = new ContentValues();
cv.put(COL2,item);
cv.put(COL3,quantity);
cv.put(COL4,calories);
return myDataBase.insert(TABLE_NAME,null,cv);
}
public String databaseToString(String item_name) {
//String myDbPath;
int cal = 0 ;
String add="";
//myDbPath = DB_PATH+DB_NAME;
//myDataBase = SQLiteDatabase.openOrCreateDatabase(myDbPath, null);
String query = "SELECT * FROM "+TABLE_NAME+" WHERE ITEM='"+item_name+"'";
Cursor c = myDataBase.rawQuery(query,null);
if(c.moveToFirst()){
add = c.getString(c.getColumnIndex("CALORIES"));
c.close();
}
add = add + " calories";
//Toast.makeText(ctx,add, Toast.LENGTH_LONG).show();
return add;
}
}
Notes
For testing purposes, method insertCal_ValEntry has been added.
Done away with any attempt to open Database rather this is done by the helper.
The check to see if the cursor is null has been removed, it is basically useless as SQLite will not return a null, it will always return a cursor, which may be empty. the Cursor move??? methods, such as moveToFirst return false if the move cannot be made.
Context isn't required by the databaseToString method so removed it.
databaseToString method made to be an instance method rather than class method (i.e not static) and made it public.
The activity in this case I've used MainActivity
public class MainActivity extends AppCompatActivity {
EditText item;
EditText quantity;
TextView calories;
Button calculate;
dietclass dbhelper; //<<<< we want an instance of the database helper
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foodcal);
item = (EditText)findViewById(R.id.etitem);
quantity = (EditText)findViewById(R.id.etquantity);
calories = (TextView)findViewById(R.id.calories);
calculate = (Button)findViewById(R.id.calculate);
dbhelper = new dietclass(this); //<<<< get the instance of the database helper
dbhelper.insertCal_ValEntry("Porridge", "100g",5000); //<<<< For testing
dbhelper.insertCal_ValEntry("Cake","500g", 20000); //<<<< For testing
calculate.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String itemstr = item.getText().toString();
printDatabase(itemstr);
//String dbstring = dietclass.databaseToString(itemstr);
//calories.setText(String.valueOf(dbstring));
}
});
}
public void printDatabase(String item){
String dbstring = dbhelper.databaseToString(item); //<<<<
//String label;wr
//label = dbstring + "calories";
calories.setText(String.valueOf(dbstring));
}
}
Notes
The principle used above could be used in any activity. That is get an instance of the database helper and then invoked methods within the helper to get/add/alter data in the database.
Results from the above:-
1) When App is started:-
2) Clicking without input (or inputting item not in table) :-
3) Clicking after inputting valid item :-
Additional Info
If you really want to get the database path the following is less prone to errors:-
String databasepath = getDatabasePath(dietclass.DATABASE_NAME).getPath();
((TextView) findViewById(R.id.dbpath)).setText(databasepath);
With the dbpath TextView (note run on 7.0.0 device):-
On a 4.1.1 device :-
Related
Im trying to figure out how I can delete one user at a time by typing in the edittext the users username and clicking deleting which I then want all the users information (username, usernum, password, birthdate, phone, address) to be deleted from the database. Below is my code and for some reason it isnt working can any one please please help me!! Im very desperate and ive been trying to figure out the problem for hours.
DatabaseHelperUser class:
public class DatabaseHelperUser extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "User.db";
public static final String TABLE_NAME = "User_table";
public static final String COL1 = "ID";
public static final String COL2 = "UserNum";
public static final String COL3 = "UserName";
public static final String COL4 = "Password";
public static final String COL5 = "BirthDate";
public static final String COL6 = "Phone";
public static final String COL7 = "Address";
public DatabaseHelperUser(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, UserNum TEXT,UserName Text,Password Text,BirthDate Text,Phone Text,Address Text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public boolean deleteData(String UserName) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "UserName" + "=?" + UserName, null) > 0;
}
}
RemoveUser class:
public class RemoveUser extends AppCompatActivity {
Button btdelete;
EditText txtUser;
DatabaseHelperUser myDb;
private String selectedName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remove_user);
btdelete = (Button) findViewById(R.id.butRemove);
txtUser = (EditText) findViewById(R.id.etxtUserName);
myDb = new DatabaseHelperUser(this);
btdelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean delete = myDb.deleteData(txtUser.getText().toString());
if(delete == true)
Toast.makeText(RemoveUser.this,"User has been deleted", Toast.LENGTH_LONG).show();
else
Toast.makeText(RemoveUser.this,"User has not been deleted", Toast.LENGTH_LONG).show();
}
});
}
}
You must pass the variable UserName as the 3d argument of the method delete(), so it will replace the placeholder ? when the statement is executed:
public boolean deleteData(String UserName) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "UserName = ?", new String[] {UserName}) > 0;
}
Hello as the title says I cannot get the app to construct a small local sqlite database. I would appreciate some help as I m an amateur. Thanks in advance.
Below there are some pictures of my source code.
I tested this code on level 24 API device, but the database does not appear in the data/data/the_package/databases/ folder
Edited to include code
MainActivity.java
public class MainActivity extends AppCompatActivity {
private CrdDBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new CrdDBHelper(this);
boolean p1 = true;
int p11sc = 0;
int p12sc = 0;
Button btnMenu = (Button) findViewById(R.id.btnMenu);
Button btntrue = (Button) findViewById(R.id.btnTrue);
Button btnFalse = (Button) findViewById(R.id.btnFalse);
// All other available code commented out
}
#Override
protected void onDestroy() {
mydb.close();
super.onDestroy();
}
}
CrdDBContract.java
public final class CrdDBContract {
private CrdDBContract(){}
public static final class GameEntry implements BaseColumns {
public static final String TABLE_NAME = "Game";
public static final String COLUMN_KNOWN = "Known";
public static final String COLUMN_TBF = "TBF";
public static final String SQL_CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ _ID + " INTEGER PRIMARY KEY, "
+ COLUMN_KNOWN + " TEXT NOT NULL, "
+ COLUMN_TBF + " TEXT NOT NULL)";
}
}
CrdDBHelper.java
public class CrdDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "CardGame.db";
public static final int DATABASE_VERSION = 1;
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CrdDBContract.GameEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
CrdDBDataInsertion.java
public class CrdDBDataInsertion {
//??????????? Code not available from images
SQLiteDatabase mDB;
private void contentvalues(String Known, String TBF) {
ContentValues values = new ContentValues();
values.put(CrdDBContract.GameEntry.COLUMN_KNOWN,Known);
values.put(CrdDBContract.GameEntry.COLUMN_TBF,TBF);
long newid = mDB.insert(CrdDBContract.GameEntry.TABLE_NAME,null,values);
}
}
Main Activity part1Main Activity part2
Main Activity part3(final)
DB Contract class
DB Helper class
DB insert class part1
DB insert class part2 (final)
You aren't, according to the code, acessing(opening) the database. You are just instantiating the DatabseHelper in MainActivity i.e. mydb = new CrdDBHelper(this);
It is not until an attempt is made to open the database (which is frequently implicit) that the database is actually created.
A simple way would be to force an open when instantiating the database. e.g. call the getWritableDatabase() method in the constructor, like :-
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
getWritableDatabase();
}
Perhaps at that time set an SQLiteDatabase object with the returned SQLiteDatabase, so your Database Helper (CrdDBHelper.java) could be :-
public class CrdDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "CardGame.db";
public static final int DATABASE_VERSION = 1;
SQLiteDatabase mDB;
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mDB = this.getWriteableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CrdDBContract.GameEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
as the onCreate method is called when (and ONLY when) the database is created the Game table will then be created.
I am currently working on an android quiz application with the questions linking to the database, however, I was be able to create the database created but somehow the values such as list of questions won't be inserted manually. As I have opened the database, it has organized the columns I have wanted but no values will be display such as the 'example question' Have I been missing some line of code?
Many Thanks
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "Questions.db";
public static final String TABLE_NAME = "Questions";
public static final String QUESTION_NUMBER = "Question_Number";
public static final String QUESTION = "Question";
public static final String ANSWER_ONE = "Answer_ONE";
public static final String ANSWER_TWO = "Answer_THREE";
public static final String ANSWER_THREE = "Answer_FOUR";
private SQLiteDatabase db;
public DatabaseHelper(Context context)
{
super(context,DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db)
{
this.db = db;
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
TABLE_NAME + " ( " +
QUESTION_NUMBER + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
QUESTION + " TEXT, " +
ANSWER_ONE + " TEXT, " +
ANSWER_TWO + " TEXT, " +
ANSWER_THREE + " TEXT " +
")";
db.execSQL(SQL_CREATE_QUESTIONS_TABLE);
fillQuestionTable();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1)
{
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
private void fillQuestionTable()
{
Question q1 = new Question(1,"Example Question?","Yes","Sometimes","No");
addQuestion(q1);
}
private void addQuestion (Question question)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(QUESTION_NUMBER, question.getQuestionNum());
cv.put(QUESTION, question.getQuestion());
cv.put(ANSWER_ONE, question.getOption1());
cv.put(ANSWER_TWO, question.getOption2());
cv.put(ANSWER_THREE, question.getOption3());
db.insert(TABLE_NAME,null,cv);
}
}
This is the activity Class
public class MainActivity extends Activity implements View.OnClickListener
{
Button screenOneButton;
Button screenTwoButton;
Button screenThreeButton;
Button quitButton;
DatabaseHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHelper mydb = new DatabaseHelper(this);
}
This is programmed under Intellij software and was able to open the database under DB SQL software FYI!
Many thanks
I want to save the Score from a Quiz in a SQLite Database and change an image in another activity if the Score is 5. There is no error shown, but even if I score 5 the image won't change... How can I log the content of my database to check if the score was added or how can I find the mistake?
DB Helper:
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 7;
private static final String DATABASE_NAME = "CE";
public static final String SCORE_TABLE = "score";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SCORE = "SCORE";
public static final String COLUMN_MARKERID = "MARKERID";
private SQLiteDatabase dbase;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase= db;
String create_query = "CREATE TABLE IF NOT EXITS " + SCORE_TABLE + " ( "
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_SCORE + " INTEGER, "
+ COLUMN_MARKERID + " TEXT) ";
db.execSQL(create_query);
}
public void addScore (DbHelper dbh, Integer score, String markerID) {
dbase = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_SCORE, score);
cv.put(COLUMN_MARKERID, markerID);
dbase.insert(SCORE_TABLE, null, cv);
}
public Cursor getScore(DbHelper dbh) {
dbase = dbh.getReadableDatabase();
String columns[] = {COLUMN_SCORE, COLUMN_MARKERID};
Cursor cursor = dbase.query(SCORE_TABLE, columns, null, null, null, null, null);
return cursor;
}
Write the Score into the Database after completing the Quiz:
public class ResultActivity extends Activity {
String markerID;
int score;
TextView t=(TextView)findViewById(R.id.textResult);
Button saveButton = (Button) findViewById(R.id.saveButton);
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_layout);
Bundle b = getIntent().getExtras();
score = b.getInt("score");
markerID = b.getString("markerID");
}
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DbHelper dbh = new DbHelper(context);
dbh.addScore(dbh,score,markerID);
Intent intent = new Intent(ResultActivity.this, Discover.class);
intent.putExtra("MarkerID", markerID);
startActivity(intent);
}
});
}
Discover class -> Check if score is 5 and change image if:
DbHelper dbh = new DbHelper(context);
Cursor cursor = dbh.getScore(dbh);
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
if (Integer.parseInt(cursor.getString(0))== 5 && InfoUeberschrift.toString().equals(cursor.getString(1))){
ImageDone.setImageResource(R.drawable.markerdone);
}
}
while(cursor.moveToNext());
}
cursor.close();
}
The SQLiteDatabase insert function returns a long value, so if an error has occurred it returns -1.
'the row ID of the newly inserted row, or -1 if an error occurred'
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
This can be used to see if the insert is happening correctly.
Or you can wrap in try and catch and print message like so
try {
//code
} catch(SQLiteException ex) {
Log.v("Insert into database exception caught", ex.getMessage());
return -1;
}
}
When I have issues using Java and SQLite i normally do it directly with the SQLite desktop version using Shell, as I find it easier to test out table design.
Hope this helps
I have made an app that has 3 activities.
In the fisrt activity(Import) i just import some values to a sqlite database.
This is my DatabaseHelper class:
public class DatabaseHelper_bp extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "bpDB";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table bp_import ( _id integer primary key, datetime text not null, systolic text not null, diastolic text not null, pulses text not null, notes text not null);";
public DatabaseHelper_bp(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
// Method is called during an upgrade of the database,
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(DatabaseHelper_bp.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS bp_import");
onCreate(database);
}
}
And my DAO class for my measures/values:
public class BpDAO {
private DatabaseHelper_bp dbHelper;
private SQLiteDatabase database;
/**
* bp table related constants.
*/
public final static String bp_TABLE = "bp_import";
public final static String bp_ID = "_id";
public final static String bp_DT = "datetime";
public final static String bp_SYS = "systolic";
public final static String bp_DIA = "diastolic";
public final static String bp_PUL = "pulses";
public final static String bp_NOT = "notes";
/**
*
* #param context
*/
public BpDAO(Context context) {
dbHelper = new DatabaseHelper_bp(context);
database = dbHelper.getWritableDatabase();
}
/**
* \ Creates a new blood pressure measure
*
* #param datetime
* #param systolic
* #param diastolic
* #param pulses
* #param notes
* #return
*/
public long importBP(String datetime, String systolic, String diastolic,
String pulses, String notes) {
ContentValues values = new ContentValues();
values.put(bp_DT, datetime);
values.put(bp_SYS, systolic);
values.put(bp_DIA, diastolic);
values.put(bp_PUL, pulses);
values.put(bp_NOT, notes);
return database.insert(bp_TABLE, null, values);
}
public void close() {
database.close();
}
/**
* Fetch all bp
*
* #return
*/
public Cursor fetchAll_bp() {
Cursor mCursor = database.query(true, bp_TABLE, new String[] { bp_SYS,
bp_DIA, bp_DT, bp_ID }, null, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
In the second activity(History) i have a List that is populated by the database,all ok
Here is the code of 2 Activity(history):
public class HistoryActivity extends ListActivity {
private BpDAO dao;
private SimpleCursorAdapter dbAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
dao = new BpDAO(this);
Cursor bpList = dao.fetchAll_bp();
String[] from = new String[] { BpDAO.bp_SYS, BpDAO.bp_DIA, BpDAO.bp_DT };
int[] target = new int[] { R.id.bpSysHolder, R.id.bpDiaHolder,
R.id.bpDtHolder };
dbAdapter = new SimpleCursorAdapter(this, R.layout.history_bp, bpList,
from, target);
setListAdapter(dbAdapter);
}
#Override
public void onListItemClick(ListView l, View view, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, view, position, id);
Log.d("BPT", "Selected bp id =" + id);
// log says that i have selected an item with id : 11
Cursor selectedBpDetails = (Cursor) l.getItemAtPosition(position);
String bp_DT = selectedBpDetails.getString(selectedBpDetails
.getColumnIndex(BpDAO.bp_DT));
String bp_SYS = selectedBpDetails.getString(selectedBpDetails
.getColumnIndex(BpDAO.bp_SYS));
String bp_DIA = selectedBpDetails.getString(selectedBpDetails
.getColumnIndex(BpDAO.bp_DIA));
String bp_PUL = selectedBpDetails.getString(selectedBpDetails
.getColumnIndex(BpDAO.bp_PUL));
String bp_NOT = selectedBpDetails.getString(selectedBpDetails
.getColumnIndex(BpDAO.bp_NOT));
Log.d("BPT", "Selected bp details = { date=" + bp_DT + ", systolic="
+ bp_SYS + ", diastolic=" + bp_DIA + ", pulses=" + bp_PUL
+ ", notes=" + bp_NOT + " }");
Intent intent = new Intent(HistoryActivity.this, FromHistory.class);
intent.putExtra("bp_SYS", bp_SYS);
intent.putExtra("bp_DIA", bp_DIA);
intent.putExtra("bp_DT", bp_DT);
intent.putExtra("bp_PUL", bp_PUL);
intent.putExtra("bp_NOT", bp_NOT);
startActivity(intent);
}
}
When i click on a list item i start a new activity that i show all the infos of the measure from the database.
But i have in logcat:
1.close() was never explicitly called on database
2.android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
3.E/System(561): java.lang.IllegalStateException: Don't have database lock!
I have seen some other questions but didn't manage to find how to close it for my situation.
(You should close your Cursors when you are done with them as the others have pointed out, but...)
The error is telling you that you need to close your SQLiteDatabase. Add this method to your BpDAO class:
public void close() {
database.close();
}
And whenever you create a new BpDAO object in any Activity you need to call close(), you can do this as soon as you are done or in onDestroy():
#Override
protected void onDestroy() {
super.onDestroy();
dao.close();
}
When you are done with cursor you need to close()
Example:
selectedBpDetails.close();
Either you close the cursor directly after the fetching of your data by calling close() on it, or you can override the onDestroy method for your activity and then in the implementation of this method you close the cursor(s) that you have opened.
public class HistoryActivity extends ListActivity {
// ...
Cursor bpList;
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
bpList = dao.fetchAll_bp();
// ...
}
#Override
protected void onDestroy() {
super.onDestroy();
bpList.close();
}
#Override
public void onListItemClick(ListView l, View view, int position, long id) {
// ...
Cursor selectedBpDetails = (Cursor) l.getItemAtPosition(position);
// ...
selectedBpDetails.close();
}
// ...
}