2011-03-21 3 views
4

나는 자동 완성을 위해 사용되는 2 개의 테이블과 4000+ 개의 행을 포함하는 SQLite 데이터베이스를 가지고 있습니다. 자동 완성을 제공하기 위해 문자열 배열을 사용하는 매우 간단한 예제를 보았거나 연락처 목록을 사용하여 동일한 작업을 수행했습니다. 분명히 이들 중 어느 것도 내 경우에는 작동하지 않습니다. 자동 완성을 위해 내 자신의 자동 완성 데이터로 내 자신의 SQLite 데이터베이스를 어떻게 사용합니까? 콘텐츠 제공 업체를 만들어야합니까? 방법? 내가 찾을 수 없기 때문에 몇 가지 예를 들어주세요. SQLiteOpenHelper을 재정 의하여 데이터베이스를 assets 폴더에서/data/data/MY_PACKAGE/databases/안드로이드 폴더로 복사했습니다. 내 사용자 지정 SQLiteOpenHelper을 사용하는 CursorAdapter 사용자 지정을 만들고 runQueryOnBackgroundThread에서 커서를 반환합니다. 누락 된 _id 열에 대한 이상한 오류가 발생합니다. 테이블에 _id 열을 추가했습니다. 또한 Filterable 인터페이스가 무엇이고 언제 데이터가 필터링되는지 이해하지 못합니다. 어떤 메소드/클래스를 재정의해야합니까? 감사.cursoradapter를 사용하여 자동 완성을 구현하는 방법

답변

7

작동합니다.

here에서 SQLiteOpenHelper가 필요합니다. 기본적으로 데이터베이스를 자산 폴더에서 특정 폴더로 복사해야합니다. 그런 다음 사용자 지정 SQLiteOpenHelper를 사용하는 사용자 지정 CursorAdapter가 필요합니다.

다음은 내 활동을위한 onCreate 메소드입니다.


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

     KeywordsCursorAdapter kwadapter = new KeywordsCursorAdapter(this, null); 

     txtKeyword = (AutoCompleteTextView)this.findViewById(R.id.txtKeyword); 
     txtKeyword.setAdapter(kwadapter); 
     txtCity = (AutoCompleteTextView)this.findViewById(R.id.txtCity); 
     btnSearch = (Button)this.findViewById(R.id.btnSearch); 
     btnSearch.setOnClickListener(this); 
    } 

여기에 cursoradapter가 있습니다. 생성시 커서에 null을 전달할 수 있습니다. 여기


public class KeywordsCursorAdapter extends CursorAdapter { 

    private Context context; 

    public KeywordsCursorAdapter(Context context, Cursor c) { 
     super(context, c); 
     this.context = context; 
    } 

    //I store the autocomplete text view in a layout xml. 
    @Override 
    public View newView(Context context, Cursor cursor, ViewGroup parent) { 
     LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View v = inflater.inflate(R.layout.keyword_autocomplete, null); 
     return v; 
    } 

    @Override 
    public void bindView(View view, Context context, Cursor cursor) { 
     String keyword = cursor.getString(cursor.getColumnIndex("keyword")); 
     TextView tv = (TextView)view.findViewById(R.id.txtAutocomplete); 
     tv.setText(keyword); 
    } 

    //you need to override this to return the string value when 
    //selecting an item from the autocomplete suggestions 
    //just do cursor.getstring(whatevercolumn); 
    @Override 
    public CharSequence convertToString(Cursor cursor) { 
     //return super.convertToString(cursor); 
     String value = ""; 
     switch (type) { 
     case Keywords: 
      value = cursor.getString(DatabaseHelper.KEYWORD_COLUMN); 
      break; 
     case Cities: 
      value = cursor.getString(DatabaseHelper.CITY_COLUMN); 
      break; 
     } 
     return value; 
    } 

    @Override 
    public Cursor runQueryOnBackgroundThread(CharSequence constraint) { 
     //return super.runQueryOnBackgroundThread(constraint); 
     String filter = ""; 
     if (constraint == null) filter = ""; 
     else 
      filter = constraint.toString(); 
       //I have 2 DB-s and the one I use depends on user preference 
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); 
     //String selectedCountryCode = prefs.getString("selectedCountry", "GB"); 
     String selectedCountryCode = prefs.getString(context.getString(R.string.settings_selected_country), "GB"); 
     selectedCountryCode += ""; 

       //Here i have a static SQLiteOpenHelper instance that returns a cursor. 
     Cursor cursor = MyApplication.getDbHelpers().get(selectedCountryCode.toLowerCase()).getKeywordsCursor(filter); 
     return cursor; 
    } 
} 

커서를 반환하는 부분이다 : 그것은 같은 조건 단지 선택입니다.


public class DatabaseHelper extends SQLiteOpenHelper { 

... 

    public synchronized Cursor getKeywordsCursor (String prefix) { 
     if (database == null) database = this.getReadableDatabase(); 
     String[] columns = {"_id", "keyword"}; 
     String[] args = {prefix}; 

     Cursor cursor; 
     cursor = database.query("keywords", columns, "keyword like '' || ? || '%'", args, null, null, "keyword", "40"); 

     int idcol = cursor.getColumnIndexOrThrow("_id"); 
     int kwcol = cursor.getColumnIndexOrThrow("keyword"); 

     while(cursor.moveToNext()) { 
      int id = cursor.getInt(idcol); 
      String kw = cursor.getString(kwcol); 
      Log.i("keyword", kw); 
     } 

     cursor.moveToPosition(-1); 
     return cursor; 
    } 

... 

} 

사용자 지정 콘텐츠 공급자를 만들 수도 있지만이 경우 재정의해야 할 쓸모없는 클래스 일 수 있습니다.

+0

그 선택 조건은 무엇을 의미합니까? – adrian

+0

'select _id, keyword from keyword '와 같은 키워드.' '|| ? || '%''. '?'는 매개 변수입니다. '||'는 연결입니다. 매개 변수를 빈 문자열로 연결 한 문자열로 변환하는 방법을 잘 모르겠습니다. 아마'? || '%' ' –

+0

비슷한 문제가 있지만 고정시킬 수 없습니다. | ... cursor = database.query ("키워드", 열, "키워드' '||||'% '"와 같은 키워드 , args, null, null, "keyword", "40"); ..... 이제 첫 번째 "keywords"는 테이블의 이름입니까? 그리고 여전히 '키워드' '||'| '' '...'와 같은 의미로 ".... IS"키워드는 "대체 할 수없는 메시지"라는 의미를 갖지 않습니다. "?" 매개 변수입니다 .... 아직 그것을 얻지 않습니다. 내가 조금 더 설명해 주시면 – adrian

관련 문제