将筛选的listview项传递给下一个活动

时间:2016-08-20 05:30:03

标签: android listview baseadapter

这里我使用BaseAdapter过滤我的listview项目。如果我没有使用搜索选项,如果我点击我的listview项目listView.setOnItemClickListener工作正常,我的意思是点击位置的项目传递给下一个activity.But on过滤后的结果,如果我点击该项目,其他一些数据将传递给下一个活动..可能是什么问题。可以帮助我解决这个问题。?

活动

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

BaseAdapter

public class BindTenDeviceBaseAdapter extends BaseAdapter implements Filterable {
    Context context;
    List<RowTenDevice> rowTenDevice;
    List<RowTenDevice> arrayList; //temporary list to store filtered values.
    LayoutInflater inflater;

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

    }

    private class ViewHolder {

        TextView txtTenDevice;
    }


    @Override
    public int getCount() {

        return arrayList.size();
    }

    @Override
    public Object getItem(int position) {

        return arrayList.get(position);
    }

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

    }

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

        ViewHolder holder = null;

        if (convertView == null) {
            convertView = inflater.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 rowTenDevice
                }
                 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.getDeviceName().toLowerCase().contains(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;
    }
}

1 个答案:

答案 0 :(得分:1)

在onItemClick中,您使用的是rowTenDevice.get(position).getDeviceName()。这导致了问题。您需要过滤项,因此在适配器中创建一个公共方法以获取arrayList.get(position).getDeviceName()。由于arrayList是过滤列表,它将为您提供所需的结果。

使用以下代码: -

替换行: - intent.putExtra(&#34; DeviceList&#34;,rowTenDevice.get(position).getDeviceName());

使用

intent.putExtra(&#34; DeviceList&#34;,((RowTenDevice)adapter.getItem(position))。getDeviceName());