re-open already closed - android

When I use the getPesoCount() like in the:
Log.v("SQL", String.valueOf(getPesoCount()));
I get aN error:
FATAL EXCEPTION: main
java.lang.IllegalStateException: attemp to re-open an already-closed object: android.database.sqlite.SQLiteQuery(mSql = SELECT * FROM pesoTable)...
public void addPeso(int peso, String date) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PESO, peso); // Contact Name
values.put(KEY_DATE, date); // Contact Phone Number
// Inserting Row
db.insert(TABLE_PESO, null, values);
Log.v("SQL", String.valueOf(getPesoCount()));
db.close(); // Closing database connection
}
public int getPesoCount() {
String countQuery = "SELECT * FROM " + TABLE_PESO;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
If I don't use getPesoCount(), no error occurs.
Can someone help me?

attempt to re-open an already-closed object:
Exception tells you a lot!
If you want to use the cursor further do not call cursor.close(); call it when you are sure that you do not need it anymore.

public void addPeso(int peso, String date) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PESO, peso); // Contact Name
values.put(KEY_DATE, date); // Contact Phone Number
// Inserting Row
db.insert(TABLE_PESO, null, values);
Log.v("SQL", String.valueOf(getPesoCount(db)));
db.close(); // Closing database connection
}
public int getPesoCount(db) {
String countQuery = "SELECT * FROM " + TABLE_PESO;
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}

Related

Sqlite Local database is not accurate

I'm developing android application and I'm storing some data in the local database using sqlite. When I save the database from the device file explorer and browse it using DB browser for sqlite it shows many records there which are correct. BUT i have implement a function that count number of records for specific table and it returns 0 which is wrong value.
I'm lost now cause I think the function is correct
public int numOfRecords(String tableName) {
int numOfRecords = 0;
try {
String query = "SELECT COUNT(*) FROM " + tableName ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.moveToFirst()) {
numOfRecords = cursor.getInt(0);
}
db.close();
}
catch (Exception ex ) {
Log.d("test" , "In exception");
}
return numOfRecords;
}
Try this code
public long getProfilesCount() {
SQLiteDatabase db = this.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
Or
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}

turning SQLite outcome to integer - Android

I'm working on a project and in need to use new ID's added to my database as numbers,
How do I turn this:
String query = "SELECT * FROM " + playlistsDBName + " WHERE ID = LAST_INSERT_ROWID";
To an integer (or some other number type) that I can use in my Android code?
you should change this your method from:
public void addNewPlaylist(String DBName, String playlistName) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("PlaylistName", playlistName);
db.insert(DBName, null, values);
db.close();
}
to
public int addNewPlaylist(String DBName, String playlistName) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("PlaylistName", playlistName);
final int id = db.insert(DBName, null, values);
db.close();
return (int)id;
}

Android database not updating

This method is supposed to update the friend in the database. But it is not. No error is shown, tried restarting to refresh the list etc still nothing. Log is showing me new values but they are not saved in the database.
public void updateFriend(Friend friend) {
Log.d("UpdateFriendMethod", friend.toString());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, friend.getName());
values.put(KEY_BIRTHDAY, friend.getBirthday().getTimeInMillis());
db.update(TABLE_Friends,
values,
KEY_NAME + " = ?",
new String[] { String.valueOf(friend.getName()) });
db.close();
}
Here is the way how do I get items from db:
public List<Friend> getAllFriends() {
List<Friend> Friends = new LinkedList<Friend>();
String query = "SELECT * FROM " + TABLE_Friends;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Friend friend = new Friend();
friend.setName(cursor.getString(0));
Date date = new Date(cursor.getLong(1));
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
friend.setBirthday(cal);
Friends.add(friend);
} while (cursor.moveToNext());
}
Log.d("getAllFriends()", Friends.toString());
return Friends;
}
I bet, problem is somewhere in that SQL statement, I am not familiar with it yet, I am used to SQL language not this.
SOLVED, problem was in SQL statement as I later found out:
public void updateFriend(Friend friend) {
Log.d("UpdateFriendMethod", friend.toString());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, friend.getName());
values.put(KEY_BIRTHDAY, friend.getBirthday().getTimeInMillis());
db.update(TABLE_Friends, values, KEY_NAME + "='" + friend.getName()
+ "'", null);
db.close();
}

exception: cursor index out of range

Here is the code in activity:
//query
final dbhelper helper = new dbhelper(this);
Cursor c = helper.query();
boolean exist =false;
if(c != null && c.moveToFirst()){
Log.d("atestdbChar1no",String.valueOf(c.getCount()));
int i=0;
while(c.isAfterLast()){
Log.d("atestdb1",String.valueOf(i++));
Log.d("atestdb2",String.valueOf(c.getInt(0)));
Log.d("atestdb3",c.getString(1));
Log.d("atestdb4",c.getString(2));
c.moveToNext();
}
//insert
ContentValues values = new ContentValues();
if(!finWords.equals("null")){
if(finWords.length()>index){
String selectWord = finWords.substring(index, index+1);
values.put("character", finChar);
values.put("word", selectWord);
helper.insert(values);
Here is the code in SQLiteOpenHelper:
public void insert(ContentValues values) {
SQLiteDatabase db = getWritableDatabase();
db.insert(TBL_NAME, null, values);
Log.d("test", "dbinsert");
db.close();
}
public Cursor query() {
SQLiteDatabase db = getWritableDatabase();
Cursor c = db.query(TBL_NAME, null, null, null, null, null, null);
Log.d("test", "dbquery");
return c;
}
I can insert data into database
but I cannot query them
the logcat say the cursor index out of range
and just output some data for example just output with id 1,2,4,7 then force close the App
but I already insert 14 data
what wrong of my code?
You forgot to negate c.isAfterlast() and unless you pass null back you do not have to check for null cursor.
if(c.moveToFirst()){
Log.d("atestdbChar1no",String.valueOf(c.getCount()));
int i=0;
while(!c.isAfterLast()){
Log.d("atestdb1",String.valueOf(i++));
Log.d("atestdb2",String.valueOf(c.getInt(0)));
Log.d("atestdb3",c.getString(1));
Log.d("atestdb4",c.getString(2));
c.moveToNext();
}

java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM pets

i have an error in my application.
I'm new in making apps for android, so i donĀ“t now what's wrong...
this is in the log:
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM pets
i have a SQLite database in which is this method:
public List<Pet> getAllPets() {
List<Pet> petList = new ArrayList<Pet>();
String selectQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Pet pet = new Pet();
pet.setID(Integer.parseInt(cursor.getString(0)));
pet.setName(cursor.getString(1));
pet.setAge(cursor.getString(2));
petList.add(pet);
} while (cursor.moveToNext());
}
return petList;
}
and then i'am using this method from database in other activity to fill the ListView by the names of every pet....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
PetListView = (ListView)findViewById(R.id.list);
MyDatabaseHelper db = new MyDatabaseHelper(this);
String [] items = new String[db.getPetsCount()];
List<Pet> pets = db.getAllPets();
for (int i = 0; i < db.getPetsCount(); i++) {
items[i] = pets.get(i).getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.activity_list_item, items);
PetListView.setAdapter(adapter);
}
when this activity starts the application crashes down..
Please, can you tell me what's worng? How can i fix it? Thanks a much for help.
EDIT:
getPetsCount() method:
public int getPetsCount() {
String countQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
i solved this by myself at the end by replace the getPetsCount method:
public int getPetsCount() {
String countQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
First, you should close your cursor once you have finished to use it (that may solve your issue)
public List<Pet> getAllPets() {
List<Pet> petList = new ArrayList<Pet>();
String selectQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Pet pet = new Pet();
pet.setID(Integer.parseInt(cursor.getString(0)));
pet.setName(cursor.getString(1));
pet.setAge(cursor.getString(2));
petList.add(pet);
} while (cursor.moveToNext());
}
// Close cursor when finished using it
cursor.close();
return petList;
}

Categories

Resources