-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 扩展 Activity {

// 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;
         }
     });

 }

. 还有 11 个 . 还有 11 个

4

1 回答 1

4

好像你从不实例化dbHelper

改变:

ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this);

至:

dbHelper = new ExternalDbOpenHelper(this);
于 2013-08-06T17:21:24.390 回答