繁体   English   中英

为自定义SQL和自定义适配器集成Searchview

[英]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 ),您可以在此处找到一个示例。 然后在它的TextChangedListeneronTextChanged方法中处理输入并进行数据库搜索,然后刷新列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM