输入退格键时,ListView不更新后更新 [英] ListView Not Updating After Filtering, when the backspace key is entered

查看:86
本文介绍了输入退格键时,ListView不更新后更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Here is the code, I used a custom adapter, and applied the Filter method, now the ListView does not update when the backspace key is entered, on when one switches back from an item activity. please help me.. and how to display no result to filtered list..













public class ItemListAdapter extends ArrayAdapter<ItemVO>
{

    private ArrayList<ItemVO> itemList;
    private ArrayList<ItemVO> fiems;
    private static final int LONG_DELAY = 3500; // 3.5 seconds
    private static final int SHORT_DELAY = 2000; // 2 seconds
    private Context context;
    private Filter filter;

    public ItemListAdapter(Context context, int textViewResourceId,ArrayList<ItemVO> stateList) 
    {
        super(context, textViewResourceId, stateList);
        this.context = context;
        this.itemList = new ArrayList<ItemVO>();
        this.itemList.addAll(stateList);
        this.fiems=new ArrayList<ItemVO>();
        this.fiems.addAll(stateList);

    }

    private class ViewHolder
    {
        TextView code;
        CheckBox name;
    }

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

        ViewHolder holder = null;

        Log.v("ConvertView", String.valueOf(position));

        if (convertView == null)
        {

            LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            convertView = vi.inflate(R.layout.listview_items, null);

            holder = new ViewHolder();
            holder.code = (TextView) convertView.findViewById(R.id.textView1);
            holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);

            convertView.setTag(holder);

            holder.name.setOnClickListener( new View.OnClickListener() 
            {
                public void onClick(View v)  
                {
                    CheckBox cb = (CheckBox) v;
                    ItemVO item = (ItemVO) cb.getTag();

                    item.setSelected(cb.isChecked());
                }
            });

        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }

        ItemVO state = itemList.get(position);

        holder.code.setText(state.getItemdescription());
        holder.name.setChecked(state.isSelected());

        holder.name.setTag(state);

        return convertView;
    }
    @Override
    public Filter getFilter()
    {
        if (filter == null)
            filter = new PkmnNameFilter();

        return filter;
    }

    private class PkmnNameFilter extends Filter
    {
            @SuppressWarnings("unused")
            @SuppressLint("DefaultLocale")
            @Override
            protected FilterResults performFiltering(CharSequence constraint)
            {   
                FilterResults results = new FilterResults();  // Holds the results of a filtering operation in values
                String prefix = constraint.toString().toLowerCase();

                if (prefix == null || prefix.length() == 0)
                {
                    ArrayList<ItemVO> list = new ArrayList<ItemVO>(fiems);
                    results.values = list;
                    results.count = list.size();
                }
                else
                {
                    final ArrayList<ItemVO> list = new ArrayList<ItemVO>(fiems);
                    final ArrayList<ItemVO> nlist = new ArrayList<ItemVO>();
                    int count = list.size();

                    for (int i=0; i<count; i++)
                    {
                        final ItemVO pkmn = list.get(i);
                        final String value = pkmn.getItemdescription().toLowerCase();

                        if (value.startsWith(prefix))
                        {
                            nlist.add(pkmn);
                        }
                       /*else
                        {
                           final Toast toast= Toast.makeText(context, "No Items Found", Toast.LENGTH_SHORT);
                            toast.show();
                             Handler handler = new Handler();
                             handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    toast.cancel(); 
                                }
                         }, 1000);
                        }*/
                    }
                    // set the Filtered result to return
                    results.values = nlist;
                    results.count = nlist.size();

                }
                return results;
            }



            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                itemList = (ArrayList<ItemVO>)results.values; // has the filtered values

                clear();
                int count = itemList.size();
                for (int i=0; i<count; i++)
                {
                    ItemVO pkmn = (ItemVO)itemList.get(i);
                    add(pkmn);

                    notifyDataSetChanged(); // notifies the data with new filtered values
                }
            }

        }


    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
        boolean notifyChanged = true;
    }
    }













public class CateringList extends Activity 
{
	     ItemVO details;
	     Bfs categoryDetails;
	     ArrayList<ItemVO> itemList;
	     ArrayList<ItemVO> i;
	     ArrayList<String> itemsList;
	     String cat;
	     ArrayAdapter<String> arrayAdapter;
	     ItemListAdapter adapter1;
	     ListView lv;
	     private SharedPreferences sp;
	      ItemListAdapter dataAdapter;
	     EditText searchBox;
	     

		 @Override
		 protected void onCreate(Bundle savedInstanceState)
		 {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.list_item_name);
			//dataAdapter.clear();
			itemList = new ArrayList<ItemVO>();
			//itemList.clear();
			 Log.d("D.TAG", " value.: " + itemList.toString());
			details = (ItemVO) ApplicationCache.getInstance().getValue("categoryNameDetails");
			categoryDetails = (Bfs) ApplicationCache.getInstance().getValue("categoryTypeDetails");
			itemList = categoryDetails.getCategoryNameDetails(); 
			lv = (ListView) findViewById(R.id.list1);
			arrayAdapter = new ArrayAdapter<String>(this,R.layout.listview_items,R.id.textView1);
				for (ItemVO mnvo : categoryDetails.getCategoryNameDetails())
				{
					Log.d("TestTag", "Name of custome care"+mnvo.getCategoryName());
					arrayAdapter.add(mnvo.getCategoryName());
				}
				Log.d("D.TAG", " value: " + itemList.toString());
				
				//binding adapter
				//lv.setAdapter(new MyAdapter(CateringList.this,R.id.textView1,itemList));
				
	   
				 dataAdapter = new ItemListAdapter(this,R.layout.listview_items, itemList);
				 Log.d("D.TAG", " value1: " + itemList.toString());
				 lv.setAdapter(dataAdapter);
				 //lv.setTextFilterEnabled(true);				 
				 searchBox=(EditText) findViewById(R.id.filter_text);
				 //searchBox.addTextChangedListener(filterTextWatcher);
				
		        searchBox.addTextChangedListener(new TextWatcher() {
		        	 
		             @Override
		             public void afterTextChanged(Editable arg0) {
		                 // TODO Auto-generated method stub
		            	 
		             }
		  
		             @Override
		             public void beforeTextChanged(CharSequence arg0, int arg1,
		                     int arg2, int arg3) {
		                 // TODO Auto-generated method stub
		             }
		  
		             @Override
		             public void onTextChanged(CharSequence s, int arg1, int arg2,
		                     int arg3) {
		            	 //String text = searchBox.getText().toString().toLowerCase(Locale.getDefault());
		                 dataAdapter.getFilter().filter(s);
		                 
		                 Log.d("D.TAG", " value2: " + itemList.toString());
		                // dataAdapter.getFilter().filter(s); 
		                 //dataAdapter.notifyDataSetChanged();
		                
		                //  
		             } 
			     });
		        Log.d("D.TAG", " value1: " + itemList.toString());
		        ApplicationCache.getInstance().clear();
		        
		        
				 dataAdapter = new ItemListAdapter(this,R.layout.listview_items, itemList);
				 lv.setAdapter(dataAdapter);
				 Log.d("D.TAG", " value1: " + itemList.toString());
				 
				 
				sp = getSharedPreferences("aksp", Context.MODE_PRIVATE);
				//store your data in a key/value form
				String items = sp.getString("Items", null);
				

				String[] itemsArray = null;
				itemsList = new ArrayList<String>();

					if(items == null || items.equalsIgnoreCase(""))
					{
				
					}
					else
					{
						itemsArray = items.split("\\|");
						for(String c : itemsArray)
						{
							itemsList.add(c);
						}
				
					}
					Intent intentObject = getIntent();
					cat = intentObject.getStringExtra("categorypos");
					Button myButton = (Button) findViewById(R.id.button1);
					myButton.setOnClickListener(new OnClickListener() 
					{
							@Override
							public void onClick(View v) 
							{

									String items = "";
					
									int count = 0;
									for(ItemVO c : itemList)
									{
										if(c.isSelected())
										{
											count++;
											items =items+"\n"+ c.getItemdescription();
											sp.edit().putString("items", items).commit();
							
										}
						
									}
									if(count==0)
									{
											Toast.makeText(CateringList.this, "Please select at least one item", Toast.LENGTH_LONG).show();
											return;
									}
									String catitems=cat +"\n "+"Items:" + items;
									Intent iIntent = new Intent(CateringList.this,MyCart.class);
									iIntent.putExtra("catitems", catitems);
									startActivity(iIntent);
					
									ApplicationCache.getInstance().clear();
									itemsList.clear();
					
									String[] countriesArray = items.split("\\|");
					
									for(String c : countriesArray)
									{
										itemsList.add(c);
									}
					
							}
					});
					/*swipe_layout.setOnTouchListener(new OnTouchListener() {
	                        @Override
	                        public boolean onTouch(View v, MotionEvent ev) {
	                            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
	                                lastY = ev.getRawY();
	                            } else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
	                                nowY = ev.getRawY();
	                            } else if (ev.getAction() == MotionEvent.ACTION_UP) {
	                                if ((nowY - lastY) > 0) {
	                               
	                                    //PULL_DOWN_EVENT, custom function here where you can show you search box view;
	                                }
	                                nowY = 0;
	                                lastY = 0;
	                            }
	                            return false;
	                        }

							
	                      });*/
					
	     }

推荐答案

我也有问题

Me too had problem with
dataAdapter.notifyDataSetChanged()



我刚刚清除了适配器每当我需要更新列表时设置适配器。它对我来说很好。


I just cleared adapter and again set the adapter whenever I needed to update the list. Its works fine for me.


我使用ArrayList来添加要在listview中显示的值。

I am using a ArrayList to add the values to be displayed in listview.
List values = new ArrayList();
ListView listView1 = (ListView) findViewById(R.id.listView1);
String listValue = null;
ArrayAdapter adapter;



使用add()添加值,我将在listValue中有一个字符串


Adding values using add(), I will have a string in listValue

values.add(listValue);



设置适配器


Setting the adapter

adapter = new ArrayAdapter(getBaseContext(),android.R.layout.simple_list_item_1, android.R.id.text1, values);
			
listView1.setAdapter(adapter);



当我需要更改listView1中的数据时,我只需使用clear()清除值


When I need to change the data in the listView1, I just clear the values using clear()

values.clear();



然后,再次设置适配器


Then, again set the adapter

adapter = new ArrayAdapter(getBaseContext(),android.R.layout.simple_list_item_1, android.R.id.text1, values);
   			
listView1.setAdapter(adapter);



希望这对您有所帮助。但我认为这不是一种方法。我们应该使用notifyDataSetChanged()。


Hope this help you. But I think this is not a way to do. We should use the notifyDataSetChanged().


这篇关于输入退格键时,ListView不更新后更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆