尝试重新查询已关闭的游标android.database.sqlite.SQLiteCursor @时无法恢复活动

时间:2013-07-16 15:28:27

标签: android android-sqlite

当我从设置活动返回到主要活动

时,会出现此错误
java.lang.RuntimeException: Unable to resume activity {rewaya.books.ahadithviewer/rewaya.books.ahadithviewer.ViewerActivity}: java.lang.IllegalStateException: trying to requery an already closed cursor  android.database.sqlite.SQLiteCursor@415708c0

这个HadithExpandableListFragment的代码,我调用数据库

package rewaya.books.ahadithviewer.fragment;

import rewaya.books.ahadithviewer.database.DatabaseAdapter;
import rewaya.books.ahadithviewer.R;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public class HadithExpandableListFragment extends Fragment {

      private OnItemSelectedListener listener;
      private DatabaseAdapter mDbHelper;
        public static Cursor mGroupsCursor;
        private HadithExpandableListAdapter mAdapter;
         ExpandableListView chapterListView;

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.hadith_expandablelist_fragment_layout,
            container, false);

      //  Button button = (Button) view.findViewById(R.id.button1);
         chapterListView=(ExpandableListView) view.findViewById(R.id.expandableView);
         fillData();
        return view;
      }

      public interface OnItemSelectedListener {
          public void onChildSelected(String text);
        }

      @Override
        public void onAttach(Activity activity) {
          super.onAttach(activity);
          if (activity instanceof OnItemSelectedListener) {
            listener = (OnItemSelectedListener) activity;
          } else {
            throw new ClassCastException(activity.toString()
                + " must implemenet MyListFragment.OnItemSelectedListener");
          }
        }


      // May also be triggered from the Activity
      public void updateDetail(int groupPosition, int childPosition,long id) {
        //  try
        //  {
              String  Paragraph = getText(groupPosition, childPosition,id);
        listener.onChildSelected(Paragraph);
    //    }
//      catch (Exception e){
//          
//      Toast.makeText(getActivity().getBaseContext(),
//              "Exception" + Log.getStackTraceString(e),
//              ).show();
//      }
        }

      private String getText(int groupPosition, int childPosition,long id) {

    //       mDbHelper =new  DatabaseAdapter(getActivity(),"hadith.db",1);
         final Cursor cursor = (Cursor) mAdapter.getChild(groupPosition, childPosition);
          final String accountGuid = cursor.getString(cursor.getColumnIndex("_id"));
//          changeAccount(accountGuid, true);
        String  query = "SELECT [Hadith] FROM [Hadith] where HadithID=1";

             Cursor selectedrow = mDbHelper.selectQuery(query);
             String  Paragraph = selectedrow.getString(selectedrow
                        .getColumnIndex("Hadith"));

    //  return Paragraph;
             return accountGuid;
        // TODO Auto-generated method stub

    }

      @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    private View fillData() {
             mDbHelper =new  DatabaseAdapter(getActivity(),"hadith.db",1);
            // mDbHelper.open();
                mGroupsCursor = mDbHelper.selectQuery("SELECT [ChapterID] as _id,[ChapterName]  FROM [Chapters]  ");

                 getActivity().startManagingCursor(mGroupsCursor);
                mGroupsCursor.moveToFirst();
              //  final ExpandableListView chapterListView = new ExpandableListView(getActivity());
                mAdapter = new HadithExpandableListAdapter(mGroupsCursor, getActivity(),
                        android.R.layout.simple_expandable_list_item_1,
                       android.R.layout.simple_expandable_list_item_2,
                        new String[] { "ChapterName" },
                        new int[] { android.R.id.text1 },
                        new String[] { "Hadith" },
                        new int[] { android.R.id.text1 });
                chapterListView.setAdapter(mAdapter);

                chapterListView.setOnChildClickListener(new OnChildClickListener()
                         {

                             @Override
                             public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
                             {
                                 chapterListView.setSelector(android.R.color.darker_gray);
                                 updateDetail(groupPosition,childPosition,id );
//                              //   System.out.println("Item: " + parent.getExpandableListAdapter().getChild(groupPosition, childPosition));
//                              Toast.makeText(getActivity().getBaseContext(),
//                              "Exception" + "Item: " + parent.getExpandableListAdapter().getChild(groupPosition, childPosition), childPosition).show();
//                    
//                            //  ChildClick(childPosition);


                                 return true;
                             }
                         });
                mDbHelper.close();
                return chapterListView;

            }


      public class HadithExpandableListAdapter extends SimpleCursorTreeAdapter {

            public HadithExpandableListAdapter(Cursor cursor, Context context,
                    int groupLayout, int childLayout, String[] groupFrom,
                    int[] groupTo, String[] childrenFrom, int[] childrenTo) {
                super(context, cursor, groupLayout, groupFrom, groupTo,
                        childLayout, childrenFrom, childrenTo);
            }

            @SuppressLint("NewApi")
            @Override
            protected Cursor getChildrenCursor(Cursor groupCursor) {
                Cursor childCursor = mDbHelper.selectQuery("SELECT [HadithID] as _id,[Hadith] ,ChapterID FROM [Hadith] where ChapterID=1 ");
                getActivity().startManagingCursor(childCursor);
                childCursor.moveToFirst();
                return childCursor;
            }

        }

    }

和DatabaseAdapter的这段代码

package rewaya.books.ahadithviewer.database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DatabaseAdapter extends SQLiteOpenHelper {

    private Context mycontext;

    private String DB_PATH = "data/data/rewaya.books.ahadithviewer/databases/";
    private static String DB_NAME = "hadith.db";
    private  String DataBaseName;
    // the extension may be .sqlite
    // or .db
    public SQLiteDatabase myDataBase;

    public DatabaseAdapter(Context dummySectionFragment, String dbName, int dbVersion) {  
         super(dummySectionFragment, dbName, null, dbVersion);
         DataBaseName =dbName;
         this.mycontext = dummySectionFragment;
         boolean dbexist = checkdatabase();
         if (dbexist) {
         } else {
             System.out.println("Database doesn't exist");
             try {
                 createdatabase();
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
         }
    }  

    public void createdatabase() throws IOException {
        boolean dbexist = checkdatabase();
        if (dbexist) {
        } else {
            this.getReadableDatabase();
            try {
                copydatabase();
            } catch (IOException e) {
                throw new Error(e.toString());
            }
        }
    }

    private boolean checkdatabase() {
        boolean checkdb = false;
        try {
            String myPath = DB_PATH + DataBaseName;
            File dbfile = new File(myPath);
            checkdb = dbfile.exists();
        } catch (SQLiteException e) {
            System.out.println("Database doesn't exist");
        }

        return checkdb;
    }

    private void copydatabase() throws IOException {

        // Open your local db as the input stream
        InputStream myinput = mycontext.getAssets().open(DataBaseName);

        // Path to the just created empty db
        @SuppressWarnings("unused")
        String outfilename = DB_PATH + DataBaseName;

        // Open the empty db as the output stream
        OutputStream myoutput = new FileOutputStream(
                "data/data/rewaya.books.ahadithviewer/databases/"+DataBaseName);

        // transfer byte to inputfile to outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myinput.read(buffer)) > 0) {
            myoutput.write(buffer, 0, length);
        }

        // Close the streams
        myoutput.flush();
        myoutput.close();
        myinput.close();

    }

    public void open() {
        // Open the database
        String mypath = DB_PATH + DataBaseName;
        myDataBase = SQLiteDatabase.openDatabase(mypath, null,
                SQLiteDatabase.OPEN_READWRITE);

    }

    public synchronized void close() {
        myDataBase.close();
        super.close();
    }
    public Cursor selectQuery(String query) 
    {
        String myPath = DB_PATH + DataBaseName;
        //myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        myDataBase =  SQLiteDatabase.openDatabase(myPath,null, SQLiteDatabase.CREATE_IF_NECESSARY); 
        Cursor mCursor =myDataBase.rawQuery(query, null);
        mCursor.moveToFirst();      
        myDataBase.close();
        return mCursor;
    }
    public Cursor getEmpByName(int Id)
    {

     SQLiteDatabase db=this.getReadableDatabase();
     Cursor c = db.rawQuery("select * from GaddHyatek_Book where ID=1", null);
     return c;


    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }
}

0 个答案:

没有答案