2017-02-18 88 views
0

我是android.I的新手,我试图编写DBHelper类的代码来将android代码连接到数据库。 这里是我的DBHelper类....通过DBHelper类将代码连接到数据库

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

import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.Locale; 

/** 
* Created by user on 2/18/2017. 
*/ 

public class DBHelper extends SQLiteOpenHelper { 
    private static final String DATABASE_PATH ="/data  /data/manikz.myofflinedictionary/databases/"; 
    private static final String DATABASE_NAME = "dict1.db"; 
    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 db, int oldVersion, int newVersion) { 

    } 
    public void createDatabase(){ 
     createDB(); 
    } 
    private void createDB(){ 
     boolean dbExists = DBExists(); 
     if(!dbExists){ 
      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("SQLHelper","database not found"); 
     } 
     if(db !=null){ 
      db.close();; 
     } 
     return db !=null?true:false; 
    } 
    private void copyDBFromResource(){ 
     InputStream inputStream = null; 
     OutputStream outStream = null; 
     String dbFilePath = DATABASE_PATH + DATABASE_NAME; 
     try{ 
      inputStream = myContext.getAssets().open(DATABASE_NAME); 
      outStream = new FileOutputStream(dbFilePath); 
      byte[] buffer = new byte[1024]; 
      int length; 
      while((length = inputStream.read(buffer)) > 0){ 
       outStream.write(buffer,0,length); 
      } 
      outStream.flush(); 
      outStream.close(); 
      inputStream.close(); 

     }catch (IOException e){throw new Error("Problem copying database from the file"); 
     } 
    } 
} 

我正在以下error..Any帮助表示衷心的欢迎..... enter image description here

+0

改为使用[SQLiteAssetHelper](http://jgilfelt.github.io/android-sqlite-asset-helper/)。 –

+0

非常感谢先生,它工作正常..... – Mandy8055

回答

0

在下面的代码

SQLiteException取代 SQLException
}catch (SQLException e){ 
     Log.e("SQLHelper","database not found"); 
    }