lundi 12 octobre 2015

Error "trying to requery an already closed cursor”

I have MainActivity with two Fragments, which are located in ViewPager.

First Fragment (Fragment_ListFragment) has ExpandableListView, in which i put my data from my database table. When i click on child, i get id of element from my table and send this id to second Fragment.

Second Fragment(Fragment_MapTab) has some TextView's and button, which starts new activity. When i get id from first fragment, second fragment update it's view.

When i click the button and start another activity, and then i return back in MainActivity i get error: java.lang.RuntimeException: Unable to resume activity {com.fedorn.mypushchino/com.fedorn.mypushchino.MainActivity}: java.lang.IllegalStateException: trying to requery an already closed cursor android.database.sqlite.SQLiteCursor@528c11c0

Fragment_ListFragment:

public class Fragment_ListFragment extends Fragment {

    private ViewPager vp;
    ExpandableListView list;
    DataBase db;

    //Data and objects for ExpandableListView
    Cursor cursor;
    String[] groupFrom = {"tag"};
    int[] groupTo = {R.id.txtServicesGroup};
    String[] childFrom = {"name", "_id"};
    int[] childTo = {R.id.txtServicesChild, R.id.txtServicesID};
    MyAdapter sctAdapter;

    public static Fragment_ListFragment getInstance() {
        Bundle args = new Bundle();
        Fragment_ListFragment fragment = new Fragment_ListFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_items_list, null);
        list = (ExpandableListView) view.findViewById(R.id.expandableListView);
        vp = (ViewPager) getActivity().findViewById(R.id.viewPager);
        db = new DataBase(getContext());

        list.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                String to = ((MainActivity) getActivity()).getTabFragmentB();
                Fragment_MapTab fragment_mapTab = (Fragment_MapTab) getActivity().getSupportFragmentManager().findFragmentByTag(to);
                TextView tv = (TextView) v.findViewById(R.id.txtServicesID);
                fragment_mapTab.update(Integer.parseInt(tv.getText().toString()));
                vp.setCurrentItem(Constants.TAB_MAP);
                return false;
            }
        });

        if (android.os.Build.VERSION.SDK_INT <
                android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            list.setIndicatorBounds(30, 80);
        } else {
            list.setIndicatorBoundsRelative(30, 80);
        }

        String myTag = getTag();
        ((MainActivity) getActivity()).setTabFragmentA(myTag);

        return view;
    }



    public void update(int f) {
        switch (f) {
            case Constants.FRAG_INIT_Administration:
                cursor = db.fetchGroup(new String[]{"Administration","School"});
                sctAdapter = new MyAdapter(getContext(),cursor,R.layout.list_fragment_services_groups,groupFrom,groupTo,R.layout.list_fragment_services_child,childFrom,childTo,db);
                list.setAdapter(sctAdapter);
                break;
            case Constants.FRAG_INIT_Apteka:
                cursor = db.fetchGroup(new String[]{"Apteka"});
                sctAdapter = new MyAdapter(getContext(),cursor,R.layout.list_fragment_services_groups,groupFrom,groupTo,R.layout.list_fragment_services_child,childFrom,childTo,db);
                list.setAdapter(sctAdapter);
                break;
            }
    }
}

Fragment_MapTab:

public class Fragment_MapTab extends Fragment {
    public static final int LAYOUT = R.layout.fragment_map_tab;
    private View view;
    Button button;
    DataBase db;
    Double coord1 = 0.1,coord2 = 0.1;
    TextView name, destination, phone,time,tv,tvPhone;
    LinearLayout ll;



    public static Fragment_MapTab getInstance() {
        Bundle args = new Bundle();
        Fragment_MapTab fragment = new Fragment_MapTab();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(LAYOUT, container, false);
        String myTag = getTag();
        ((MainActivity) getActivity()).setTabFragmentB(myTag);

        tvPhone = (TextView) view.findViewById(R.id.tvPhone);
        tv = (TextView) view.findViewById(R.id.tvWork);
        button = (FancyButton) view.findViewById(R.id.btn_spotify);
        ll = (LinearLayout) view.findViewById(R.id.fragment_ll);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), Map.class);
                intent.putExtra("coord1", coord1);
                intent.putExtra("coord2", coord2);
                startActivity(intent);
            }
        });

        button.setVisibility(View.INVISIBLE);
        tv.setVisibility(View.INVISIBLE);
        tvPhone.setVisibility(View.INVISIBLE);
        ll.setVisibility(View.INVISIBLE);

        name = (TextView) view.findViewById(R.id.tv_fragmentmap_name);
        destination = (TextView) view.findViewById(R.id.tv_fragmentmap_destination);
        phone = (TextView) view.findViewById(R.id.tv_fragmentmap_phone);
        time = (TextView) view.findViewById(R.id.tv_fragmentmap_time);
        return view;
    }

    public void update(int id) {         
        button.setVisibility(View.VISIBLE);
        tv.setVisibility(View.VISIBLE);
        tvPhone.setVisibility(View.VISIBLE);
        ll.setVisibility(View.VISIBLE);

        db = new DataBase(getContext());
        name.setText(db.getContact(id).getName());
        destination.setText(db.getContact(id).getDestination());
        phone.setText(db.getContact(id).getPhone());
        time.setText(db.getContact(id).getTime());

        String[] s = db.getContact(id).getCoord().split(",");
        coord1 = Double.parseDouble(s[0]);
        coord2 = Double.parseDouble(s[1]);

        db.close();
    }

}

DataBase:

public class DataBase extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 101;
    private static final String DATABASE_NAME = "pushchinoObjects";

    //Колонки таблицы Объектов
    private static final String TABLE_OBJECTS = "objects";
    private static final String KEY_ID = "_id";
    private static final String KEY_NAME = "name";
    private static final String KEY_DESTINATION = "destination";
    private static final String KEY_PHONE = "phone";
    private static final String KEY_COORD = "coord";
    private static final String KEY_TIME = "time";
    private static final String KEY_TAG = "tag";
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_OBJECTS +
            "(" + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_NAME + " TEXT,"
            + KEY_DESTINATION + " TEXT,"
            + KEY_PHONE + " TEXT,"
            + KEY_COORD + " TEXT,"
            + KEY_TIME + " TEXT,"
            + KEY_TAG + " TEXT" + ")";
    //Колонки таблицы Групп
    private static final String TABLE_GROUP = "groups";
    private static final String KEY_ID_GROUP = "_id";
    private static final String KEY_TAG_GROUP = "tag";
    String CREATE_GROUP_TABLE = "CREATE TABLE " + TABLE_GROUP +
            "(" + KEY_ID_GROUP + " INTEGER PRIMARY KEY,"
            + KEY_TAG_GROUP + " TEXT" + ")";


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


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_CONTACTS_TABLE);

        //Create objects
        db.insert(TABLE_OBJECTS, null, getCV(new myObject("Administration", "here", "12521", "54.8326484,37.6206439", "34.55", "Administration")));
        db.insert(TABLE_OBJECTS, null, getCV(new myObject("Schoold", "here", "12521", "54.8326484,37.6206439", "34.55", "School")));
        db.insert(TABLE_OBJECTS, null, getCV(new myObject("Apteka", "here", "12521", "54.8326484,37.6206439", "34.55", "Apteka")));


        //Create gtoups
        db.execSQL(CREATE_GROUP_TABLE);
        db.insert(TABLE_GROUP, null, getCV2("Administration"));
        db.insert(TABLE_GROUP, null, getCV2("School"));

        db.insert(TABLE_GROUP, null, getCV2("Apteka"));                                   
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_OBJECTS);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_GROUP);
        onCreate(db);
    }

    public myObject getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_OBJECTS, new String[]{KEY_ID,
                        KEY_NAME, KEY_DESTINATION, KEY_PHONE, KEY_COORD, KEY_TIME, KEY_TAG}, KEY_ID + "=?",
                new String[]{String.valueOf(id)}, null, null, null, null);

        if (cursor != null) {
            cursor.moveToFirst();
        }

        myObject object = new myObject( cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6));

        return object;
    }


    //return ordered group cursor
    public Cursor fetchGroup(String[] tags) {
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "";
        for (int i = 0; i < tags.length; i++) {
            if (i == tags.length - 1) {
                query = query + "SELECT * FROM groups WHERE tag = '" + tags[i] + "' ORDER BY 2";
            } else {
                query = query + "SELECT * FROM groups WHERE tag = '" + tags[i] + "' UNION ";
            }
        }

        return db.rawQuery(query, null);
    }

    //return ordered objects cursor
    public Cursor fetchChildren(String tag) {
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "SELECT * FROM objects WHERE tag = '" + tag + "' ORDER BY 2";
        return db.rawQuery(query, null);
    }

    public ContentValues getCV(myObject object) {
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, object.getName());
        values.put(KEY_DESTINATION, object.getDestination());
        values.put(KEY_PHONE, object.getPhone());
        values.put(KEY_COORD, object.getCoord());
        values.put(KEY_TIME, object.getTime());
        values.put(KEY_TAG, object.getTag());
        return values;
    }

    public ContentValues getCV2(String tag) {
        ContentValues values = new ContentValues();
        values.put(KEY_TAG_GROUP, tag);
        return values;
    }
}

Also i notices, that everything works fine with api 10. I have read a lot and everybody tells, that i need to realise CursorLoader, but i can't realise how i can do this. Please, help me, what's the problem here?

Aucun commentaire:

Enregistrer un commentaire