ali
ali

Reputation: 11045

android.database.StaleDataException: Access closed cursor

I have main Activity, a SQLiteOpenHelper class and a Fragment, where I must get a Cursor with data from the database.

Inside my main activity I store and initiate the database, as a static public member:

public class Main extends FragmentActivity {
    public static Main MainActivity;
    public static DBHelper Database;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        MainActivity = this;
        Database = new Database(getApplicationContext(), "db_test", null, 1);
    }
}

This is how my database's class looks like:

public class DBHelper extends SQLiteOpenHelper {
    public static final String MAIN_TABLE = "tbl_list";

    public DBHelper(Context c, String n, CursorFactory f, int v) {
        super(c, n, f, v);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(
            "CREATE TABLE IF NOT EXISTS " + MAIN_TABLE + " (" + 
            "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
            "name VARCHAR (64) NOT NULL, " + 
            "status TEXT DEFAULT NULL " + 
            ")"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
    }
}

Inside my fragment, I am trying to retrieve a list with all the records:

public class MyFrag extends Fragment {
    private DBHelper db;

    @Override
    public View onCreateView(LayoutInflater i, ViewGroup v, Bundle b) {
        db = Main.Database.getWritableDatabase();
    }

    private void showList() {
        ListView list_view= new ListView(Main.MainActivity);
        String[] data = { "_id", "name", "status" };
        Cursor c = db.query(Database.TASKS_TABLE, data, null, null, null, null, null);

        c.moveToFirst();

        if (c.getCount() > 0) {
            String[] columns = new String[] { "name", "status" };
            int[] views = new int[] { 
                R.id.item_name, 
                R.id.item_status
            };
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(
                Main.MainActivity, 
                R.layout.mylist, 
                c, 
                columns, 
                views, 
                0
            );
            list_view.setAdapter(adapter);
        }
    }
}

When I run the application I get this error: android.database.StaleDataException: Access closed cursor

Upvotes: 1

Views: 890

Answers (1)

danidee
danidee

Reputation: 9624

You didn't open a connection to the database so there is no way you can access it, you have to add a method that opens your database and you close it after you are done manipulating it

Upvotes: 1

Related Questions