Android的筛选和排序的ListView带适配器异步任务期间设置 [英] Android filter and sort ListView with adapter set during Async task

查看:472
本文介绍了Android的筛选和排序的ListView带适配器异步任务期间设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做的数据一个ListView我从放置在服务器的数据库中获取。 ListView中有两个TextViews的每一行,一个是城市,另一种为ID的每个城市都有在数据库上,但这个TextView的(编号的一种)从ListView中隐藏的,所以用户只能看到城市。

I'm making a ListView with data I get from a database placed in a server. The ListView has TWO TextViews for each row, one for the cities, and the other one for the ID's each city has on the database, but this textview(the ID's one) is HIDDEN from the ListView, so the user can only see cities.

一切工作正常,但现在我想一个搜索栏添加到列表视图,所以我可以过滤城市,但我发现了以下问题:

Everything works fine, but now I want to add a search bar to the listview so I can filter the cities, but i'm getting the following problems:

1,将ListView控件的适配器是一个简单的适配器,因为你可以在code看到的,我也没有发现如何筛选使用这种适配器列表视图的例子。

1.-The adapter of the ListView is a Simple Adapter, as you can see on the code, and I have found no examples of how to filter a Listview using such an adapter.

2 - 我获得了通过异步任务ListView中的信息,并建立内部的 onPostExecute 的将Async任务的方法,并再次,我已经找到了没有的ListView的例子过滤它当它在这样的地方。

2.-I'm getting the info for the ListView through an Async Task, and setting up the ListView inside the onPostExecute method of the Async Task, and again, I have found no examples of filtering it when its in such a place.

下面是相关的code。如果有人需要完整的code,就问我吧。

Here is the "relevant" code. If somebody needs the complete code, just ask me for it.

public class SQLWebVer extends ListActivity implements OnItemClickListener{
ProgressDialog barraProgreso;
    ArrayList<HashMap<String, String>> listaCiudades;
    .
    .//some more varibles for the class
    .
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sqlwebver);

    // Hashmap de la ListView
    listaCiudades = new ArrayList<HashMap<String, String>>();

    new cargaCiudades().execute();//this is the call to the async task

    }
    class cargaCiudades extends AsyncTask<String, String, String>{//the async task
    .
    .//here are the onPreExecute and doInBackground methods
    .
         protected void onPostExecute(String file_url) {
        barraProgreso.dismiss();//quita la barra de la pantalla
        runOnUiThread(new Runnable(){//actualiza la UI(la listView)

            public void run() {
                // TODO Auto-generated method stub
                ListAdapter adapter = new SimpleAdapter 
                                      (SQLWebVer.this, listaCiudades, 
                                      R.layout.sqlweblist_item,
                          new String[]{"key_id", "key_ciudad"},new int[]
                                      {R.id.ID_CIUDAD, R.id.CIUDAD});

                setListAdapter(adapter);
            }

        });
        }
     }

我曾尝试添加的过滤功能无论是在的onCreate和onPostExecute方法,但没有运气的话,有什么建​​议?

I have tried to add the filter feature both on the onCreate and onPostExecute method, but with no luck so, any suggestions?

Pd积:?奖金的问题,我怎么可能由城市按字母顺序排序我的ListView但保持与他的城市每个ID(不改变PHP文件)

P.D:BONUS question, how could I sort my ListView alphabetically by cities but keeping each ID related to his city?(without changing the php files)

编辑:我通过创建实现过滤定制底座适配器解决了这个问题。 Wasn't很难,因为我想在第一;)

I solved the problem by creating a Custom Base Adapter which implements filterable. Wasn´t as hard as I thought at first ;)

推荐答案

前段时间我解决了这个问题,但我忘了张贴为我工作的答案,所以这里是:

Some time ago I solved this problem but I forget to post the answer that worked for me, so here it is:

package android.codigo;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;


public class MiAdaptador extends ArrayAdapter<Item2> {

    private ArrayList<Item2> allItems;
    @SuppressWarnings("unused")
    private ArrayList<Item2> subItems;

    public ArrayList<Item2> getItems() {
        return allItems;
    }

    public MiAdaptador(Context context, int textViewResourceId,
            ArrayList<Item2> items) {
        super(context, textViewResourceId, items);
        this.allItems = items;
        this.subItems = items;
    }

    @Override
     public int getCount(){
           return subItems.size();
     }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.item2_lista, null);
        }

        Item2 it = subItems.get(position);

        if (it != null) {
            TextView nombre = (TextView) v.findViewById(R.id.textView1);
            ImageView img = (ImageView) v.findViewById(R.id.imageView1);
            ImageView img2 = (ImageView) v.findViewById(R.id.imageView2);
            ImageView img3 = (ImageView) v.findViewById(R.id.imageView3);
            if (nombre != null) {
                nombre.setText(it.getNombre());
            }
            if (img != null) {
                img.setImageResource(it.getID());
            }
            if (img != null) {
                img2.setImageResource(it.getID2());
            }
            if (img != null) {
                img3.setImageResource(it.getID3());
            }
        }

        return v;

    }
    public Filter getFilter() {
        Filter filter = new Filter() {

            @Override
            protected FilterResults performFiltering(CharSequence prefijo) {

                FilterResults results = new FilterResults();
                ArrayList<Item2> aux = new ArrayList<Item2>();

                // El prefijo tiene que ser mayor que 0 y existir
                if (prefijo != null && prefijo.toString().length() > 0) {

                    for (int index = 0; index < allItems.size(); index++) {
                        Item2 si = allItems.get(index);
                        String nombre = si.getNombre();

                        String nom[] = nombre.split(" ");
                        for(int i=0; i<nom.length; i++){
                            if (nom[i].toLowerCase().startsWith(prefijo.toString().toLowerCase())) {
                                aux.add(si);
                            }
                        }
                    }
                    results.values = aux;
                    results.count = aux.size();
                } else {
                    synchronized (allItems) {
                        results.values = allItems;
                        results.count = allItems.size();
                    }
                }
                return results;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence prefijo,FilterResults results) {
                subItems = (ArrayList<Item2>) results.values;
                notifyDataSetChanged();

            }
        };
        return filter;
    }
}

和主类添加这样的:

ListView lv = (ListView)findViewById(R.id.list);
    lv.setTextFilterEnabled(true);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(this);




    TextWatcher filtro = new TextWatcher(){

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

        }

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

        }

        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub
            adapter.getFilter().filter(e.getText().toString());//filtra el texto metido en el edittext en tiempo real
        }

    };

    e.addTextChangedListener(filtro);
}

这篇关于Android的筛选和排序的ListView带适配器异步任务期间设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆