简体   繁体   English

搜索自定义适配器不起作用

[英]Custom Adapter with Search Not working

I tried to add textwatcher with filter class but it do not work plz help. 我试图用过滤器类添加textwatcher,但它不能正常工作。 I get the json array through the server using the url. 我使用网址通过服务器获取json数组。 the search(filter) doesnt work well. 搜索(过滤器)无法正常工作。

public class CallDetails extends Activity { 公共类CallDetails扩展Activity {

SessionManager session;
ArrayList<Drivers> driverList = new ArrayList<Drivers>();
private List<Drivers> driverlist = null;
ListView listview;
ImageButton btback;
DriverAdapter dadapter;
String uid;
String name;
String email;
String odtyp;
static String oid;      
Drivers driver;

private EditText editTextFilter;
private static String OUTBOX_URL ="";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.calldetails);
    Intent i = getIntent();  
    oid =i.getStringExtra("orderId");
    odtyp =i.getStringExtra("ordertype");       
    OUTBOX_URL ="http://www.gdrive.com/api/calldetails.php?id="+oid;

    //managing session...
    session = new SessionManager(getApplicationContext());      
    HashMap<String, String> user = session.getUserDetails(); 
    name = user.get(SessionManager.KEY_NAME);        
    email = user.get(SessionManager.KEY_EMAIL);
    uid = user.get(SessionManager.KEY_UID);
    btback =(ImageButton)findViewById(R.id.btnBack);        
    btback.setVisibility(View.INVISIBLE);

    // Locate the EditText in listview_main.xml
    editTextFilter = (EditText)findViewById(R.id.editTextFilter);
    editTextFilter.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable arg0) {
            String text = editTextFilter.getText().toString().toLowerCase(Locale.getDefault());
            dadapter.filter(text);
        }
        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3){ /* to do*/ }
        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) { /*to do*/ }
    }); 


    //populating view with data...
    //driverList = new ArrayList<Drivers>();
    new JSONAsyncTask().execute(OUTBOX_URL);
    listview = (ListView)findViewById(R.id.drlist);         
    dadapter = new DriverAdapter(CallDetails.this, R.layout.list_item, driverList);
    listview.setItemsCanFocus(false);
    listview.setAdapter(dadapter);
    //populating list ends


    listview.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), driverList.get(position).getName(), Toast.LENGTH_LONG).show();              
        }
    }); 
    }
    public void back(View v){
         Intent back = new Intent(getApplicationContext(), SafetyDrive.class);
         startActivity(back);
         finish();
}


private class DriverAdapter extends ArrayAdapter<Drivers> {
    Context context;
    int Resource;
    LayoutInflater inflater;
    ArrayList<Drivers> driverList = new ArrayList<Drivers>();

    public DriverAdapter(Context context, int layoutResourceId,ArrayList<Drivers> drs) {
        super(context, layoutResourceId, drs);
        //inflater = ((Activity) context).getLayoutInflater();
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = layoutResourceId;
        driverList = drs;           
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //Log.d("in ", "view start");
        View item = convertView;
        DriverWrapper DriverWrapper = null;         
        if (item == null) {
            DriverWrapper = new DriverWrapper();
            item = inflater.inflate(Resource, null);                
            DriverWrapper.ename = (TextView) item.findViewById(R.id.textName);
            DriverWrapper.ephone = (TextView) item.findViewById(R.id.textPhone);                
            DriverWrapper.mkcall = (ImageButton) item.findViewById(R.id.btnphone);              
            item.setTag(DriverWrapper);
        } else {
            DriverWrapper = (DriverWrapper) item.getTag();
        }
        Drivers driver = driverList.get(position);
        DriverWrapper.ename.setText("Name: " + driver.getName());
        DriverWrapper.ephone.setText("Phone: " + driver.getPhone());
        final String dp = driver.getPhone().trim();

        DriverWrapper.mkcall.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //making call..
                //Log.e("no is", dp);
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:" +dp));
                //callIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(callIntent);  
                //finish();
            }
        });

        return item;
    }
    class DriverWrapper {
        TextView ename;
        TextView ephone;
        ImageButton mkcall;
        //ImageButton msg;  
    }

    // Filter Class     
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        driverList.clear();
        if (charText.length() == 0) {               
            driverList.addAll(driverList);
        } else {
            for (Drivers driver : driverList) {
                if (driver.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
                    driverList.add(driver);
                }
            }
        }
        notifyDataSetChanged();
    }
}

class JSONAsyncTask extends AsyncTask { JSONAsyncTask类扩展了AsyncTask {

    ProgressDialog dialog;      
    @Override
    protected void onPreExecute() {

        super.onPreExecute();
        dialog = new ProgressDialog(CallDetails.this);
        dialog.setMessage("Loading, please wait");
        dialog.show();
        dialog.setCancelable(false);
    }

    @Override
    protected Boolean doInBackground(String... urls) {
        try {
            //Log.d("in at-", "asynctask");
            HttpGet httppost = new HttpGet(urls[0]);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);

            // StatusLine stat = response.getStatusLine();
            int status = response.getStatusLine().getStatusCode();

            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);                 

                JSONObject jsono = new JSONObject(data);                    
                JSONArray jarray = jsono.getJSONArray("drivers");                   
               if(jarray.length()!=0){
                   for (int i = 0; i < jarray.length(); i++) {                      
                        JSONObject object = jarray.getJSONObject(i);                    
                        Drivers driver = new Drivers();     
                        driver.setPhone(object.getString("phone"));
                        driver.setName(object.getString("emp_name"));
                        driverList.add(driver);                             
                    }                       
               }else{
                    driver = new Drivers();     
                    driver.setPhone(" ");
                    driver.setName(" No Driver Place yet");
                    driverList.add(driver);
                }
                return true;
            }

        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    protected void onPostExecute(Boolean result) {
        dialog.cancel();
        btback.setVisibility(View.VISIBLE);
        dadapter.notifyDataSetChanged();
        if(result == false)
            Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();

    }
}

} }

public class Drivers { 公共类驾驶员{

private String name;
private String phone;

public Drivers() {

}

public Drivers(String name, String phone) {
    super();
    this.name = name;
    this.phone = phone;

}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

} }

actually it wont filter because youve cleared the driverList and then in the else statement you loop to driverList which is already empty. 实际上,它不会过滤,因为您已经清除了driverList,然后在else语句中循环到已经为空的driverList。 the only thing you can do is create a backup list for the driversList and then use the backup list to get all data for filtering to the driverList. 唯一可以做的就是为driversList创建一个备份列表,然后使用该备份列表将所有数据过滤到driverList。

Example Here: 这里的例子:

// here is the backuplist
ArrayList<Drivers> backupList = new ArrayList<Drivers>();
   // Filter Class     
public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    // actually its easy to just clear the backup list
    // but due to reasons where users press backspace you have to load backup list only once
    if(backupList.isEmpty()) {
        backupList.addAll(driverList);
    }
    driverList.clear();
    if (charText.length() == 0) {
        driverList.addAll(backupList);
    } else {
        for (Drivers driver : backupList) {
            if (driver.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
                driverList.add(driver);
            }
        }
    }
    notifyDataSetChanged();
}

Hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM