我遇到了这个问题,我想知道我能得到一些帮助。我有以下代码。
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.Resources.NotFoundException;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.AsyncTask;
import android.util.Log;
/**
* Simple notes database access helper class. Defines the basic CRUD operations
* for the notepad example, and gives the ability to list all notes as well as
* retrieve or modify a specific note.
*
* This has been improved from the first version of this tutorial through the
* addition of better error handling and also using returning a Cursor instead
* of using a collection of inner classes (which is less scalable and not
* recommended).
*/
public class recoverAnimalDBHelper extends SQLiteOpenHelper{
private static String DB_PATH = "/data/data/com.recover.foundanimal/databases/";
public static final String KEY_BIRDGROUP = "birdgroup";
public static final String KEY_BIRD_LATINNAME = "birdlatinname";
public static final String KEY_BIRD_COMMONNAME = "birdcommonname";
public static final String KEY_BIRD_REGIONFOUND = "birdregionfound";
public static final String KEY_BIRD_SUBREGION = "birdsubregion";
public static final String KEY_ROWID = "_id";
private static final String TAG = "RECOVERAnimalDBHelper";
private static SQLiteDatabase mDb;
private static final String DATABASE_NAME = "recoveranimals.sqlite";
private static final String DATABASE_BIRD_SPECIES_TABLE = "birds";
private static int DATABASE_VERSION = 1;
/**
* Database creation sql statement
*/
private static final String CREATE_BIRD_SPECIES_TABLE =
"create table "+DATABASE_BIRD_SPECIES_TABLE+" ("+KEY_ROWID+" integer primary key autoincrement, "
+ KEY_BIRDGROUP+" text not null, "
+ KEY_BIRD_LATINNAME+" text not null, "
+KEY_BIRD_COMMONNAME+" text not null, "
+KEY_BIRD_REGIONFOUND+" text not null, "
+KEY_BIRD_SUBREGION +" text not null); ";
protected static Context mCtx = null;
public recoverAnimalDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mCtx = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
// }
// if (!db.isReadOnly())
// {
// // Enable foreign key constraints
// db.execSQL("PRAGMA foreign_keys=ON;");
// }
// db.execSQL(CREATE_BIRD_SPECIES_TABLE);
// fillDatabase(db);
}
public void createDatabase() {
boolean dbExist = checkDataBase();
if(!dbExist) {
this.getWritableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}else {
this.getWritableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DATABASE_NAME;
mDb = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private static boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
private void fillDatabase(SQLiteDatabase db) {
db.beginTransaction();
Resources currResource = mCtx.getResources();
Field[] values = R.array.class.getDeclaredFields();
String[] birds = currResource.getStringArray(R.array.birdfamilies);
HashMap<String, String[]> birdFamToKey = new HashMap<String, String[]>(birds.length);
for(String bird : birds) {
String[] brdtyps = bird.split("b1234b");
birdFamToKey.put(brdtyps[brdtyps.length-1], brdtyps);
}
String[] specBird = null;
String birdGroup = null;
for(Field v : values) {
if(birdFamToKey.containsKey(v.getName())) {
try {
specBird = currResource.getStringArray(v.getInt(null));
birdGroup = birdFamToKey.get(v.getName())[0];
} catch (NotFoundException e) {
Log.w(TAG,""+v.getName()+" was not found in keyset with error: "+e.getLocalizedMessage());
continue;
} catch (IllegalArgumentException e) {
Log.w(TAG,""+v.getName()+" was not found in keyset with error: "+e.getLocalizedMessage());
continue;
} catch (IllegalAccessException e) {
Log.w(TAG,""+v.getName()+" was not found in keyset with error: "+e.getLocalizedMessage());
continue;
}
}
if(specBird != null && birdGroup != null) {
for(String brdspc : specBird) {
if(brdspc.contains("Family"))
continue;
String[] brdspcarr = brdspc.split("b1234b");
ContentValues initialValues = new ContentValues();
try {
initialValues.put(KEY_BIRDGROUP,birdGroup);
initialValues.put(KEY_BIRD_LATINNAME, brdspcarr[1]);
initialValues.put(KEY_BIRD_COMMONNAME, brdspcarr[0]);
if(brdspcarr.length>2) {
initialValues.put(KEY_BIRD_REGIONFOUND, brdspcarr[2]);
if(brdspcarr.length >3)
initialValues.put(KEY_BIRD_SUBREGION , brdspcarr[3]);
else
initialValues.put(KEY_BIRD_SUBREGION , "");
}else {
initialValues.put(KEY_BIRD_REGIONFOUND, "");
initialValues.put(KEY_BIRD_SUBREGION , "");
}
} catch (Exception e) {
Log.w(TAG, e.getLocalizedMessage()+"\nCAUSE: "+e.getMessage());
e.printStackTrace();
}
db.insertOrThrow(DATABASE_BIRD_SPECIES_TABLE, null, initialValues);
}
}
specBird = null;
}
db.endTransaction();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
// + newVersion + ", which will destroy all old data");
// db.execSQL("DROP TABLE IF EXISTS "+DATABASE_BIRD_SPECIES_TABLE);
// onCreate(db);
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private static void copyDataBase() throws IOException{
//Open your local db as the input stream
AssetManager assetManager = mCtx.getAssets();
InputStream myInput = assetManager.open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DATABASE_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();
}
@Override
public synchronized void close() {
if(mDb != null)
mDb.close();
super.close();
}
public void resetTables() {
this.onUpgrade(mDb, 1, 1);
}
/**
* Return a Cursor over the list of all birds in the database
*
* @return Cursor over all notes
*/
public Cursor fetchAllAnimals() {
Cursor mCursor = mDb.query(DATABASE_BIRD_SPECIES_TABLE, new String[] {KEY_ROWID,KEY_BIRDGROUP,KEY_BIRD_LATINNAME,
KEY_BIRD_COMMONNAME, KEY_BIRD_REGIONFOUND,KEY_BIRD_SUBREGION}, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/**
* Returns all unique macroclasses of animals
*
* @return Cursor to all bird types
*/
public Cursor fetchAllAnimalTypes() {
Cursor mCursor = mDb.query(true, DATABASE_BIRD_SPECIES_TABLE, new String[] {KEY_ROWID,KEY_BIRDGROUP}, null,null,null,null,KEY_BIRDGROUP+" ASC",null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/** Returns all animals species that mach an animal type
*
* @return Cursor pointing to all animal species matching the bird type selected
*/
public Cursor fetchAllAnimalSpecies(String animalType) {
Cursor mCursor = mDb.query(DATABASE_BIRD_SPECIES_TABLE,new String[] {KEY_ROWID,KEY_BIRD_COMMONNAME},KEY_BIRDGROUP+" = ?",new String[] {animalType},null,null,KEY_BIRD_COMMONNAME+" DESC");
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/**
* Return a Cursor positioned at the animal that matches the given rowId
*
* @param rowId id of animal to retrieve
* @return Cursor positioned to matching animal, if found
* @throws SQLException if note could not be found/retrieved
*/
public Cursor fetchAnimal(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_BIRD_SPECIES_TABLE, new String[] {KEY_ROWID,KEY_BIRDGROUP,KEY_BIRD_LATINNAME,
KEY_BIRD_COMMONNAME, KEY_BIRD_REGIONFOUND,KEY_BIRD_SUBREGION}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean isOpen() {
if( mDb != null && mDb.isOpen())
return true;
return false;
}
public Cursor fetchAnimalTypePartialMatching(String partialmatch) {
Cursor mCursor = mDb.query(true, DATABASE_BIRD_SPECIES_TABLE, new String[] {KEY_BIRDGROUP,KEY_ROWID}, KEY_BIRDGROUP+" LIKE ?",
new String[] {partialmatch},null,null,KEY_BIRDGROUP+" DESC",null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAnimalSpecificPartialMatching(String animalType, String partialmatch) {
Cursor mCursor = mDb.query(DATABASE_BIRD_SPECIES_TABLE, new String[]{KEY_BIRD_COMMONNAME,KEY_ROWID},
KEY_BIRDGROUP+" = ? AND "+KEY_BIRD_COMMONNAME+" LIKE ?",new String[] {animalType,partialmatch},null,
null,KEY_BIRD_COMMONNAME+" DESC");
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAnimalSpeciesParitalMatching(String partialmatch) {
Cursor mCursor = mDb.query(DATABASE_BIRD_SPECIES_TABLE, new String[]{KEY_BIRD_COMMONNAME,KEY_ROWID},
KEY_BIRD_COMMONNAME+" LIKE ?",new String[] {partialmatch},null,
null,KEY_BIRD_COMMONNAME+" DESC");
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor query(String[] m_projection, String selct, String[] args,
String m_sortOrder) {
Cursor mCursor = mDb.query(this.DATABASE_BIRD_SPECIES_TABLE, m_projection, selct, args, null, null, m_sortOrder);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
使用它的代码是:
AutoCompleteTextView actvMainType = (AutoCompleteTextView) findViewById(R.id.animalMainTypeTB);
actvMainType.setMaxLines(1);
SimpleCursorAdapter scaSpecTyp = new SimpleCursorAdapter(cntxt,R.layout.simpleautocompletelayout,mCursorMainType,
new String[] {recoverAnimalDBHelper.KEY_BIRDGROUP}, new int[] {R.id.autocompleteTxt});
scaSpecTyp.setStringConversionColumn(
mCursorMainType.getColumnIndexOrThrow(recoverAnimalDBHelper.KEY_BIRDGROUP));
scaSpecTyp.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
String partialItemName = null;
if (constraint != null) {
partialItemName = constraint.toString();
}
return rdbHelper.fetchAnimalTypePartialMatching(partialItemName);
}
});
actvMainType.setAdapter(scaSpecTyp);
actvMainType.setThreshold(1);
我试图让这个数据库工作,我似乎无法使自动完成工作。有什么建议吗?
非常感谢! 乔恩
答案 0 :(得分:2)
使用此网站:http://www.outofwhatbox.com/blog/2010/11/android-simpler-autocompletetextview-with-simplecursoradapter/我能够非常简单地解决这个问题。我的代码基本上非常草率,我没有正确使用LIKE术语。谢谢大家!