передать отфильтрованный элемент списка до следующего действия

android listview baseadapter

103 просмотра

1 ответ

Здесь я использую BaseAdapter для фильтрации своих элементов listview.when без использования параметра поиска, если я нажимаю на свой элемент listview, listView.setOnItemClickListener работает хорошо, я имею в виду, что элемент в позиции, по которой щелкнули, передается следующей активности. Но по отфильтрованному результату если я нажимаю на элемент, некоторые другие данные передаются следующему действию ... в чем может быть проблема? Кто-нибудь может помочь мне решить эту проблему?


Деятельность

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;
    }
}
Автор: sunil y Источник Размещён: 08.11.2019 10:55

Ответы (1)


1 плюс

Решение

В onItemClick вы используете rowTenDevice.get (position) .getDeviceName (). Это вызывает проблему. Вам нужен отфильтрованный элемент, поэтому создайте открытый метод в адаптере, чтобы получить arrayList.get (position) .getDeviceName (). Так как arrayList - это отфильтрованный список, он даст вам необходимый результат.

Используйте следующий код: -

Заменить строку: - intent.putExtra ("DeviceList", rowTenDevice.get (position) .getDeviceName ());

С участием

intent.putExtra ("DeviceList", ((RowTenDevice) adapter.getItem (position)). getDeviceName ());

Автор: Ramit Размещён: 20.08.2016 06:22
Вопросы из категории :
32x32