在android中加载现有数据库

在android中加载现有数据库,android,database,sqlite,Android,Database,Sqlite,可能重复: 我正在用Android做一个项目,我正在尝试将现有数据库加载到我的应用程序中。我发现了一个错误 public class DBHelper extends SQLiteOpenHelper{ private static String DB_PATH = "/data/data/com.example.qbox/databases/"; private static String DB_NAME = "frases.db"; private SQLiteDatabase myD

可能重复:

我正在用Android做一个项目,我正在尝试将现有数据库加载到我的应用程序中。我发现了一个错误

public class DBHelper extends SQLiteOpenHelper{

private static String DB_PATH = "/data/data/com.example.qbox/databases/";
private static String DB_NAME = "frases.db";

private SQLiteDatabase myDatabase;
private final Context _context;

public static final String KEY_ID = "_id";
public final static String KEY_FRASE = "frase";
public final static String KEY_AUTOR = "autor";
public final static String KEY_CATEGORIA = "categoria";
public final static String KEY_FAVORITA = "favorita";

public static final String DATABASE_TABLE = "frases";

private static final String[] cols = new String[] { KEY_ID, KEY_FRASE, KEY_AUTOR, KEY_CATEGORIA, KEY_FAVORITA};


public DBHelper(Context context) {

        super(context, DB_NAME, null, 1);
        this._context = context;
    }        


/**
* create new db and then rewrite records.
* */
public void createDataBase() throws IOException{

    boolean dbExist = checkDataBase();

    if(dbExist){
        // dn exists ... nothing to do
    } else {
      this.getReadableDatabase();
    try {

    copyDataBase();

    } catch (IOException e) {
    throw new Error("Error copiando Base de Datos");
    }
}

}

/**
* Check if db exists
*/
private boolean checkDataBase(){

SQLiteDatabase checkDB = null;

try{

String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

} catch(SQLiteException e) {

}
if(checkDB != null){

    checkDB.close();

}
return checkDB != null ? true : false;
}

/**
*  Copy Database
 **/
private void copyDataBase() throws IOException{

    InputStream myInput = _context.getAssets().open(DB_NAME);
    String outFileName = DB_PATH + DB_NAME;
    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while (( length = myInput.read(buffer)) > 0){
        myOutput.write(buffer, 0, length);
    }

    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void open() throws SQLException{
    try {
        createDataBase();
    } catch (IOException e) {
        throw new Error("Ha sido imposible crear la Base de Datos");
    }

    String myPath = DB_PATH + DB_NAME;
    myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}

@Override
public synchronized void close() {
    if(myDatabase != null)
        myDatabase.close();
    super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

/**
* INSERTAR NUEVA FRASE
* */
public long insertarFrase(Integer id,String frase, String autor, String categoria, String favorita ) {
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_ID, id);
    newValues.put(KEY_FRASE,frase);
    newValues.put(KEY_AUTOR, autor);
    newValues.put(KEY_CATEGORIA, categoria);
    newValues.put(KEY_FAVORITA, favorita);
    return myDatabase.insert(DATABASE_TABLE, null, newValues);
}

/**
* BORRAR FRASE CON _id = _rowIndex
* */
public boolean removerFrase(long _rowIndex) {
    return myDatabase.delete(DATABASE_TABLE, KEY_ID + "=" + _rowIndex, null) > 0;
}

/**
* ACTUALIZAR FRASE _id = _rowIndex
* */
public boolean updateFrase(Integer _rowIndex, String frase, String autor, String categoria, String favorita ) {
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_FRASE,frase);
    newValues.put(KEY_AUTOR, autor);
    newValues.put(KEY_CATEGORIA, categoria);
    newValues.put(KEY_FAVORITA, favorita);
    return myDatabase.update(DATABASE_TABLE, newValues, KEY_ID + "=" + _rowIndex, null) > 0;
}


  public List<Frase> getTodasLasFrases() {
        List<Frase> contacts = new ArrayList<Frase>();

        Cursor cursor = myDatabase.query(DBHelper.DATABASE_TABLE,
            cols, null, null, null, null, null);

        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
          Frase frase = cursorFrase(cursor);
          contacts.add(frase);
          cursor.moveToNext();
        }
        cursor.close();
        return contacts;
      }
  private Frase cursorFrase(Cursor cursor) {
      Frase frase = new Frase();
          frase.setId(cursor.getLong(0));
          frase.setFrase(cursor.getString(1));
          frase.setAutor(cursor.getString(2));
          frase.setCat(cursor.getString(3));
          frase.setFav(cursor.getString(4));
      return frase;
  }
  public Frase getContact(int id) {

        Cursor cursor = myDatabase.query(DBHelper.DATABASE_TABLE, cols, this.KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Frase frase = cursorFrase(cursor);

        return frase;
  }

尝试打开db时出现nullPointerException。您已经声明了它,但没有创建它的实例。在onCreate()方法的主活动中,创建DBHelper类的新实例,然后将上下文作为参数传递给其构造函数:

db = new DBHelper(getBaseContext());

尝试打开db时出现nullPointerException。您已经声明了它,但没有创建它的实例。在onCreate()方法的主活动中,创建DBHelper类的新实例,然后将上下文作为参数传递给其构造函数:

db = new DBHelper(getBaseContext());

请在您的帖子中设置logcat跟踪的格式。否则很难阅读

还请学习如何理解异常堆栈跟踪以及如何调试应用程序。这将节省包括你在内的所有人的时间

logcat显示空指针异常在prepareFrases()中,特别是第74行

Caused by: java.lang.NullPointerException 11-10 21:45:08.376: E/AndroidRuntime(5535): at com.example.qbox.Home.prepararFrases(Home.java:74) 
您没有告诉我们第74行是什么,但因为它只包含一条可执行语句,所以它必须是这样的:

db.open();
它为空的原因(如果您在调试器中进行了调试,您就会知道)是因为您没有初始化它,例如:

db = new DBHelper(this);

请在你的帖子中设置logcat跟踪的格式,否则很难阅读

还请学习如何理解异常堆栈跟踪以及如何调试你的应用程序。这将节省*所有人(包括你)的时间

logcat显示空指针异常在prepareFrases()中,特别是第74行

Caused by: java.lang.NullPointerException 11-10 21:45:08.376: E/AndroidRuntime(5535): at com.example.qbox.Home.prepararFrases(Home.java:74) 
您没有告诉我们第74行是什么,但因为它只包含一条可执行语句,所以它必须是这样的:

db.open();
它为空的原因(如果您在调试器中进行了调试,您就会知道)是因为您没有初始化它,例如:

db = new DBHelper(this);

对不起,我对这个页面和android都很陌生。。。我觉得有点傻!非常感谢您的回答。对不起,我对这个页面和android都很陌生。。。我觉得有点傻!非常感谢你的回答。