从现有数据库中检索数据并将其填充到列表视图中

时间:2014-11-25 08:53:37

标签: android

我想从我的数据库中检索我的sqlite数据,我想在listview中填充它。我按照教程并实现了代码。我创建了一个名为MYCATEGORY.db的数据库,并将其复制到我的assets文件夹中。但我收到异常“从资源文件中复制数据库的问题”

我的主要活动.java

public class MainActivity extends ActionBarActivity {

    private DBHelper dbhelper = null;
    private Cursor ourCursor = null;
    private  DBAdapter adapter= null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView myListView = (ListView) findViewById(R.id.listView1);      
        dbhelper = new DBHelper(this);
        dbhelper.createDatabase();
        dbhelper .openDataBase();
        ourCursor = dbhelper .getCursor();
        startManagingCursor(ourCursor);
        adapter= new DBAdapter (ourCursor);
        myListView.setAdapter(adapter);
    }

    class DBAdapter extends CursorAdapter {

        DBAdapter (Cursor c){

            super(MainActivity.this, c);            
        }

        public void bindView(View row, Context ctxt, Cursor c) {

            DBHolder holder =(DBHolder)row.getTag();
            holder.populateFrom(c,dbhelper);
        }

        @Override
        public View newView(Context ctxt, Cursor c, ViewGroup parent) {

            LayoutInflater inflater=getLayoutInflater();
            View row =inflater.inflate(R.layout.row,parent,false);
            DBHolder holder =new DBHolder(row);
            row.setTag(holder);
            return (row);
        }
    }

    static class DBHolder {

        private TextView name=null;
        DBHolder(View row){

            name=(TextView)row.findViewById(R.id.textView1);
        }

        void populateFrom(Cursor c,DBHelper r){

            name.setText(r.getName(c));
        }
    }
}

DBHelper.java

public class DBHelper extends SQLiteOpenHelper {

        private static final String DATABASE_PATH =    "/data/data/com.example.databaseapp/databases/";

    private static final String DATABASE_NAME= "MYCATEGORY.db";
    private static final String TABLE_NAME = "MYMAINTABLE";

    private static final String COLUMN_ID = "cat_id";
    private static final String  COLUMN_NAME= "cat_name";
    private static final int SCHEMA_VERSION = 1;
    public SQLiteDatabase dbSqlite;
    private final Context myContext;

    public DBHelper(Context context) {

        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
        this.myContext =context ;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {}

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

    void createDatabase() {

        createDB();
    }

    private void createDB() {

        boolean dbExist =DBExists();
        if(!dbExist ){

            this.getReadableDatabase();
            copyDBFromResource();
        }
    }

    private boolean DBExists(){

        SQLiteDatabase db=null;
        try {

            String databasePath =DATABASE_PATH + DATABASE_NAME ;
            db = SQLiteDatabase .openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
            db.setLocale(Locale.getDefault());
            db.setLockingEnabled(true);
            db.setVersion(1);
        }
        catch(SQLException e) {

            Log.e("sqlHelpeer ","database not found");
        }
        if(db != null){

            db.close();
        }
        return db!=null ? true :false;
    }

    private void copyDBFromResource(){

        InputStream inputstream = null;
        OutputStream outputstream = null;
        String dbFilePath = DATABASE_PATH +DATABASE_NAME;
        try{

            inputstream =myContext .getAssets() .open(DATABASE_NAME);
            outputstream =new FileOutputStream(dbFilePath);
            byte[] buffer =new byte[1024];
            int length;
            while ((length=inputstream.read(buffer)) > 0){

                outputstream.write(buffer,0,length);
            }
            outputstream.flush();
            outputstream.close();
            inputstream.close();
        }
        catch(IOException e){

            throw new Error("problem copyingg database from resource file");
        }
    }

    public void openDataBase() throws SQLException{

        String myPath =DATABASE_PATH + DATABASE_NAME;
        dbSqlite = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
    }

    public synchronized void close(){

        if(dbSqlite != null) {

            dbSqlite.close();
        }
        super.close();
    }

    public Cursor getCursor(){

        SQLiteQueryBuilder queryBulider = new SQLiteQueryBuilder();
        queryBulider .setTables(TABLE_NAME);
        String[] asColumnsToReturn = new String[] {COLUMN_ID,COLUMN_NAME};
        Cursor mCursor =queryBulider.query(dbSqlite, asColumnsToReturn, null, null,         null,null,"cat_name ASC" );
        return mCursor;
    }

    public String getName(Cursor c) {

        return(c.getString(1));
    }
}

这是我的日志猫

11-25 14:21:27.095: W/dalvikvm(18936): threadid=1: thread exiting with uncaught exception (group=0x40c89a68)
11-25 14:21:27.095: E/AndroidRuntime(18936): FATAL EXCEPTION: main
11-25 14:21:27.095: E/AndroidRuntime(18936): java.lang.Error: problem copyingg database  from resource file
11-25 14:21:27.095: E/AndroidRuntime(18936):    at   com.example.androiddatabaselist.DBHelper.copyDBFromResource(DBHelper.java:92)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at    com.example.androiddatabaselist.DBHelper.createDB(DBHelper.java:52)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at com.example.androiddatabaselist.DBHelper.createDatabase(DBHelper.java:45)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at com.example.androiddatabaselist.MainActivity.onCreate(MainActivity.java:26)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at android.app.Activity.performCreate(Activity.java:4470)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at android.app.ActivityThread.access$600(ActivityThread.java:128)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at android.os.Looper.loop(Looper.java:137)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at android.app.ActivityThread.main(ActivityThread.java:4514)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at java.lang.reflect.Method.invokeNative(Native Method)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at java.lang.reflect.Method.invoke(Method.java:511)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
11-25 14:21:27.095: E/AndroidRuntime(18936):    at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:0)

您的DATABASE_PATH错了。它应该是从/开始的绝对路径,

DATABASE_PATH =    "/data/data/com.example.databaseapp/databases/" 

在尝试复制文件之前,还应该检查目录是否存在。 E.g

   File file = new File(DATABASE_PATH);
   file.mkdirs();
   file.mkdir(); 
   outputstream =new FileOutputStream(new File(file, DATABASE_NAME));

而不是硬编码数据库路径,您应该使用Context.getDatabasePath(String name),例如

  mContext.getDatabasePath(mDataBaseName)

答案 1 :(得分:0)

我认为你在这里给出了错误的数据库名称DATABASE_NAME =" MYCATEGORY.db" 。请检查您的数据库名称是" MYCATEGORY.db"或不。

答案 2 :(得分:0)

更新数据库路径。请改用

ContextWrapper cw =new ContextWrapper(getApplicationContext());
DB_PATH =cw.getFilesDir().getAbsolutePath()+ "/databases/"; 

或者你也可以使用它

String outFileName = context.getDatabasePath() + dbname;