2013-08-06 46 views
-1
public class ExternalDbOpenHelper extends SQLiteOpenHelper{ 

private static final String TABLE_NAME = "hymn"; 

private final Context myContext; 

private static final String TAG = "ExternalDbOpenHelper"; 
//The Android's default system path of your application database. 

private static String DB_PATH = "/data/data/com.catholic_hymnal.arnold/databases/"; 
public static String HYMN_NAME = "KEY_HYMN"; 
public static String HYMN_ID = "_id" ; 
private SQLiteDatabase myDataBase; 
private static String DB_PATH = "/data/data/com.catholic_hymnal.arnold/databases/"; 

private static String DB_NAME = "hymnals"; 


public ExternalDbOpenHelper (Context context) { 

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

public void createDataBase() throws IOException{ 

boolean dbExist = checkDataBase(); 

if(dbExist){ 
    Log.d(TAG, "db exists"); 
this.getReadableDatabase(); 
//do nothing - database already exist 
}else{ 
File f = new File(DB_PATH); 
if (!f.exists()) { 
f.mkdir(); 
} 

this.getReadableDatabase(); 

try 
{ 
copyDataBase(); 
} 
catch (IOException e) 
{ 
throw new RuntimeException(e); 
} 
} 

} 


private boolean checkDataBase() { 
File dbFile = new File(DB_PATH + DB_NAME); 
return dbFile.exists(); 

} 



private void copyDataBase() throws IOException{ 

//Open your local db as the input stream 
InputStream myInput = myContext.getAssets().open(DB_NAME); 

// Path to the just created empty db 
String outFileName = DB_PATH + DB_NAME; 

//Open the empty db as the output stream 
OutputStream myOutput = new FileOutputStream(outFileName); 

//transfer bytes from the inputfile to the outputfile 
byte[] buffer = new byte[1024]; 
int length; 
while ((length = myInput.read(buffer))>0){ 
myOutput.write(buffer, 0, length); 
} 

//Close the streams 
myOutput.flush(); 
myOutput.close(); 
myInput.close(); 
} 

public void openDataBase() throws SQLException{ 

//Open the database 
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) { 
if (newVersion > oldVersion) 
    Log.v("Database Upgrade」, 「Database version higher than old.", null); 
    myContext.deleteDatabase(DB_NAME); 

} 

// Add your public helper methods to access and get content from the database. 
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy 
// to you to create adapters for your views. 


public Cursor fetchHymnByName(String inputText) throws SQLException { 
     Log.w(TAG, inputText); 
     Cursor mCursor = null; 
     if (inputText == null || inputText.length() == 0) { 
     mCursor = myDataBase.query(TABLE_NAME, new String[] {HYMN_ID,HYMN_NAME}, 
     null, null, null, null, null); 

     } 
     else { 
    mCursor = myDataBase.query(true, TABLE_NAME, new String[]  {HYMN_ID,HYMN_NAME}, 
     HYMN_NAME + " like '%" + inputText + "%'", null, 
     null, null, null, null); 
     } 
     if (mCursor != null) { 
     mCursor.moveToFirst(); 
     } 
     return mCursor; 

    } 

    public Cursor fetchAllHymns() { 

      String sql ="SELECT * FROM TABLE_NAME"; 

      Cursor mCur = myDataBase.rawQuery(sql, null); 
      if (mCur!=null) 
      { 
       mCur.moveToNext(); 
      } 
      return mCur; 
     } 

    public boolean deleteAllCountries() { 

      int doneDelete = 0; 
      doneDelete = myDataBase.delete(TABLE_NAME, null , null); 
      Log.w(TAG, Integer.toString(doneDelete)); 
      return doneDelete > 0; 

     } 



    } 

公共類PrepopSqliteDbActivity延伸活動{我不斷收到java.lang.NullPointerException。請在下面是我的課和日誌貓

// private static final String DB_NAME = "hymnals"; 

//A good practice is to define database field names as constants 


private ExternalDbOpenHelper dbHelper; 
private SimpleCursorAdapter dataAdapter; 

@Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    //Our key helper 

      dbHelper = new ExternalDbOpenHelper(this); 


    try { 
     try { 
         //dataabase is created 

      dbHelper.createDataBase(); 

     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     ///database is opened 
     dbHelper.openDataBase(); 




    } catch (SQLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    //That’s it, the database is open! 

    displayListView(); 
    dbHelper.deleteAllCountries(); 


} 

private void displayListView() { 

//all hymns are fetched 
    final Cursor cursor = dbHelper.fetchAllHymns(); 

    // The desired columns to be bound 
    String[] columns = new String[] { 

      ExternalDbOpenHelper.HYMN_ID, 
      ExternalDbOpenHelper.HYMN_NAME, 


    }; 

    // the XML defined views which the data will be bound to 
    int[] to = new int[] { 
    R.id.tVid, 
    R.id.name, 

    }; 

    // create the adapter using the cursor pointing to the desired data 
    //as well as the layout information 
    dataAdapter = new SimpleCursorAdapter(
    this, R.layout.country_info, 
    cursor, 
    columns, 
    to, 
    0); 

    ListView listView = (ListView) findViewById(R.id.listView1); 
    // Assign adapter to ListView 
    listView.setAdapter(dataAdapter); 


    listView.setOnItemClickListener(new OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> listView, View view, 
    int position, long id) { 
    // Get the cursor, positioned to the corresponding row in the result set 
    Cursor cursor = (Cursor) listView.getItemAtPosition(position); 

    // Get the state's capital from this row in the database. 
    String countryCode = 
    cursor.getString(cursor.getColumnIndexOrThrow("code")); 
    Toast.makeText(getApplicationContext(), 
    countryCode, Toast.LENGTH_SHORT).show(); 

    } 
    }); 

    EditText myFilter = (EditText) findViewById(R.id.myFilter); 
    myFilter.addTextChangedListener(new TextWatcher() { 

    public void afterTextChanged(Editable s) { 
    } 

    public void beforeTextChanged(CharSequence s, int start, 
    int count, int after) { 
    } 

    public void onTextChanged(CharSequence s, int start, 
    int before, int count) { 
    dataAdapter.getFilter().filter(s.toString()); 
    } 
    }); 

    dataAdapter.setFilterQueryProvider(new FilterQueryProvider() { 
     public Cursor runQuery(CharSequence constraint) { 
      try { 
       return dbHelper.fetchHymnByName(constraint.toString()); 
      } catch (SQLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      return cursor; 
     } 
    }); 

} 

// LOgCAts 堆棧跟蹤: // 08-06 13:18:49.946:E/AndroidRuntime(1462 ):致命例外:main 08-06 13:18:49.946:E/AndroidRuntime(1462):java.lang.RuntimeException:無法啓動活動ComponentInfo {com.catholic_hymnal.arnold/com.catholic_hymnal.arnold.PrepopSqliteDbActivity}: java.lang.NullPointerException 08-06 13:18:49.946:E/AndroidRuntime(1462):at android.app.ActivityTh read.performLaunchActivity(ActivityThread.java:2180) 08-06 13:18:49.946:E/AndroidRuntime(1462):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 08-06 13:18: 49.946:E/AndroidRuntime(1462):at android.app.ActivityThread.access $ 600(ActivityThread.java:141) 08-06 13:18:49.946:E/AndroidRuntime(1462):at android.app.ActivityThread $ H (Handle.java:99) 08-06 13:18:49.946 :E/AndroidRuntime(1462):在android.os.Looper.loop(Looper.java:137) 08-06 13:18:49.946:E/AndroidRuntime(1462):在android.app.ActivityThread.main(ActivityThread .java:5039) 08-06 13:18:49.946:E/AndroidRuntime(1462):at java.lang.reflect.Method .invokeNative(Native Method) 08-06 13:18:49.946:E/AndroidRuntime(1462):at java.lang.reflect.Method.invoke(Method.java:511) 08-06 13:18:49.946: E/AndroidRuntime(1462):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793) 08-06 13:18:49.946:E/AndroidRuntime(1462):at com.android。 internal.os.ZygoteInit.main(ZygoteInit.java:560) 08-06 13:18:49.946:E/AndroidRuntime(1462):at dalvik.system.NativeStart.main(Native Method) 08-06 13:18 :49.946:E/AndroidRuntime(1462):導致:java.lang.NullPointerException 08-06 13:18:49.946:E/AndroidRuntime(1462):at com.catholic_hymnal.arnold.PrepopSqliteDbActivity.displayListView(PrepopSqliteDbActivity.java: 65) 08-06 13:18:49.946:E/AndroidRuntime(1462):at com.catholic_hymnal.arnold.Prepo E/AndroidRuntime(1462):at android.app.Activity.performCreate(Activity.java:5104) 08-06 13:18: 49.946:E/AndroidRuntime(1462):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 08-06 13:18:49.946:E/AndroidRuntime(1462):at android.app.ActivityThread.performLaunchActivity ActivityThread.java:2144) 08-06 13:18:49.946:E/AndroidRuntime(1462):... 11多個

+0

什麼是'PrepopSqliteDbActivity'的65行? – codeMagic

回答

4

好像你從來沒有實例dbHelper

變化:

ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this); 

要:

dbHelper = new ExternalDbOpenHelper(this); 
+0

@ user2476688請將此答案標記爲已解決,並在必要時創建另一個問題。 – JRomero

+0

這是我現在得到的錯誤08-06 13:05:54.056:E/AndroidRuntime(1192):java.lang.RuntimeException:無法啓動活動ComponentInfo {com.catholic_hymnal.arnold/com.catholic_hymnal.arnold.PrepopSqliteDbActivity} :android.database.sqlite.SQLiteReadOnlyDatabaseException:嘗試寫一個只讀數據庫(代碼8) – Azeem

+0

好吧謝謝你@ J.Romero。上帝保佑 – Azeem

相關問題