簡體   English   中英

將過濾的listview項傳遞給下一個活動

[英]pass filtered listview item to next activity

我在這里使用BaseAdapter過濾列表視圖項。當不使用搜索選項時,如果單擊列表視圖項,則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;
    }
}

在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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM