2016-08-20 65 views
0

这里我使用BaseAdapter来过滤我的listview items.when没有使用搜索选项,如果我点击我的listview项目listView.setOnItemClickListener效果很好,我的意思是在点击位置的项目是传递给下一个activity.But上,如果我点击该项目的过滤结果,一些其他数据传递给下一个activity..what可能是问题。任何人都可以请帮我解决这个问题..?通过过滤listview项目到下一个活动


活动

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; 
    } 
} 
+0

为什么所有的代码? Terible!而你的问题与下一个活动无关。你唯一的问题是,在项目点击监听器的位置值出错。或.get(位置)的值。 – greenapps

+0

好的..所以我必须做..? –

+0

发布证明问题的最小代码。为什么你打扰我们使用异步任务,数据库并在UI线程上运行?使用简单的列表视图和适配器和过滤器方法来展示问题,这对你自己来说也是有好处的。如果你愿意的话,你很可能会很快找到解决方案。 – greenapps

回答

1

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

使用以下代码: -

替换行: - intent.putExtra( “DEVICELIST”,rowTenDevice.get(位置).getDeviceName());

随着

intent.putExtra( “DEVICELIST”,((RowTenDevice)adapter.getItem(位置))getDeviceName());

+0

当我不搜索anything..at那个时候发生了什么获取(位置).getDeviceName()将有所不同..?当时我必须使用rowTenDevice.get(position).getDeviceName()right ..?如何实现这一个..? –

+0

不需要最初arrayList = rowTenDevice的权利。 List总是显示arrayList项目,所以使用arrayList检索正确的项目,您的代码将正常工作。 – Ramit

+0

可以请你告诉我我到底需要更改什么..?我的意思是我必须在适配器中添加什么代码。 –