2012-04-05 4 views
0

미리 채워진 데이터베이스에 액세스하는 코드로 고민 중입니다. nullPointerException 오류가 발생하고 무슨 일이 일어나고 있는지 파악할 수 없습니다. 내 코드를 게시 할 것이고 누군가가 도움을 줄 수 있다면 크게 감사 할 것입니다.android prepopulated 데이터베이스 프로그램의 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/finalresult1

<?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) 
+0

시도해보십시오. http://stackoverflow.com/questions/9109438/using-already-created-database-with-android/9109728#9109728 –

+0

데이터베이스를 열지 못했습니다. 감사합니다. Yaqub !!! – codenamejupiterx

답변

0

우프. 이 모든 것을 따르기가 어렵습니다.

먼저 fetchNote()에서 오류가 발생합니다. 스택 추적에서 아래쪽의 다섯 번째 줄이이를 보여줍니다. 끝 부분에있는 회선 번호를 사용하여 에 도달 할 수 있습니다.이 발생합니다.

내 생각 엔 쿼리가 실패한 것 같습니다.

내 추측은 다른 곳에서 바이트 단위로 데이터베이스를 복사하여 데이터베이스를 "복원"하려고하기 때문입니다. 나는 이것이 효과가있을 것이라고 확신하지 못한다. 앱에 미리 채워진 데이터베이스를 제공하는 가장 좋은 방법은 데이터를 플랫 파일에 저장 한 다음 앱이 처음 실행될 때 데이터베이스를 만들고 데이터를 데이터에 기록하는 것입니다.

Developers Guide에서 샘플 앱 SearchableDictionary의 DictionaryDatabase.java 소스 파일은 이에 대한 예제 코드를 제공합니다.

관련 문제