0

可能重复:
如何将现有数据库与 Android 应用程序一起使用

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

}

在主班

公共类 Home 扩展 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
4

2 回答 2

2

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

db = new DBHelper(getBaseContext());
于 2012-11-11T00:52:56.857 回答
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);
于 2012-11-11T00:57:19.250 回答