2012-03-28 27 views
15

Tôi có một cơ sở dữ liệu SQLite mà tôi muốn truy vấn. Tôi muốn nhắm mục tiêu Android 2.2 thông qua ICS. Tôi đã xem qua bài viết this về cách thực hiện việc này, nhưng nó sử dụng mã không dùng nữa (không truy vấn không đồng bộ, nhưng trên chuỗi giao diện người dùng). Tôi đã đọc từ đó tôi có thể sử dụng CursorLoader cùng với LoaderManager để thực hiện tác vụ này, cách thực hành tốt nhất, ưa thích (như không bog xuống luồng giao diện người dùng).Sử dụng CursorLoader để truy vấn SQLite DB và điền vào AutoCompleteTextView

Sự cố đang tìm kiếm ví dụ ngắn gọn để giải thích cho tôi cách thực hiện việc này. 1) Nạp cơ sở dữ liệu, 2) truy vấn cơ sở dữ liệu, 3) sử dụng kết quả để điền một khung nhìn danh sách AutoCompletetextBox.

Ví dụ này có tồn tại không?

+0

Cũng cố gắng tìm một ví dụ như thế này. Những cái tôi thấy dường như thiếu một con trỏ. – kpierce8

+0

Tôi đang làm điều gì đó tương tự TẠI ĐÂY !! http://stackoverflow.com/questions/12854336/autocompletetextview-backed-by-cursorloader – toobsco42

Trả lời

1

Tôi biết đây là một câu hỏi cũ nhưng đối với những người ghé thăm trang này:

SimpleCursorAdapter có một constructor mới:

SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) 

cunstructor này không sử dụng chuỗi giao diện người dùng. Bạn có thể sử dụng nó safey.

0

Tôi đã tạo một lớp SQLiteHelper. Im trường hợp của tôi, tôi có một cơ sở dữ liệu SQLite mà tôi sao chép từ thư mục nội dung vào/data/thư mục dữ liệu nếu không có:

private DatabaseHelper(Context context, String name, CursorFactory factory, 
     int version) { 
    super(context, DB_NAME, null, 1); 
    this.mContext = context; 
} 

// getInstance() singleton 
public static synchronized DatabaseHelper getInstance(Context context) { 
    if (_instance == null) { 
     _instance = new DatabaseHelper(context,null,null,1); 
    } 
    return _instance; 
} 

@Override 
public void onCreate(SQLiteDatabase db) { 
    // Leave it blank, we don't want to create. 

} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    // Leave it blank, we don't want to upgrade 

} 

public void createDataBase() throws IOException{ 

    boolean dbExist = checkDataBase(); 

    if(dbExist){ 
     openDataBase(); 
     // check the version number; 
     SQLiteCursor cursor = runQuery("select versionNumber from version where VersionType = \"CURRENT\""); 
     if (cursor!=null){ 
      cursor.moveToFirst(); 
      int version = cursor.getInt(cursor.getColumnIndex("versionNumber")); 
      if (version!=SQL_VERSION){ 
       //TODO - grab the favorites and ingredients first. 
       ArrayList<String> favorites = getFavorites(); 
       // I think I need to close the db before erasing it, then open new one. 
       close(); 
       mContext.deleteDatabase(DB_NAME); 
       this.getReadableDatabase(); 
       copyDataBase(); 
       openDataBase(); 
       for (int i = 0; i<favorites.size();i++){ 
        insert(Constants.TABLE_FAVORITES,Constants.FAVORITE,favorites.get(i)); 
       } 
       close(); 
      } 
     } 
    }else{ 
     //By calling this method and empty database will be created into the default system path 
     //of your application so we are gonna be able to overwrite that database with our database. 
     this.getReadableDatabase(); 

     copyDataBase(); 
    } 
} 

private void copyDataBase(){ 

    //Open your local db as the input stream 
    InputStream myInput; 
    try { 
     myInput = mContext.getAssets().open(DB_NAME); 
     // Path to the just created empty db 
     String outFileName = LOCATION + 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(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

public void openDataBase() throws SQLException{ 
    //Open the database 
    String myPath = LOCATION + DB_NAME; 
    mDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); 

} 

@Override 
public synchronized void close() { 
    if(mDatabase != null) 
     mDatabase.close(); 
    super.close(); 
} 

public SQLiteCursor runQuery(String query){ 
    return (SQLiteCursor) mDatabase.rawQuery(query,null); 
} 

private boolean checkDataBase(){ 

    SQLiteDatabase checkDB = null; 

    try{ 
     String myPath = LOCATION + DB_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; 
} 

// all insert does is insert to favorites and into your bar. 
public void insert(String table, String column, String value) { 
    ContentValues values = new ContentValues(); 
    values.put(column, value); 
    mDatabase.insert(table, null, values); 

} 

public void delete(String table, String column, String value){ 
    mDatabase.delete(table,column+" = \""+value+"\"",null); 
} 

Để lấp đầy các ô tô Autocomplete TextView trên hoạt động của tôi:

startManagingCursor(mCursor); 
    // get instance of database helper class 
    mDatabaseHelper = DatabaseHelper.getInstance(this); 
    // create database for first time 
    try { 
     mDatabaseHelper.createDataBase(); 
    } catch (IOException e) { 
     //Log.i(TAG,"Could not create the database"); 
     e.printStackTrace(); 
    } 
    // open the database 
    mDatabaseHelper.openDataBase(); 
      mDrinks = this.populate(); 

phương pháp cư:

//populates by drinks 
private ArrayList<String> populate() { 
    ArrayList<String> items = new ArrayList<String>(); 
    mCursor = mDatabaseHelper.runQuery(
      "select "+ Constants.TITLE +" from " 
      +Constants.TABLE_DRINK+" order by " 
      +Constants.TITLE); 
    if (mCursor != null){ 
     mCursor.moveToFirst(); 
     while (!mCursor.isAfterLast()){ 
      items.add(mCursor.getString(mCursor.getColumnIndex(Constants.TITLE))); 
      mCursor.moveToNext(); 
     } 
    } 
    return items; 
} 

Sau đó, tôi đặt nó:

// when text changes, autocomplete happens 
    mSearchTextView = (AutoCompleteTextView) findViewById(R.id.search_drink); 
    mSearchTextView.setAdapter(
      new ArrayAdapter<String>(
        this, R.layout.list_item, mDrinks)); 
    mSearchTextView.setClickable(true); 
    // clear the text when the searchTextView is clicked. Necessary for 
    // clearing after pressing enter in an invalid drink. 
    mSearchTextView.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      mSearchTextView.setText(""); 

     } 
    }); 
    mSearchTextView.setOnItemClickListener(new OnItemClickListener(){ 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, 
       long arg3) { 
      // TODO - here we need to get the name, then search for ingredients and show everything in 
      // an alert dialog. Here is main logic. 
      buildDialog(parent.getItemAtPosition(position).toString()); 
     } 

    }); 
    mSearchTextView.setOnEditorActionListener(new OnEditorActionListener() { 

     @Override 
     public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
      if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { 
       InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
       in.hideSoftInputFromWindow(mSearchTextView 
         .getApplicationWindowToken(), 
         InputMethodManager.HIDE_NOT_ALWAYS); 
       Toast.makeText(v.getContext(), "Please Select a Drink from the Auto Complete or the List Shown", Toast.LENGTH_LONG).show(); 
      } 

      return false; 
     } 
    }); 

Hy vọng bạn hiểu. Tôi không thể cung cấp cho bạn nguồn đầy đủ của tôi vì đây là một ứng dụng thị trường mà tôi đã phát triển. Bạn có thể kiểm tra xem nó ra trước khi cố gắng để làm tất cả các công việc: https://play.google.com/store/apps/details?id=com.life.plus.studios.bartender.drink.recipes.light

+0

Cảm ơn. Tôi sẽ phải kiểm tra việc triển khai của bạn. Cũng giống như ứng dụng của bạn! – mraviator

+0

Np. Nếu bạn có thêm câu hỏi cho tôi biết kể từ khi tôi không đưa nguồn đầy đủ một số điều có thể gây nhầm lẫn. –

+6

Tôi sẽ downnvote, nhưng tôi không có đủ danh tiếng, bởi vì câu trả lời không thực hiện CursorLoader, đó là thực hành tốt nhất và những gì đã được yêu cầu. – CraPo

0

Tôi không có mã trên tay, nhưng tôi hỏi một câu hỏi tương tự trước đây:

Android db loading chat for chat application

Nếu bạn đọc nó một cách cẩn thận, bạn có thể tìm ra cách để sử dụng một CursorLoader cho cơ sở dữ liệu SQLite của bạn;)

Các vấn đề liên quan