Tuesday, January 31, 2017

How to handle issue "Cannot perform this operation because the connection pool has been closed" – Android

Problem:
If you try another operation after closing the database, it will give you that exception.Because db.close(); releases a reference to the object, closing the object if the last reference was released.

Solution:
Keep a single SQLiteOpenHelper instance(Singleton) in a static context. Do lazy initialization, and synchronize that method. Such as
 public class DatabaseHelper  
 {  
   private static DatabaseHelper instance;  
   public static synchronized DatabaseHelper getInstance(Context context)  
   {  
     if (instance == null)  
       instance = new DatabaseHelper(context);  
     return instance;  
   }  
 //Other stuff...   
 }  
And you don’t have to close it? When the app shuts down, it’ll let go of the file reference, if its even holding on to it. i.e. You should not close the DB since it will be used again in the next call. So Just remove
 db.close();  

No comments :

Post a Comment