0

I already searched a lot but I haven't found a way (maybe it is because I am a starter at developing). My project is available here: https://github.com/Heromine/Service-Notes.

I am trying to search, or filter, the text the user input. I am not sure how can I do it. My is a note-taking app, so it should search for the title or the content of a note.

My adapter:

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);
}}

You may need other files so you can check the project structure. Can anyone make it in my personal project. If you want make it on Github or post the file here, because I don't know what to do to make it working.

halfer
  • 19,824
  • 17
  • 99
  • 186
Jonathan I
  • 240
  • 1
  • 4
  • 18
  • Possible duplicate of [SearchView In ListView having a custom Adapter](http://stackoverflow.com/questions/23422072/searchview-in-listview-having-a-custom-adapter) – Dhia Jan 04 '16 at 11:59

1 Answers1

0

Place a TextWatcher on your user input (I assume it's an EditText), you can find an example here. Then in it's TextChangedListener's onTextChanged method handle the input and make a database search, after that refresh your list.

Gex
  • 2,092
  • 19
  • 26