2017-02-14 4 views
0

У меня возникли трудности с созданием собственного поиска, загрузкой его из базы данных и отображением данных в списке.Как создать собственную поисковую загрузку из собственных данных?

Теперь мое приложение работает, когда я нажимаю кнопку поиска, появляется список поиска, но я не могу выполнять поиск. Когда я начинаю писать свой поиск в поисковом окне, приложение не находит и не фильтрует мой список, также когда я отправляю поиск, мои приложения возвращаются к mainActivity, отображающему мой список поиска.

MainActivity

public class MainActivity extends AppCompatActivity { 

    /** Database helper that will provide us access to the database */ 
    private MarluvasDbHelper myDbHelper; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     myDbHelper = new MarluvasDbHelper(this); 
     try { 
      myDbHelper.createDataBase(); 

     } catch (IOException ice) { 
      throw new Error("Unable to connect"); 
     } 
     myDbHelper.openDataBase(); 

     // Create and/or open a database to read from it 
     //SQLiteDatabase db = myDbHelper.getReadableDatabase(); 
     //Toast.makeText(MainActivity.this, "Sucess", Toast.LENGTH_SHORT).show(); 
     //Toast.makeText(MainActivity.this, MarluvasContract.MarluvasEntry.COLUMN_COD, Toast.LENGTH_SHORT).show(); 
     //displayDatabaseInfo(); 
    } 

    private void displayDatabaseInfo(){ 
     // Create and/or open a database to read from it 
     SQLiteDatabase db = myDbHelper.getReadableDatabase(); 

     // Define a projection that specifies which columns from the database 
     // you will actually use after this query. 
     String[] projection = { 
       MarluvasContract.MarluvasEntry._ID, 
       MarluvasContract.MarluvasEntry.COLUMN_MODELO, 
       MarluvasContract.MarluvasEntry.COLUMN_COR}; 

     // Perform a query on the pets table 
     Cursor cursor = db.query(
       MarluvasContract.MarluvasEntry.TABLE_NAME, // The table to query 
       projection,   // The columns to return 
       null,     // The columns for the WHERE clause 
       null,     // The values for the WHERE clause 
       null,     // Don't group the rows 
       null,     // Don't filter by row groups 
       null);     // The sort order 

     ListView listView = (ListView) findViewById(R.id.list); 

     CustomAdapter adapter = new CustomAdapter(this, cursor, 0); 

     listView.setAdapter(adapter); 
    } 

    public Cursor getStudentListByKeyword(String search) { 
     //Open connection to read only 
     SQLiteDatabase db = myDbHelper.getReadableDatabase(); 

     // Define a projection that specifies which columns from the database 
     // you will actually use after this query. 
     String[] projection = { 
       MarluvasContract.MarluvasEntry._ID, 
       MarluvasContract.MarluvasEntry.COLUMN_MODELO, 
       MarluvasContract.MarluvasEntry.COLUMN_COR}; 

     //String whereClause = MarluvasContract.MarluvasEntry.COLUMN_MODELO+ "=?"; 
     //String [] whereArgs = {" LIKE '%" +search + "%' "}; 

     // Perform a query on the pets table 
     Cursor cursor = db.query(
       MarluvasContract.MarluvasEntry.TABLE_NAME, // The table to query 
       projection,   // The columns to return 
       null,     // The columns for the WHERE clause 
       null,     // The values for the WHERE clause 
       null,     // Don't group the rows 
       null,     // Don't filter by row groups 
       null);     // The sort order 



     ListView petListView = (ListView) findViewById(R.id.list); 

     CustomAdapter adapter = new CustomAdapter(this, cursor, 0); 

     petListView.setAdapter(adapter); 

     return cursor; 
    } 



    @Override 
    public void onResume(){ 
     super.onResume(); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 

     // Inflate the options menu from XML 
     MenuInflater inflater = getMenuInflater(); 
     inflater.inflate(R.menu.options_menu, menu); 

     // Get the SearchView and set the searchable configuration 
     SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); 
     SearchView searchView = (SearchView) menu.findItem(search).getActionView(); 

     // Assumes current activity is the searchable activity 
     searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); 
     searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default 


     searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { 

      @Override 
      public boolean onQueryTextSubmit(String s) { 
       getStudentListByKeyword(s); 

       return false; 
      } 

      @Override 
      public boolean onQueryTextChange(String s) { 
       getStudentListByKeyword(s); 

       return false; 
      } 

     }); 

     return true; 

    } 
} 

CustomAdapter

public class CustomAdapter extends CursorAdapter { 

    private LayoutInflater mInflater; 

    public CustomAdapter(Context context, Cursor c, int flags) { 
     super(context, c, flags); 
     mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    } 

    @Override 
    public View newView(Context context, Cursor cursor, ViewGroup parent) { 

     return LayoutInflater.from(context).inflate(R.layout.item, parent, false); 
    } 

    @Override 
    public void bindView(View view, Context context, Cursor cursor) { 

     // Find fields to populate in inflated template 
     TextView modelo = (TextView) view.findViewById(R.id.modelo); 
     TextView cor = (TextView) view.findViewById(R.id.cor); 

     // Extract properties from cursor 
     String stringModelo = cursor.getString(cursor.getColumnIndexOrThrow(MarluvasContract.MarluvasEntry.COLUMN_MODELO)); 
     String stringDescr = cursor.getString(cursor.getColumnIndex(MarluvasContract.MarluvasEntry.COLUMN_COR)); 

     // Populate fields with extracted properties 
     modelo.setText(stringModelo); 
     cor.setText(stringDescr); 


    } 
} 

Как я могу это исправить? Как реализовать метод setOnQueryTextListener?

Большое вам спасибо!

+0

'Что я должен делать?' ... вы должны показать нам минимальное представление о проблеме. Вы включили слишком много кода. –

+0

Проблема возникает в этом коде строки –

+0

cursor = queryPlace.getStudentList(); –

ответ

0
+0

Я попытался, и я получил ошибку в этом коде строки: Курсор курсор = db.rawQuery (selectQuery, null); в getStudentList –

+0

Я добавлю код создания таблицы ... Я использовал контракт и код для чтения моей базы данных из папки с ресурсами –

+0

Я добавил код контракта и базы данных –

Смежные вопросы