Home Ask Login Register

Developers Planet

Your answer is one click away!

naqib loodin February 2016

Closing the database

Please help me where should I put the db.close () in this class, because when I put it at the end of class inside onPause method but it generates error and force stops the app , the problem happens when I click on the row , I want that a share menu popup when I click the row , the first time I click the row it pops the menu but for the second time I click on the row it force stops the app , when I remove the db.close () it is Ok but I know the db ahould be closed but I don't know where should I close? Here is the Class codes :

public class sharedlist extends ListActivity {

 private String[] items;
 private database db;

 private Typeface homa;
 private Typeface nazanin;
 private SharedPreferences sp;
 private Typeface god;

   protected void onCreate(Bundle savedInstanceState) {

db=new database(this);

items=new      String[db.Count("content")];

homa=Typeface.createFromAsset(getAssets(), "Font/homa.ttf");
nazanin=Typeface.createFromAsset(getAssets(), "Font/nazanin.ttf");
god=Typeface.createFromAsset(getAssets(), "Font/Godfather.ttf");
sp=getApplicationContext().getSharedPreferences("setting", 0);

setListAdapter(new AAD());


protected void   onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);

Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, db.Display_Shared(position, 2).toString());
startActivity(Intent.createChooser(sharingIntent,"اشتراک گذاری از طریق"));


class AAD extends ArrayAdapter{

public AAD(){
    super(sharedlist.this , R.layout.row,items);

public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater in=getLayoutInflater();
    View row=in.inflate(R.layout.row, parent, false);



user3275938 February 2016

You should set the db.close() in the onListItemClick() method. You got error, when you click on the row for the second time, because your database is closed. I think you should open your database in the onListItemClick() do your stuff, and close the database.

Doug Stevenson February 2016

Generally speaking, if you open a resource in an activity lifecycle method, you should close it in another lifecycle method for symmetry.

For example, if you open in onCreate, close in onDestroy. If you open in onStart, close in onStop.

In your case, since you open in onCreate and use the opened db while the activity is running, you could close in onDestroy, which is supposed to be the very last method executed before the activity finishes.

Post Status

Asked in February 2016
Viewed 1,814 times
Voted 7
Answered 2 times


Leave an answer

Quote of the day: live life