使用带有来自DB的新数据的光标刷新ListView

时间:2012-04-02 10:00:20

标签: android database listview refresh adapter

我在刷新ListView时遇到问题。我调用我的ListView Activity,我使用带有游标的SQL语句从DB获取数据,我使用自定义适配器(扩展ListView)绘制BaseAdapter,所有工作正常。

我想在顶部放置EditText来搜索ListView上的项目,使用键入的文本过滤实际视图,相同的活动。我来自getText()EditText,并使用此文本制作新的SQL语句过滤结果。我已检查过光标是否有正确的过滤结果,但我使用adapter.notifyDataSetChanged()尝试更新ListView但没有任何反应(没有错误或强制关闭)。

有人可以帮我或者告诉我一些使用数据库获取这个简单搜索功能的技巧吗?我在ArrayLists + getFilter() + SimpleCursorAdapter找到了许多类似的问题,但它不适用于我的数据库和自定义适配器。

活动 ListaCaracteres:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(es.hsk.ap.R.layout.lista_caracteres);

    try{
        hanyuDBHelper = new HanyuSQLHelper(this);
        hanyuDB = hanyuDBHelper.getReadableDatabase();
        c = hanyuDB.rawQuery(" SELECT * FROM Caracteres ", null);
    }
    catch(SQLiteException ex)
    {
        Toast mensajeError=Toast.makeText(getApplicationContext(), "Error accediendo a los datos", Toast.LENGTH_SHORT);
        mensajeError.show();
        Log.e("LogLugares", "Error en getReadableDatabase()", ex);
    }


    adapter = new AdapterListaCaracteres(this,c);
    listaCaracteres = (ListView)findViewById(es.hsk.ap.R.id.listaCaracteres);
    listaCaracteres.setAdapter(adapter);

    buscador = (EditText)findViewById(R.id.buscador);
    buscador.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void onTextChanged( CharSequence arg0, int arg1, int arg2, int arg3)
        {
        }

        @Override
        public void beforeTextChanged( CharSequence arg0, int arg1, int arg2, int arg3)
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0)
        {
            // TODO Auto-generated method stub

            String texto="";
            texto=buscador.getText().toString();

            c = hanyuDB.rawQuery(" SELECT * FROM Caracteres WHERE significado LIKE '%"+texto+"%'", null);
            adapter.notifyDataSetChanged();
        }
    });
}

我的自定义适配器,AdapterListaCaracteres从BaseAdapter扩展:

public class AdapterListaCaracteres extends BaseAdapter implements ListAdapter{

private Context  mContext;
private Cursor  datos;
private LayoutInflater inflater;

public AdapterListaCaracteres(Context  context, Cursor  c){
    this.mContext = context;
    this.datos = c;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return datos.getCount();
}

@Override
public Object  getItem(int position) {
    // TODO Auto-generated method stub
    return datos.getString(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

public View  getView(int position, View  convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    View item = convertView;
    ViewHolder holder;

    inflater = (LayoutInflater) mContext.getSystemService(Context .LAYOUT_INFLATER_SERVICE);
    datos.moveToPosition(position);

    if(item==null){
        try{
            item = inflater.inflate(es.hsk.ap.R.layout.caracter, null);
        }
        catch(InflateException ex)
        {

        }


        holder = new ViewHolder();
        holder.caracter = (TextView)item.findViewById(es.hsk.ap.R.id.caracter);
        holder.pinyin = (TextView)item.findViewById(es.hsk.ap.R.id.pinyin);
        holder.significado = (TextView)item.findViewById(es.hsk.ap.R.id.significado);

        item.setTag(holder);
    }
    else{
        holder = (ViewHolder)item.getTag();
    }           

    holder.caracter.setText(datos.getString(2));            
    holder.pinyin.setText(datos.getString(3));  
    holder.significado.setText(datos.getString(4));

    return item;

}
static class ViewHolder{
    TextView caracter;
    TextView pinyin;
    TextView significado;
}
}

3 个答案:

答案 0 :(得分:1)

试试这个:

/*
 * Listener que actuará cuando se escriba en el EditText
 */
buscador.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        String texto = "";
        texto = buscador.getText().toString();
        c = hanyuDB.rawQuery(" SELECT * FROM Caracteres WHERE significado LIKE '%"                                                                                         + texto + "%'", null);

        AdapterListaCaracteres adapter2 = new AdapterListaCaracteres(getApplicationContext(), c, false);
        listaCaracteres.setAdapter(adapter2);
        return false;
    }

});
/*********************************************/

祝你好运;)

ALEX

答案 1 :(得分:0)

重新初始化适配器而不是notifydatasetchanged():

    adapter = new AdapterListaCaracteres(this,c);
    listaCaracteres.setAdapter(adapter);

答案 2 :(得分:0)

现在它正在运作!我的一个朋友(感谢Muni!)找到了一种更好的方法来使用EditText过滤listview结果:

buscador.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

而不是:

buscador.addTextChangedListener(new TextWatcher()
{

感谢所有人的帮助。

修改

更新@AlexMuni和我自己的答案,onKey()方法在模拟器上运行完美,但在实际设备中无效。

我终于完成了以前的方法:

buscador = (EditText)findViewById(R.id.buscador); 
    buscador.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void onTextChanged( CharSequence arg0, int arg1, int arg2, int arg3)
        {
            texto = buscador.getText().toString();
            c = hanyuDB.rawQuery(
                    " SELECT * FROM Caracteres WHERE significado LIKE '%"
                            + texto + "%'", null);
            AdapterListaCaracteres adapter2 = new AdapterListaCaracteres(ListaCaracteres.this, c, false);
            listaCaracteres.setAdapter(adapter2);
        }

        @Override
        public void beforeTextChanged( CharSequence arg0, int arg1, int arg2, int arg3)
        {
        }

        @Override
        public void afterTextChanged(Editable arg0)
        {
        }
    });