通过DBHelper类将代码连接到数据库

时间:2017-02-18 14:42:41

标签: android database sqlite

我是android的新手。我正在尝试编写DBHelper类的代码来将android代码连接到数据库。 这是我的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");
        }
    }
}

我收到以下错误..非常欢迎任何帮助..... enter image description here

1 个答案:

答案 0 :(得分:0)

使用以下代码中的SQLiteException替换}catch (SQLException e){ Log.e("SQLHelper","database not found"); }

Runtime.getRuntime().exec("su & pm clear " + packagename);