开发者

Android SQLite closing database between 2 activities

I know there are simila开发者_JS百科r forum threads to this one, but I've read them and tried the methods for solving the problem but it doesn't seem to do it. I get the:

close() was never explicity called on database /data/data...

application did not close the database or cursor that was opened...

My error does not occur directly, it happens after awhile, when I've gone back and forth between the two activities.

I use two activities which both need a connection to the database. My idea was for the first activity to close the database before the other activity starts. Here is my code:

@Override
public void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    movies = new MoviesData(this);
    cursor = getTitles();
    showTitles(cursor);
}

@Override
public void onPause() {
    movies.close();
    super.onPause();
}

@Override
public void onResume() {
    movies = new MoviesData(this);
    super.onResume();
}

This is my first activity, the second one is pretty much alike and is started upon a buttonpress. The MoviesData class is just an empty SQLiteOpenHelper class found below.

public class MoviesData extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "movies.db";
    private static final int DATABASE_VERSION = 1;

    public MoviesData(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
}

I now know when the error is displayed. If I quit the application and then open it again and try to do something the error is showing. I've tried to close the database in "onDestroy()" but that doesn't help either...


//
@Override
public void onPause() {
    super.onPause();
   movies.close();
cursor.close();

}
// no need to write this code 
@Override
public void onResume() {
    movies = new MoviesData(this);
    super.onResume();
}


I made it work now! I just added this to my SQLiteOpenHelper class.

public class MoviesData extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "movies.db";
    private static final int DATABASE_VERSION = 1;

    private static MoviesData movies;

    private MoviesData(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public static MoviesData getInstance(Context context) {
        if (movies == null) {
            movies = new MoviesData(context);
        }
        return movies;
    }

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜