App crashes between onPause and onResume Listview issue - android

I have a listview activity which populates data through an sqlite database; however, whenever I enter onPause and then go into onResume my app crashes and I receive this error: "java.lang.IllegalStateException: trying to requery an already closed cursor android.database.sqlite.SQLiteCursor#418106a8". Would anyone know how to stop this? Is there a method I have to call in onPause?
#Override
protected void onResume() {
super.onResume();
uGraduateListAdapter = new ArrayAdapter<String>(ListOfAlarms.this, android.R.layout.simple_list_item_1, populateList());
listOfAlarms.setAdapter(uGraduateListAdapter);
Log.i(TAG, "Resume was called");
}
#Override
protected void onPause() {
super.onPause();
Log.i(TAG, "Pause was called");
sqliteDatabase.close();
}
public List<String> populateList(){
// We have to return a List which contains only String values. Lets create a List first
List<String> uGraduateNamesList = new ArrayList<String>();
// First we need to make contact with the database we have created using the DbHelper class
AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);
// Then we need to get a readable database
sqliteDatabase = openHelperClass.getReadableDatabase();
// We need a a guy to read the database query. Cursor interface will do it for us
//(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
cursor = sqliteDatabase.query(AndroidOpenDbHelper.TABLE_NAME_ALARM, null, null, null, null, null, null);
// Above given query, read all the columns and fields of the table
startManagingCursor(cursor);
// Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
while (cursor.moveToNext()) {
// In one loop, cursor read one undergraduate all details
// Assume, we also need to see all the details of each and every undergraduate
// What we have to do is in each loop, read all the values, pass them to the POJO class
//and create a ArrayList of undergraduates
String alarmName = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_ALARM_NAME));
// String ugUniId = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_UNI_ID));
String alarmTotalTime = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLLUMN_ALARM_TOTALTIME));
// Finish reading one raw, now we have to pass them to the POJO
TestAlarm ugPojoClass = new TestAlarm();
ugPojoClass.setTitle(alarmName);
ugPojoClass.setTotalTime(alarmTotalTime);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
pojoArrayList.add(ugPojoClass);
// But we need a List of String to display in the ListView also.
//That is why we create "uGraduateNamesList"
uGraduateNamesList.add(alarmName);
}
// If you don't close the database, you will get an error
sqliteDatabase.close();
return uGraduateNamesList;
}

You are using deprecated methods (startManagingCursor()), which is dangerous.
How I see what happens: when you close your database (twice actually: in populateList() and onPause()), your cursors to this database become invalid. But since you called startManagingCursor(), your Activity retains your cursors and tries to call requery() on them when restarting, which throws the error.
Try not calling startManagingCursor() at all, just cursor.close() when you're done with it. Or you can migrate to newer LoaderManager altogether.

Related

is there a way of modifying values loaded via CursorLoader and just before displaying to the textview

I'm using plain old ListViews, SimpleCursorAdapter, LoaderCallback etc. to read values from a database and display in textViews.
sample code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cateory_list);
mListView = (ListView) findViewById(R.id.list_view);
mAdapter = new SimpleCursorAdapter(
this,
R.layout.category_parent,
null,
new String[] {CategoryTable.COL_2},
new int[] {R.id.text_view},
0);
mListView.setAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri uri = new Uri.Builder()
.scheme("content")
.appendPath(CategoryTable.TB_NAME)
.authority("com.example.auth")
.build();
return new CursorLoader(this, uri, null, null, null, null);
}
Everything works well and the values from database are displayed on the listview. But suppose I want to do some text processing of the values before displaying, how can I do that?
Edit 1: I don't want to do the text processing in main-thread. Is there a way I can use the AsynTaskLoader thread created from CursorLoader and off-load the work over there?
Yep. It is called a ViewBinder. You want a SimpleCursorAdapter.ViewBinder, in your case. It is called just as the data is moved from the adapter, in to the view.
Be careful, though. It is called a lot (likely several times for each view in each cell of the list). It needs to run really fast and, unless you want to drive the GC nuts, should not allocate anything.
I managed to create a Custom Loader by extending CursorLoader and only overriding public Cursor loadInBackground()
This way I'm retrieving the data, do long running text processing, insert the result back to new table and return the cursor of the new table.
Sample code:
#Override
public Cursor loadInBackground() {
Cursor cursor = super.loadInBackground();
cursor.moveToFirst();
try {
ActiveAndroid.beginTransaction();
do {
String s = doProcessing(cursor.getString(colNumber));
createAndInsertIntoNewTable(s);
} while (cursor.moveToNext());
ActiveAndroid.setTransactionSuccessful();
} finally {
ActiveAndroid.endTransaction();
}
return cursorFromNewTable;
}
This completely does the work in AsyncTaskLoader thread and solves my problem perfectly.

Inserting rows from different activity is not being shown in main activity

I have a database helper class that gets all of the rows of a table from a SQLite database. In the onCreate of my Main Activity I am calling that method and populating a ListView with that data.
I have a separate Activity that is getting info from a network and inserting rows into the database. After that is done I am calling finish() and it returns to the Main Activity.
When it returns the inserted rows are not being displayed in the ListView. From debugging, it appears that they are not being returned from the database helper method.
If I close and relaunch the app, the rows show up. If I change the screen orientation, they show up.
Here is my database helper method:
public List<Object> getAllObjects() {
List<Object> objects = new ArrayList<Object>();
Cursor cursor = database.query(SQLiteHelper.TABLE_OBJECT,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Object object = cursorToObject(cursor);
objects.add(object);
cursor.moveToNext();
}
cursor.close();
return objects;
}
Your main Activity is not newly created, you return to an old instance. In your case, put the update code in the onResume method of your main Activity, not in the onCreate method.
See the Activity lifecycle for further details on when code is executed.

Proper way to handle Cursor objects

When you call .close() on a Cursor Object, does it mean that for the rest of the Activity's duration it cannot be used? The following is a method within my Manager Object:
Cursor cursor = null;
try {
SQLiteDatabase db = openDb();
cursor = db.query("table", null, "id=?", new String[] { id }, null, null, null);
cursor.moveToFirst();
long dateTime = cursor.getLong(1);
cursor.close();
return dateTime ;
} catch (CursorIndexOutOfBoundsException e) {
return -1;
} finally {
if (cursor != null) {
cursor.close();
}
closeDb();
}
This is the method that's throwing me an IllegalStateException. However, there's a slight twist: it only throws an error the second time it is called. Tracing the stacktrace, I find that the line causing me trouble is the following:
Cursor cursor = db.query("table", null, "id=?", new String[] { id }, null, null, null);
Just to clear things up a bit, this method can be called several times within the Activity's lifetime through clicking of a particular ListView item. The openDb() and closeDb() methods are as follows:
public SQLiteDatabase openDb() {
if (mDbHelper == null) {
mDbHelper = new DatabaseHelper(mContext);
}
return mDbHelper.getWritableDatabase();
}
public void closeDb() {
mDbHelper.close();
}
And these are stored in the superclass of my Manager object. mDbHelper is a static Object.
Being fairly new to Android programming, I'm wondering why this would throw me an exception. The only logical explanation I can think of is that Cursor Objects are actually re-used, and they should not be closed for the duration of an activity. Am I right? And if I am, when do you actually close the Cursor?
---EDIT---
Having tinkered around with the code a bit, I seem to be getting the exception being thrown on a much more irregular basis. For some odd reason, it seems to happen randomly; I can click on eight multiple ListView items with no issues, and suddenly bam! The ninth causes the application to crash.
Because clicking on a ListView also invokes a method which updates that very same table (which up till now has caused me no problems thus far), I think it's only relevant that I include that as well:
try {
SQLiteDatabase db = openDb();
ContentValues cv = new ContentValues();
cv.put("id", id);
cv.put("dateTime", dateTime);
long affected = db.replace("table", null, cv);
return affected;
} finally {
closeDb();
}
As you can see, no rocket science is involved here. However, this method has now started to throw similar Exceptions, happening on the line:
long affected = db.replace("table", null, cv);
I'm starting to suspect that it's a click-too-fast problem, and the SQLite connections are not given enough time to close. Because there is no pattern to the crashes that I can discern; sometimes it crashes on the third try, sometimes on the eighth, sometimes it even seems to work fine till well past the tenth.
Could that be possible?
As the docs say after you have called close() your Cursor becomes forever invalid.
Also, there's no need to call close 2 times in your function. It's enough to call it in the finally block only
Because you call the close() method on the static object, it may not necessarily "nullify" the static object. So when you check if mDbHelper is null in the openDb() method the second time, it will pass this condition, and therefore the method will unintentionally return a closed database. When you try and query this closed database, it will therefore throw the illegalstateexception.
Try:
public SQLiteDatabase closeDb() {
mDbHelper.close()
mDbHelper = null;
}
I hope I have helped.

Updating List view from database

I feel like i am missing something simple and stupid. I have a list view with a few buttons at the top. The list view is initially populated with data. When you click a button the list view is supposed to populate its self based on a changed variable in the Where statement. In reality i could probably just start a new List activity but i feel like there is a better way.
I have been reading up on CursorAdapter.changeAdapter() and notifydatasetchanged() I have not implemented this yet because i am having a more basic problem.
I can successfully query the database and display the static results in the list. When i try to break process into steps i am running into an ERROR: Invalid statement in fillWindow. The best i understand this is caused by improperly closing cursors databases and DB helpers and for this reason people use content providers.
For now i am just trying to get this to work.
public class DListView extends ListActivity implements OnClickListener{
public static final String NAME = "Name";
public static final String DESCRIPT = "Description";
public static final String DATABASE_TABLE = "Table";
public static final String DAY = "Day_id";
/** Called when the activity is first created. */
private Cursor c = null;
private String[] colsfrom = {"_id", NAME, DESCRIPT, DAY};
private int[] to = new int[] {R.id.text01, R.id.text02, R.id.text03, R.id.text04};
public int b = 0;
public int d = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drinklistview);
View left = findViewById(R.id.left_button);
left.setOnClickListener(this);
View right = findViewById(R.id.right_button);
right.setOnClickListener(this);
Intent thisIntent = getIntent();
b = thisIntent.getIntExtra("_b", 0);
//0 is the default argument is nothing is passed.
d = thisIntent.getIntExtra("_d", 0); //same idea as above.
c = fillList();
/*this creates a new cursor adapter
#param Context is the list context that you will be filling.
#param int layout is the layout that you will use for the rows
#param Cursor is the cursor that was returned from the query
#param from is the column names
#param to is the layout ids that the fields will be put in.
#param from is the column names to map from
#param to is the layout ids that the column fields will be put in.
*/
SimpleCursorAdapter myAdapter = new SimpleCursorAdapter(this, R.layout.row, c, colsfrom, to);
setListAdapter(myAdapter);
}
private Cursor fillList() {
DBHelper DbHelper = new DBHelper(this);
Cursor cursor;
String wHERE = "_id = " + b + " AND Day_id = " + d ;
try {
myDbHelper.openDataBase();
}
catch(SQLException sqle){
throw sqle;
}
cursor = myDbHelper.getDrinks(DATABASE_TABLE, colsfrom, wHERE, null, null,null, null);
myDbHelper.close();
return cursor;
}
When i put the contents of fillList() in the onCreate() it displays data just fine. When i pull it out it gives me the ERROR. Why is this happening? If anyone has a better way of going about this i would love to read it. Or we can play a game called "What stupid thing am i doing wrong Now?
Thankyou.
EDIT:From DBHelper
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
I am thinking that my problem line is the super.close() I believe that this line closes the database and anything affiliated with it which means the cursor that i try to use after its closed. I may be wrong though. Please explain if you can.
Your problem is right here, in your fillList():
myDbHelper.close(); // <--- here
return cursor;
you make a cursor object but close your database connection before you even get to use it (this component of the database) which would render it useless or null if you would. Usually you close the cursor and then the database. But that's not throwing the error. That error specifically is because you hooked up this cursor to a cursorAdapter trying to fill your listView with nothing. Move that and it should be gone.
So where do you move it then? If you have a cursor hooked up to listView, it needs to be open the entire time, otherwise you'll get another error saying "attempting to re-open an already closed object". I'd suggest putting in the onDestroy() when then listView is being chucked as well.
YaY Solved. Mango is exactly correct. Thankyou for you suggestion to close cursor in on destroy. I am not sure if the super.close() line closes my cursor or not. but i will look into it. I am also going to put the database query in async task for kicks and giggles.
I simply moved the two lines that created a new SimpleCursorAdapter and set the list view into the fillList method.
I also implemented my buttons and just added fillList at the end.
Here is the code that fixed things. Simple Mistake.
private void fillList() {
DBHelper DbHelper = new DBHelper(this);
Cursor cursor;
String wHERE = "_id = " + b + " AND Day_id = " + d ;
try {
myDbHelper.openDataBase();
}
catch(SQLException sqle){
throw sqle;
}
cursor = myDbHelper.getDrinks(DATABASE_TABLE, colsfrom, wHERE, null, null,null, null);
SimpleCursorAdapter myAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, colsfrom, to);
setListAdapter(myAdapter);
myDbHelper.close();
}
And Here is wehre i call the fillList again that updates my list view.
public void onClick(View v) {
switch(v.getId()) {
//Mess with d based on button click
}
fillList();
}
Now the application has to create a new simple cursor adapter every time something is changed.
If anyone has any ideas on implementing this without creating a new CursorAdapter every time that would help very much but my initial problem is solved. Thankyou for your help. Just the fact that you wanted to see my stack trace told me that i was not doing anything wrong in the code that i initially presented and i forgot that i made my dbHelper close all connections. Thankyou mango. I solved this last night but couldnt post it. Thanks for the explanation good sir. If you have any insight to the constant creation of a new cursoradapter i would be very pleased to see it. Maybe i need to fix the super.close() command somehow.

android database already close onResume

my application has an issue where if I go back to an activity I get an error that the database has been closed:
ERROR/AndroidRuntime(3566): Caused by: java.lang.IllegalStateException: database /data/data/com.kempville.app/databases/MyDB already closed
I instantiate, open, instatiate a cursor, do the query, close the cursor and close the database all within a method called during onResume(). I don't know what is assumed to be open whenever onResume gets called when this activity comes back to the front.
private void getMydata() {
MyDb db;
db = new MyDB(this);
db.open();
Cursor c = db.getInfo(code);
startManagingCursor(c);
if (c.moveToFirst()) {
name = c.getString(c.getColumnIndex("name"));
}
c = fdb.getType(myArray.getString("type"));
startManagingCursor(c);
if (c.moveToFirst()) {
type = c.getString(c.getColumnIndex("type"));
}
c.close();
db.close();
Seems that startManagingCursor will try to close it, though you've closed it yourself. Either drop the startManagingCursor (it's getting deprecated) or better call stopManagingCursor

Categories

Resources