在android中加载现有数据库

时间:2012-11-11 00:44:35

标签: android database sqlite

  

可能重复:
  How to use an existing database with an Android application

我正在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;
  }

}

在主类

public class Home extends Activity实现OnClickListener {

ImageButton favBtn,catBtn,infoBtn,shareBtn;

DBHelper db;    

ListView lv;
List<Frase> values;
ArrayAdapter<Frase> adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.home);


    favBtn =(ImageButton) findViewById(R.id.favBtn);
    catBtn = (ImageButton) findViewById(R.id.catBtn);
    infoBtn = (ImageButton) findViewById(R.id.infoBtn);
    shareBtn = (ImageButton) findViewById(R.id.shareBtn);

    infoBtn.setOnClickListener(this);
    catBtn.setOnClickListener(this);
    favBtn.setOnClickListener(this);
    shareBtn.setOnClickListener(this);
    prepararFrases();     
}

@Override
public void onClick(View v) {

}

public void prepararFrases(){

    db.open();
      /*
    values = db.getTodasLasFrases();
    adapter = new ArrayAdapter<Frase>(this,
            android.R.layout.simple_list_item_1, values);

    //setListAdapter(adapter);


    for (Frase cn : values) {
        String log = "Id: "+cn.getId()+" ,Frase: " + cn.getFrase()+ " ,Autor: " + cn.getAutor();
        Log.d("Name: ", log);
    }  

    db.close();*/

}

}

错误:

11-10 21:45:08.366: E/AndroidRuntime(5535): Uncaught handler: thread main exiting due to uncaught exception
11-10 21:45:08.376: E/AndroidRuntime(5535): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.qbox/com.example.quotebox.Home}: java.lang.NullPointerException
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2503)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2519)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.ActivityThread.access$2200(ActivityThread.java:123)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1870)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.os.Looper.loop(Looper.java:123)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.ActivityThread.main(ActivityThread.java:4370)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at java.lang.reflect.Method.invokeNative(Native Method)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at java.lang.reflect.Method.invoke(Method.java:521)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at dalvik.system.NativeStart.main(Native Method)
11-10 21:45:08.376: E/AndroidRuntime(5535): Caused by: java.lang.NullPointerException
11-10 21:45:08.376: E/AndroidRuntime(5535):     at com.example.qbox.Home.prepararFrases(Home.java:74)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at com.example.qbox.Home.onCreate(Home.java:45)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2466)
11-10 21:45:08.376: E/AndroidRuntime(5535):     ... 11 more

2 个答案:

答案 0 :(得分:2)

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

db = new DBHelper(getBaseContext());

答案 1 :(得分:1)

请格式化帖子中的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();

它为null的原因(如果你已经在你的调试器中逐步介绍)是你没有初始化它,如:

db = new DBHelper(this);