I have been stuck this issue for 2 days.
I have a Custom SimpleCursorAdapter named Mail_Content_SimpleCursor and in my MainActivity have these codes:
private Mail_Content_SimpleCursor mail_content_cusor;
private Cursor mail_cursor;
ListView Mail_contents;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Mail_contents = (ListView)findViewById(R.id.mail_list_view_item);
mail_cursor = mDB.getMailData("gmail#gmail.com"); // Cursor query read recods from database
startManagingCursor(mail_cursor);
String[] from = new String[]{"mail_From","mail_Subject","mail_Content"};
int[] to = new int[] {R.id.mail_list_from,R.id.mail_list_subject,R.id.mail_list_content};
mail_content_cusor = new Mail_Content_SimpleCursor(this, R.layout.main_mail_list_item, mail_cursor, from, to);
Mail_contents.setAdapter(mail_content_cusor);
}
And then, I want to change cursor to get other records with other condition with a function
public void change(){
mail_cursor = mDB.getMailData("yahoo#gmail.com"); // change where clause in query
startManagingCursor(mail_cursor);
mail_content_cusor.changeCursor(mail_cursor);
}
But changeCursor function make my app crash with this error
09-22 14:07:18.189: E/AndroidRuntime(31931): java.lang.IllegalStateException: attempt to re-open an already-closed object: android.database.sqlite.SQLiteQuery (mSql = SELECT * FROM mail_contents WHERE mail_user='gmail#gmail.com')
Try using swapCursor instead .
According To Documentation :
SwapCursor : Swap in a new Cursor, returning the old Cursor. Unlike changeCursor(Cursor), the returned old Cursor is not closed.
Related
I am building a very simple app that contains a SQLiteDatabase which I want to display in a ListFragment, using a custom SimpleCursorAdapter.
My code is working fine, but I'm not sure if I'm doing things the correct way. I have searched a lot for (authoritative) examples of this, but have only found either overly simplified examples using ArrayAdapter, or overly complicated examples using ContentProvider.
ListFragment
public class CallListFragment extends ListFragment{
private CallListDbHelper dbHelper;
private SQLiteDatabase db;
private Cursor cursor;
private CallListAdapter adapter;
#Override
public void onResume() {
super.onResume();
// Create a database helper
dbHelper = new CallListDbHelper(getActivity());
// Get the database
db = dbHelper.getReadableDatabase();
// Get a cursor to the entire call list from the database
cursor = db.query( // SELECT
CallEntry.TABLE_NAME, // FROM ...
new String[] { // <columns>
CallEntry._ID,
CallEntry.COLUMN_NUMBER,
CallEntry.COLUMN_TIME },
null, // WHERE ... (x = ?, y = ?)
null, // <columnX, columnY>
null, // GROUP BY ...
null, // HAVING ...
CallEntry.COLUMN_TIME + " DESC" // ORDER BY ...
);
adapter = new CallListAdapter(getActivity(), cursor);
setListAdapter(adapter);
}
#Override
public void onPause() {
super.onPause();
// Close cursor, database and helper
if( null !=cursor ) cursor.close();
if( null != db ) db.close();
if( null != dbHelper ) dbHelper.close();
}
}
Adapter
public class CallListAdapter extends SimpleCursorAdapter {
private static final String[] FROM = {
CallListContract.CallEntry.COLUMN_NUMBER,
CallListContract.CallEntry.COLUMN_TIME
};
private static final int[] TO = {
R.id.phoneNumber,
R.id.time
};
public CallListAdapter(Context context, Cursor cursor){
this(context, R.layout.listitem_call, cursor, FROM, TO);
}
private CallListAdapter(Context context, int layout, Cursor cursor, String[] from, int[] to) {
super(context, layout, cursor, from, to, 0);
}
}
For something simple it will work. But...
Do you use your DB in one place?
How big is your DB?
How often do you hit onResume/onPause?
General recommendation is onResume/onPause should be as fast as possible, but DB operations can be blocking...
Especially first touch (creation) of DB can be time-consuming and potentially you can get ANR.
Don't use Activity as a Context or you may can get memory leaks. The recommended way is to use the Context of your Application in conjunction with singleton pattern, so you'll not bother to close DB.
CursorLoader needs the cursor to be open in order to function and will call close() on the cursor for you. As for SimpleCursorAdapter I don't see auto-close feature in the source code =(.
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.
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.
While inserting my listview gets refreshed automatically but not update when the item in the listview is updated. It only updates on database. I can see the listview is updated when I close the application and open again, or come back from previous activity.
I found some discussion related to my problem. Like: Refresh ListView with ArrayAdapter after editing an Item . Her I found that make a new method to populate the Listview and call it in the onResume method of your activity.
And the problem has been solved using this. But I do not get how to make new method mentioned like there. Could anybody help me to make it understandable?
My code in activity class:
personNamesListView = (ListView) findViewById(R.id.traineeslist);
traineeListAdapter = new ArrayAdapter<Trainee>(this,
android.R.layout.simple_list_item_1,
currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
protected void onResume() {
super.onResume();
}
And this way I populated my personNamesListView using method stringToString() in model class;
public void loadTraineeList() {
DatabaseHelper db = DatabaseHelper.getInstance();
this.traineeArrayList = new ArrayList <Trainee>();
Cursor cursor = db.select("SELECT * FROM person p JOIN attendance a ON p._id = a.person_id WHERE training_id="+Integer.toString(this.getId())+";");
while (cursor.moveToNext()) {
Trainee trainee = new Trainee();
trainee.setID(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.PERSON_ID)));
trainee.setFirstname(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_FIRSTNAME)));
trainee.setLastname(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_LASTNAME)));
trainee.setJobTitle(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_JOBTITLE)));
trainee.setEmail(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_EMAIL)));
trainee.setCompany(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_COMPANY)));
trainee.setDepartment(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_DEPARTMENT)));
trainee.setBadgeNumber(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_BADGE)));
// Pass to the arraylist
this.traineeArrayList.add(trainee);
}
}
public ArrayList<Trainee> getTraineeArrayList() {
return traineeArrayList;
}
public void setTraineeArrayList(ArrayList<Trainee> traineeArrayList) {
this.traineeArrayList = traineeArrayList;
}
I insert and Update data into database into one method:
public void storeToDB() {
DatabaseHelper db = DatabaseHelper.getInstance();
db.getWritableDatabase();
if (this.id == -1) {
// Person not yet stored into Db => SQL INSERT
// ContentValues class is used to store a set of values that the
// ContentResolver can process.
ContentValues contentValues = new ContentValues();
// Get values from the Person class and passing them to the
// ContentValues class
contentValues.put(DatabaseHelper.PERSON_FIRSTNAME, this
.getFirstname().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_LASTNAME, this
.getLastname().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_JOBTITLE, this
.getJobTitle().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_EMAIL, this.getEmail());
contentValues.put(DatabaseHelper.PERSON_COMPANY, this.getCompany()
.trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_DEPARTMENT, this
.getDepartment().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_BADGE, this
.getBadgeNumber().trim().toUpperCase());
// here we insert the data we have put in values
this.setID((int) db.insert(DatabaseHelper.TABLE_PERSON,
contentValues));
} else {
// Person already existing into Db => SQL UPDATE
ContentValues updateTrainee = new ContentValues();
updateTrainee.put(DatabaseHelper.PERSON_FIRSTNAME, this
.getFirstname().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_LASTNAME, this
.getLastname().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_JOBTITLE, this
.getJobTitle().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_EMAIL, this.getEmail());
updateTrainee.put(DatabaseHelper.PERSON_COMPANY, this.getCompany()
.trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_DEPARTMENT, this
.getDepartment().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_BADGE, this
.getBadgeNumber().trim().toUpperCase());
db.update(DatabaseHelper.TABLE_PERSON, updateTrainee,
DatabaseHelper.PERSON_ID+"= ?", new String[]{Integer.toString(this.getId())});
System.out.println("Data updated");
}
}
You should call traineeListAdapter.notifyDataSetChanged() whenever you update your ArrayList representing the items in the ListView.
There's a similar question here that can give you some help.
Although I've accomplished something similar using
yourlistview.invalidateViews()
after changing the data to show in the listview
when notifyDataSetChanged() didn't work.
EDIT:
After making all the operations in the data that I want to show i just set the adapter and try to refresh my listview by calling invalidateViews().
selectedStrings = new ArrayList<String>(typeFilterStrings);
adapter.setArrayResultados(selectedStrings);
listTypeFilter.invalidateViews();
It's not obligatory to set the adapter again in my case worked.
use like this:
Create an instance of your custom adapter, so you can use it anywhere you like...
public class ScoreList extends SherlockFragmentActivity {
private ListView listViewScore;
private ScoreListAdapter adapter;
static List<Score> listScore = new ArrayList<Score>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.score_list);
ctx = this;
listScore = dbh.getAllScores();
listViewScore = (ListView) findViewById(R.id.score_list);
adapter = new ScoreListAdapter(ctx, R.layout.score_row_item, listScore);
listViewScore.setAdapter(adapter);
((BaseAdapter) listViewScore.getAdapter()).notifyDataSetChanged();
}
}
By the way, if your listScore array is already loaded, then you do not need to use
adapter.notifyDatasetChanged();
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.