2016-01-04 1 views
0

J'ai déjà beaucoup cherché mais je n'ai pas trouvé un moyen (c'est peut-être parce que je suis un démarreur au développement). Mon projet est disponible ici: https://github.com/Heromine/Service-Notes. J'essaie de rechercher ou de filtrer le texte saisi par l'utilisateur. Je ne suis pas sûr de comment je peux le faire. My est une application de prise de notes, il devrait donc rechercher le titre ou le contenu d'une note.Intregrating Searchview pour personnalisé SQL et adaptateur personnalisé

Mon adaptateur:

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

Vous pouvez avoir besoin d'autres fichiers afin que vous puissiez vérifier la structure du projet. Quelqu'un peut-il faire dans mon projet personnel. Si vous voulez le faire sur Github ou poster le fichier ici, parce que je ne sais pas quoi faire pour le faire fonctionner.

+0

Copie possible de [SearchView dans ListView ayant un adaptateur personnalisé] (http://stackoverflow.com/questions/23422072/searchview-in-listview-having-a-custom-adapter) – DhiaTN

Répondre

0

Placez un TextWatcher sur votre entrée utilisateur (je suppose que c'est un EditText), vous pouvez trouver un exemple here. Puis dans sa méthode onTextChanged gérer l'entrée et faire une recherche dans la base de données, après que rafraîchir votre liste.