0

我正在修改访问预填充数据库的代码。我遇到了 nullPointerException 错误,我不知道发生了什么。我将发布我的代码,如果有人可以提供帮助,我将不胜感激。

活动:

    public class Activity1c extends ListActivity {


IngredientHelper mDbHelper=null;
int char_property;
int char_name;
long a=1;

@Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act1c);
    mDbHelper = new IngredientHelper(this);

    Bundle extras = getIntent().getExtras();
    char_name = extras.getInt("char_name");
    char_property = extras.getInt("char_property");
    char_name+=1;
    char_property+=1;

    Toast.makeText(Activity1c.this,
            "The char_name you picked was " + char_name  + " and the property was "+char_property,
            Toast.LENGTH_LONG).show();



    Cursor notesCursor = mDbHelper.fetchNote(a);
    startManagingCursor(notesCursor);

    // Create an array to specify the fields we want to display in the list (only TITLE)
    String[] from = new String[]{IngredientHelper.COLUMN_TITLE,IngredientHelper.COLUMN_TITLE2};

    // and an array of the fields we want to bind those fields to (in this case just text1)
    int[] to = new int[]{R.id.craft_type_display,R.id.spec_type_display};




    // Now create a simple cursor adapter and set it to display
    SimpleCursorAdapter notes = 
        new SimpleCursorAdapter(this, R.layout.finalresult1, notesCursor, from, to);
    setListAdapter(notes);


}///end main




  }///end class

xml/act1c

     <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"


  android:layout_width="fill_parent"
    android:layout_height="fill_parent">

<ListView android:id="@+id/android:list"
      android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
<TextView android:id="@+id/android:empty"
      android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
  </LinearLayout>

xml/最终结果1

  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:orientation="vertical" >

   <TextView
    android:id="@+id/craft_type_display"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/spec_type_display"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

  </LinearLayout>

类/IngredientHelper

public class IngredientHelper extends SQLiteOpenHelper{

 //we declare a bunch of useful constants
//the should be pretty obvious what they are!
private static final String DATABASE_PATH = "/data   /data/com.android.Database_Practice_3_31_12/databases/";
private static final String DATABASE_NAME="infotest.sqlite";
private static final int SCHEMA_VERSION=1;
public static final String TABLE_NAME = "info";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TITLE = "name";
public static final String COLUMN_TITLE2 = "phone";
public static final String COLUMN_TITLE3 = "fav_color";
public static final String COLUMN_TITLE4 = "home_city";

public SQLiteDatabase dbSqlite;

private final Context myContext;

public IngredientHelper(Context context) {
    super(context, DATABASE_NAME, null, SCHEMA_VERSION);
    this.myContext = context;
    // check if exists and copy database from resource
    //createDB();
}

@Override
public void onCreate(SQLiteDatabase db) {
    // check if exists and copy database from resource

}

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

}
public void createDatabase() {
    createDB();
}

private void createDB() {

    boolean dbExist = DBExists();

    if (!dbExist) {

        //By calling this method we create an empty database into the default system location
        //We need this so we can overwrite that database with our database.
        this.getReadableDatabase();
        //now we copy the database we included!
        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 (SQLiteException 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 resource file.");

    }

}

public void openDataBase() throws SQLException {

    String myPath = DATABASE_PATH + DATABASE_NAME;
    dbSqlite = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READWRITE);

}

@Override
public synchronized void close() {

    if (dbSqlite != null)
    {
        dbSqlite.close();
    }
    super.close();

}


public Cursor getCursor() {

    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

    queryBuilder.setTables(TABLE_NAME);

    String[] asColumnsToReturn = new String[] { COLUMN_ID,COLUMN_TITLE};

    //make sure you get your search by string pass correctly!
    Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
            null, null, null, null);

    return mCursor;
}

public String getName(Cursor c) {
    return(c.getString(1));
}

public Cursor fetchNote(long rowId) throws SQLException {

    Cursor mCursor =

        dbSqlite.query(true, TABLE_NAME, new String[] {
                COLUMN_ID,  COLUMN_TITLE,COLUMN_TITLE2,COLUMN_TITLE3,COLUMN_TITLE4}, COLUMN_ID + "=" + rowId, null,
                null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}

}

日志猫

 04-04 19:54:50.764: E/AndroidRuntime(454): Uncaught handler: thread main exiting due to uncaught exception
 04-04 19:54:50.774: E/AndroidRuntime(454): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.Database_Practice_3_31_12/com.android.Database_Practice_3_31_12.Activity1c}: java.lang.NullPointerException
 04-04 19:54:50.774: E/AndroidRuntime(454):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
 04-04 19:54:50.774: E/AndroidRuntime(454):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
 04-04 19:54:50.774: E/AndroidRuntime(454):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
 04-04 19:54:50.774: E/AndroidRuntime(454):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
 04-04 19:54:50.774: E/AndroidRuntime(454):     at android.os.Handler.dispatchMessage(Handler.java:99)
 04-04 19:54:50.774: E/AndroidRuntime(454):     at android.os.Looper.loop(Looper.java:123)
 04-04 19:54:50.774: E/AndroidRuntime(454):     at android.app.ActivityThread.main(ActivityThread.java:4363)
04-04 19:54:50.774: E/AndroidRuntime(454):  at java.lang.reflect.Method.invokeNative(Native Method)
04-04 19:54:50.774: E/AndroidRuntime(454):  at java.lang.reflect.Method.invoke(Method.java:521)
04-04 19:54:50.774: E/AndroidRuntime(454):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-04 19:54:50.774: E/AndroidRuntime(454):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-04 19:54:50.774: E/AndroidRuntime(454):  at dalvik.system.NativeStart.main(Native Method)
04-04 19:54:50.774: E/AndroidRuntime(454): Caused by: java.lang.NullPointerException
04-04 19:54:50.774: E/AndroidRuntime(454):  at com.android.Database_Practice_3_31_12.IngredientHelper.fetchNote(IngredientHelper.java:173)
04-04 19:54:50.774: E/AndroidRuntime(454):  at com.android.Database_Practice_3_31_12.Activity1c.onCreate(Activity1c.java:49)
04-04 19:54:50.774: E/AndroidRuntime(454):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
 04-04 19:54:50.774: E/AndroidRuntime(454):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
4

1 回答 1

0

哎呀。很难遵循所有这些。

首先,您在 fetchNote() 中遇到错误。在堆栈跟踪中,从底部算起的第 5 行显示了这一点。您可以使用末尾的行号来接近它发生的位置。

我的猜测是查询失败。

我进一步的猜测是,这是因为您正试图通过从其他地方逐字节复制数据库来“恢复”数据库。我不相信这会奏效。在应用程序中提供预填充数据库的最佳方法是将其数据放在一个平面文件中,然后在应用程序首次运行时创建数据库并将数据写入其中。

在开发人员指南中,示例应用程序 SearchableDictionary 中的源文件 DictionaryDatabase.java 提供了示例代码。

于 2012-04-05T01:05:13.350 回答