[英]Custom Adapter Not Refreshing after Filter with SearchView - Android-
[英]Intregrating Searchview for custom sql and custom adapter
我已經搜索了很多東西,但是還沒有找到方法(也許是因為我是開發的入門者)。 我的項目在這里可用: https : //github.com/Heromine/Service-Notes 。
我正在嘗試搜索或過濾用戶輸入的文本。 我不確定該怎么做。 My是一個記筆記應用程序,因此它應搜索筆記的標題或內容。
我的適配器:
public class NotesAdapter extends BaseAdapter {
/** Wrapper para notas. Util para cambiar el fondo de los item seleccionados. */
public static final String KEY_TITLE = "title";
public static final String KEY_BODY = "body";
public static final String KEY_CATID = "id";
private static final String DATABASE_TABLE = "notes_schema-v%s.sql";
private SQLiteDatabase mDb;
public static class NoteViewWrapper {
private final Note note;
private boolean isSelected;
/**
* Contruye un nuevo NoteWrapper con la nota dada.
*
* @param note una nota.
*/
public NoteViewWrapper(Note note) {
this.note = note;
}
public Note getNote() {
return note;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
private static final DateFormat DATETIME_FORMAT = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
private final List<NoteViewWrapper> data;
/**
* Constructor.
*
* @param data la lista de notas a usar como fuente de datos para este adaptador.
*/
public NotesAdapter(List<NoteViewWrapper> data) {
this.data = data;
}
/** @return cuantos datos hay en la lista de notas. */
@Override
public int getCount() {
return data.size();
}
/**
* @param position la posición de la nota que se quiere
* @return la nota en la posición dada.
*/
@Override
public NoteViewWrapper getItem(int position) {
return data.get(position);
}
/**
* @param position una posición
* @return la misma posición dada
*/
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) { // inflar componente visual
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.notes_row, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else holder = (ViewHolder) convertView.getTag(); // ya existe, solo es reciclarlo
// Inicializa la vista con los datos de la nota
NoteViewWrapper noteViewWrapper = data.get(position);
holder.noteIdText.setText(String.valueOf(noteViewWrapper.note.getId()));
holder.noteTitleText.setText(noteViewWrapper.note.getTitle());
// Corta la cadena a 80 caracteres y le agrega "..."
holder.noteContentText.setText(noteViewWrapper.note.getContent().length() >= 80 ? noteViewWrapper.note.getContent().substring(0, 80).concat("...") : noteViewWrapper.note.getContent());
holder.noteDateText.setText(DATETIME_FORMAT.format(noteViewWrapper.note.getUpdatedAt()));
// Cambia el color del fondo si es seleccionado
if (noteViewWrapper.isSelected) holder.parent.setBackgroundColor(parent.getContext().getResources().getColor(R.color.selected_note));
// Sino lo regresa a transparente
else holder.parent.setBackgroundColor(parent.getContext().getResources().getColor(android.R.color.transparent));
return convertView;
}
/** Almacena componentes visuales para acceso rápido sin necesidad de buscarlos muy seguido.*/
private static class ViewHolder {
private TextView noteIdText;
private TextView noteTitleText;
private TextView noteContentText;
private TextView noteDateText;
private View parent;
/**
* Constructor. Encuentra todas los componentes visuales en el componente padre dado.
*
* @param parent un componente visual.
*/
private ViewHolder(View parent) {
this.parent = parent;
noteIdText = (TextView) parent.findViewById(R.id.note_id);
noteTitleText = (TextView) parent.findViewById(R.id.note_title);
noteContentText = (TextView) parent.findViewById(R.id.note_content);
noteDateText = (TextView) parent.findViewById(R.id.note_date);
}
}}
DatabaseHelper:
public class NotesDatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = NotesDatabaseHelper.class.getSimpleName();
private static final String DATABASE_SCHEMA_FILE_NAME_PATTERN = "notes_schema-v%s.sql";
private static final String DATABASE_NAME = "notes.db";
private static final int DATABASE_VERSION = 1;
private final Context context;
/**
* Construye un NotesDatabaseHelper.
*
* @param context el contexto donde se crea este NotesDatabaseHelper.
*/
public NotesDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
/**
* {@inheritDoc}
*/
@Override
public void onCreate(SQLiteDatabase db) {
Log.v(TAG, "Creating database version " + DATABASE_VERSION + "...");
InputStream fileStream = null;
try {
// lee archivo notes_schema-v%s.sql para extraer las sentencias SQL
fileStream = context.getAssets().open(String.format(DATABASE_SCHEMA_FILE_NAME_PATTERN, DATABASE_VERSION));
String[] statements = SQLFileParser.getSQLStatements(fileStream);
// ejecuta las sentencias
for (String statement : statements) {
Log.v(TAG, statement);
db.execSQL(statement);
}
} catch (IOException ex) {
Log.e(TAG, "Unable to open schema file", ex);
} finally {
if (fileStream != null) {
try {
fileStream.close();
} catch (IOException ex) {
Log.e(TAG, "Unable to close stream", ex);
}
}
}
}
/**
* {@inheritDoc}
*/
@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");
context.deleteDatabase(DATABASE_NAME);
onCreate(db);
}}
您可能需要其他文件,以便您可以檢查項目結構。 誰能在我的個人項目中做到這一點。 如果您想在Github上制作它或在此處發布文件,因為我不知道該怎么做才能使其正常工作。
在您的用戶輸入上放置一個TextWatcher
(我假設它是一個EditText
),您可以在此處找到一個示例。 然后在它的TextChangedListener
的onTextChanged
方法中處理輸入並進行數據庫搜索,然后刷新列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.