如何在BaseAdapter上实现getFilter() [英] how to implement getFilter() on a BaseAdapter

查看:77
本文介绍了如何在BaseAdapter上实现getFilter()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我正在从数据库中获取数据并在ListView中显示项目.我想为listView项目执行搜索选项.我正在从BaseAdapter获取项目.如何在自定义BaseAdapter中实现getFilter().这是我的活动

In my application I am fetching data from database and displaying items in ListView. I want to perform search option for listView items. I am fetching items from BaseAdapter. How to implement getFilter() in custom BaseAdapter. here is my activity

public class BindTenGPS extends Activity {
    private MenuItem menuItem;
    DbaAdapter db;
    private ProgressDialog progressDialog;
    ListView listView ;
    EditText inputSearch;
    private  BindTenDeviceBaseAdapter adapter;
    List<RowTenDevice> rowTenDevice;
    ArrayList<String> DeviceName = new ArrayList<String>();

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.list1_main);
         inputSearch = (EditText)findViewById(R.id.inputSearch);
         db=new DbaAdapter(getApplicationContext());


         new LoadTrackNumbers().execute();

     }

     private class LoadTrackNumbers extends AsyncTask<Void, Integer, Void> {
            int myProgress;
            @Override  
            protected void onPreExecute()  
            {  
                //Create a new progress dialog  
                progressDialog = new ProgressDialog(BindTenGPS.this);  
                //Set the progress dialog to display a horizontal progress bar  
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
                //Set the dialog title to 'Loading...'  
                progressDialog.setTitle("Loading...");  
                //Set the dialog message to 'Loading application View, please wait...'  
                progressDialog.setMessage("Loading application View, please wait...");  
                //This dialog can't be canceled by pressing the back key  
                progressDialog.setCancelable(true);  
                //This dialog isn't indeterminate  
                progressDialog.setIndeterminate(false);  
                //The maximum number of items is 100  
                progressDialog.setMax(100);  
                //Set the current progress to zero  
                progressDialog.setProgress(0);  
                //Display the progress dialog  
                progressDialog.show(); 

            }
            @Override
            protected Void doInBackground(Void... params) {
                try  
                {  
                    //Get the current thread's token  
                    synchronized (this)  
                    { 
                        DeviceName.clear();
                        publishProgress(10);
                        this.wait(500);
                        Connection conn = null;
                        try {
                            Log.w("Error connection","shyam1");
                        String driver = "net.sourceforge.jtds.jdbc.Driver";
                        Log.w("Error connection","shyam2");
                        Log.i("Android"," MySQL Connect Example0.");
                        Class.forName(driver).newInstance();
                        Log.w("Error connection","shyam3");
                        String connString = "jdbc:jtds:sqlserver://ip address;instance=SQLEXPRESS;DatabaseName=AAUMConnect;";
                        String username = "username";
                        String password = "password";
                        Log.w("Error connection","shyam4");
                        publishProgress(20);
                        this.wait(500);
                        publishProgress(30);
                        this.wait(500);
                        publishProgress(40);
                        this.wait(500);
                        publishProgress(50);
                        this.wait(500);
                        conn = DriverManager.getConnection(connString,username,password);
                        publishProgress(80);
                        Log.w("Error connection","shyam5");
                        Statement stmt = conn.createStatement();
                        ResultSet reset;
                        db.open();
                        int superuser = db.GetISSuperUser();
                        db.close();
                        db.open();
                        int clientid = db.GetClientID();
                        db.close();
                        if(superuser == 0)
                        {
                            db.open();
                            String branch = db.GetBranch();
                            db.close();
                            reset = stmt.executeQuery("SELECT dbo.fn_AddEveryNthItem(LEFT(AssignVehicleToTrackTable, LEN(AssignVehicleToTrackTable) - 1), ',','@', 1) AS DeviceName FROM (SELECT DeviceName + ',' FROM AssignVehicleToTrack where ClientID = " + clientid + " and BranchName = '" + branch.trim() + "' and VirtualNo = 'GPS' order by DeviceName FOR XML PATH ('')) T1 (AssignVehicleToTrackTable)");
                        }
                        else
                        {
                            reset = stmt.executeQuery("SELECT dbo.fn_AddEveryNthItem(LEFT(AssignVehicleToTrackTable, LEN(AssignVehicleToTrackTable) - 1), ',','@', 1) AS DeviceName FROM (SELECT DeviceName + ',' FROM AssignVehicleToTrack where ClientID = " + clientid + " and VirtualNo = 'GPS' order by DeviceName FOR XML PATH ('')) T1 (AssignVehicleToTrackTable)");
                        }

                        //Print the data to the console
                        Log.w("Error connection","shyam6");
                        int i1 = 0, c = 0;
                         try
                         {
                             while(reset.next()){
                                    publishProgress(c);
                                    String[] tokens = new String[100];
                                    tokens = reset.getString(1).split("@");
                                    for(int i=0;i<tokens.length;i++)
                                    {
                                        DeviceName.add(tokens[i].substring(1));
                                    }
                                    i1++;
                                    c+=10;
                                }
                         }
                         catch(Exception ex)
                         {
                             runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(), "GPS Device not available", Toast.LENGTH_LONG).show();
                                    }
                               });
                         }

                        reset.close();
                        conn.close();
                        rowTenDevice = new ArrayList<RowTenDevice>();
                        for (int j = 0; j < DeviceName.size(); j++) {
                            RowTenDevice item = new RowTenDevice(DeviceName.get(j));
                            Log.w("Data:","D"+j+" : "+DeviceName.get(j));
                            rowTenDevice.add(item);
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                listView = (ListView) findViewById(R.id.list);
                                Log.w("Data:","E1");
                                adapter = new BindTenDeviceBaseAdapter(BindTenGPS.this, rowTenDevice);
                                Log.w("Data:","E2");
                                listView.setAdapter(adapter);
                                Log.w("Data:","E3");

                                inputSearch.addTextChangedListener(new TextWatcher() {


                                    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                                        // When user changed the Text
                                        BindTenGPS.this.adapter.getFilter().filter(cs);   
                                    }


                                    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                          
                                    }
                                });
                                listView.setOnItemClickListener(new OnItemClickListener() {

                                    @Override
                                    public void onItemClick(
                                            AdapterView<?> arg0, View arg1,
                                            int position, long arg3) {
                                        // TODO Auto-generated method stub
                                        Intent intent = new Intent(BindTenGPS.this, ShowGPS.class);
                                        intent.putExtra("DeviceList", rowTenDevice.get(position).getDeviceName());

                                        startActivity(intent);
                                    }

                                });
                                Log.w("Data:","E4");


                           }
                       });

                        } catch (Exception e)
                        {
                            Log.w("Error connection","shyam" + e.getMessage());
                            e.printStackTrace();
                        }
                        this.wait(500);
                        publishProgress(100);
                    }  
                }  
                catch (Exception e)  
                {  
                    e.printStackTrace();  
                }  
                return null;
            }
            @Override  
            protected void onProgressUpdate(Integer... values)  
            {  
                //set the current progress of the progress dialog  
                progressDialog.setProgress(values[0]);  
            }  
            //after executing the code in the thread  
            @Override
            protected void onPostExecute(Void result)  
            {  
                //close the progress dialog  
                progressDialog.dismiss();
                //initialize the View  
                //setContentView(R.layout.list1_main);  
            }
        }

}

BindTenDeviceBaseAdapter

BindTenDeviceBaseAdapter

我已经编辑了基本适配器.现在它在if(data.toLowerCase().startsWith(constraint.toString()))
处引发错误 错误是The method toLowerCase() is undefined for the type RowTenDevice.我正在使用RowTenDevice类加载String..so,如何使其工作?

EDIT 2: I have edited my base adapter.now it is throwing error at if(data.toLowerCase().startsWith(constraint.toString()))
error is The method toLowerCase() is undefined for the type RowTenDevice. I am using RowTenDevice class to load String..so how do I make it work ?

public class BindTenDeviceBaseAdapter extends BaseAdapter implements Filterable {
    Context context;
    List<RowTenDevice> rowTenDevice;
    List<RowTenDevice> arrayList; 
    LayoutInflater inflater;

    public BindTenDeviceBaseAdapter(Context context, List<RowTenDevice> items) {
        this.context = context;
        this.rowTenDevice = items;
        this.arrayList = items;
        inflater = LayoutInflater.from(context);

    }

    /*private view holder class*/
    private class ViewHolder {

        TextView txtTenDevice;
    }


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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;

        LayoutInflater mInflater = (LayoutInflater)
            context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_tendevice, null);
            holder = new ViewHolder();
            holder.txtTenDevice = (TextView) convertView.findViewById(R.id.tvTenDevice);
            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }

        RowTenDevice rowItem = (RowTenDevice) getItem(position);

        holder.txtTenDevice.setText(rowItem.getDeviceName());
        return convertView;
    }

    @Override
    public Filter getFilter() {
        // TODO Auto-generated method stub
         Filter filter = new Filter() {

             @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    // TODO Auto-generated method stub
                      arrayList = (List<RowTenDevice>) results.values; // has the filtered values
                      notifyDataSetChanged();
                }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                // TODO Auto-generated method stub
                FilterResults results = new FilterResults();
                List<RowTenDevice> FilteredArrList = new ArrayList<RowTenDevice>();

                if (rowTenDevice == null) {
                    rowTenDevice = new ArrayList<RowTenDevice>(arrayList); // saves the original data in mOriginalValues
                }
                 if (constraint == null || constraint.length() == 0) {

                     // set the Original result to return  
                     results.count = rowTenDevice.size();
                     results.values = rowTenDevice;
                 } else {
                     constraint = constraint.toString().toLowerCase();
                     for (int i = 0; i < rowTenDevice.size(); i++) {
                         RowTenDevice data = rowTenDevice.get(i);
                         if (data.toLowerCase().startsWith(constraint.toString())) {
                             FilteredArrList.add(data);
                         }
                     }
                     // set the Filtered result to return
                     results.count = FilteredArrList.size();
                     results.values = FilteredArrList;
                 }
                 return results;
             }


    };
        return filter;


    }
}

RowTenDevice

public class RowTenDevice {
    private String devicename;
    public RowTenDevice(String devicename) {
        this.devicename = devicename;
    }
    public String getDeviceName() {
        return devicename;
    }
    public void setDeviceName(String devicename) {
        this.devicename = devicename;
    }
}

我知道这个问题已经问过几次了,但是没有一个解决方案对我有用.

I know this question has been asked several times, but none of the solutions worked for me.

推荐答案

使用(如果您确定有关数据和设备名称都不为空)

Use (if you sure about data and device name are both not null)

if(data.getDeviceName().toLowerCase().startsWith(constraint.toString()))

代替

   if(data.toLowerCase().startsWith(constraint.toString()))

此外, 检查此可能的问题和答案. 问题

In addition, Check this likely question and answer. Question

这篇关于如何在BaseAdapter上实现getFilter()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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