Searchview过滤器,来自检索到的Volley Library数据

时间:2016-02-19 05:04:51

标签: android android-studio android-recyclerview android-volley searchview

我正在使用Volley Library从服务器检索数据。现在我实现了SearchView来过滤数据。在这里,我对每个tabs使用了searchview。搜索查询未正确传递给适配器类。有时它会传递。虽然它传递给适配器类,但我需要过滤从服务器检索到的数据,并且需要调整它的回收器视图。

这是我的代码..请帮我解决。

TabFragment.java

public class TabFragment_1 extends Fragment implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {

    public static final String MyPREFERENCES = "Preference";
    Context context;
    RecyclerView recyclerView;
    SharedPreferences pref;
    String currentTab;
    private String query = "";
    //    private ListAdapter mAdapter;
    private List<Restaurant_Beam> listSuperHeroes;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;
    private int count = 0;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        context = getActivity();
        pref = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        currentTab = pref.getString("FIRST_TAB", "tab1");
        Log.e("Current Tab", currentTab);

        recyclerView = (RecyclerView) view.findViewById(R.id.fragment_list_rv);

        layoutManager = new GridLayoutManager(context, 2);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        setHasOptionsMenu(true);

        listSuperHeroes = new ArrayList<>();

        getData();
        return view;
    }

    //This method will get data from the web api
    private void getData() {
        //Showing a progress dialog
        final ProgressDialog loading = ProgressDialog.show(context, "Loading Data", "Please wait...", false, false);
        //Creating a json array request
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {

            @Override
            public void onResponse(JSONArray response) {
                //Dismissing progress dialog
                loading.dismiss();
                //calling method to parse json array
                parseData(response);
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                });

        //Creating request queue
        RequestQueue requestQueue = Volley.newRequestQueue(context);

        //Adding request to the queue
        requestQueue.add(jsonArrayRequest);
    }

    private void parseData(JSONArray array) {

        for (int i = 0; i < array.length(); i++) {
            Restaurant_Beam superHero = new Restaurant_Beam();
            JSONObject json = null;
            try {
                json = array.getJSONObject(i);
                superHero.setStr_categoryName(json.getString(Config.CATEGORY_NAME));
                superHero.setStr_productName(json.getString(Config.PRODUCT_NAME));
                superHero.setStrPrice(json.getInt(String.valueOf(Config.PRICE)));
                superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
                superHero.setTAB_NAME(json.getString(Config.TAB_NAME));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (superHero.getTAB_NAME().contains(currentTab)) {
                listSuperHeroes.add(superHero);
                adapter = new CardAdapter(listSuperHeroes, context);
                recyclerView.setAdapter(adapter);
            }
        }
    }

    @Override
    public boolean onClose() {
        System.out.println("Restaurant Tab onQueryTextSubmit =" + "");
        return false;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        System.out.println("Restaurant Tab onQueryTextSubmit =" + query);
        ((CardAdapter) recyclerView.getAdapter()).setFilter(query);
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        System.out.println("Restaurant Tab onQueryTextSubmit =" + newText);

        return false;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main, menu);

        final SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
        searchView.setSubmitButtonEnabled(false);
        searchView.setIconifiedByDefault(true);
        searchView.setOnQueryTextListener(this);
        searchView.setOnCloseListener(this);
        super.onCreateOptionsMenu(menu, inflater);
    }
}

CardAdapter.java:

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {

    List<Restaurant_Beam> restaurant_prducts;
    Config config;
    Bitmap bmp;
    boolean success = false;
    ArrayList<String> CATEGORYNAME;
    ArrayList<String> ITEMNAME;
    ArrayList<String> ITEM_PRICE;
    ViewHolder vHolder;
    ArrayList<String> visibleObjects;
    ArrayList<String> wordList;

    private ImageLoader imageLoader;
    private Context context;

    public CardAdapter(List<Restaurant_Beam> superHeroes, Context context) {
        super();

        this.restaurant_prducts = superHeroes;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

        Restaurant_Beam restaurant_beam = restaurant_prducts.get(position);

        imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
        imageLoader.get(config.IMAGE_URL + restaurant_beam.getImageUrl() + ".jpg", ImageLoader.getImageListener(holder.productImage, R.drawable.image_1, R.drawable.image_1));  //android.R.drawable.ic_dialog_alert

/*        holder.productImage.setImageUrl(config.IMAGE_URL + restaurant_beam.getImageUrl() + ".jpg", imageLoader);
        holder.txt_itemName.setText(restaurant_beam.getStr_productName());
        holder.txt_categoryName.setText(String.valueOf(restaurant_beam.getStr_categoryName()));
        holder.txt_Price.setText(String.valueOf(restaurant_beam.getStrPrice()));
        holder.linearLayout.setVisibility(View.INVISIBLE);*/

        String IMAGE_URL = config.IMAGE_URL + restaurant_beam.getImageUrl() + ".jpg";
        String ITEM_NAME = restaurant_beam.getStr_productName();
        String CATEGORY_NAME = restaurant_beam.getStr_categoryName();
        String PRICE = String.valueOf(restaurant_beam.getStrPrice());

        holder.productImage.setImageUrl(IMAGE_URL, imageLoader);
        holder.txt_itemName.setText(ITEM_NAME);
        holder.txt_categoryName.setText(CATEGORY_NAME);
        holder.txt_Price.setText(PRICE);
        holder.linearLayout.setVisibility(View.INVISIBLE);

        ITEMNAME = new ArrayList<>();
        CATEGORYNAME = new ArrayList<>();
        ITEM_PRICE = new ArrayList<>();

        ITEMNAME.add(ITEM_NAME);
        CATEGORYNAME.add(CATEGORY_NAME);
        ITEM_PRICE.add(PRICE);

        Log.e("Filter", String.valueOf(ITEMNAME) + "  ..." + CATEGORYNAME);

        holder.productImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(view.getContext(), ProductActivity.class);
                i.putExtra("itemName", holder.txt_itemName.getText().toString());
                i.putExtra("categoryName", holder.txt_categoryName.getText().toString());
                i.putExtra("Price", Integer.parseInt(holder.txt_Price.getText().toString()));
                view.getContext().startActivity(i);
            }
        });

        holder.iv_settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                holder.linearLayout.setVisibility(View.VISIBLE);
            }
        });
        holder.viewDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(), "Clicked ViewDetail", Toast.LENGTH_SHORT).show();
            }
        });
        holder.addToCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(), "Clicked AddToCart", Toast.LENGTH_SHORT).show();
            }
        });
        holder.checkOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(), "Clicked CheckOut", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        Log.e("Restaurant Size", String.valueOf(restaurant_prducts
                .size()));
        return restaurant_prducts.size();
    }

    public void setFilter(String query) {
        Log.e("Adapter Query", query);
        String[] stringArray = new String[restaurant_prducts.size()];
        for (int i = 0; i < restaurant_prducts.size(); i++) {
            System.out.println("I am inside ForLoop" + " " + i);
            stringArray[i] = restaurant_prducts.get(i).toString();
        }
        wordList = new ArrayList<String>(Arrays.asList(stringArray));

        List<Restaurant_Beam> list = new ArrayList<>(stringArray.length);

//        list.addAll(wordList);
//        restaurant_prducts.add(list);
//
//        for(String s : stringArray){
//            restaurant_prducts.add()
//        }

        Log.e("String array", wordList.toString());

        Log.e("Adapter Query", String.valueOf(ITEMNAME) + " " + CATEGORYNAME + " " + ITEM_PRICE + " " + stringArray);
        notifyDataSetChanged();
    }

//    public void flushFilter() {
//        visibleObjects=new ArrayList<>();
//        visibleObjects.addAll(allObjects);
//        notifyDataSetChanged();
//    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public NetworkImageView productImage;
        public TextView txt_categoryName;
        public TextView txt_itemName, txt_Price;
        public CardView cardlist_item;
        public ImageView iv_settings;
        public LinearLayout linearLayout;
        public Button viewDetail, addToCart, checkOut;

        public ViewHolder(View itemView) {
            super(itemView);
            iv_settings = (ImageView) itemView.findViewById(R.id.iv_settings);
            cardlist_item = (CardView) itemView.findViewById(R.id.cardlist_item);
            txt_itemName = (TextView) itemView.findViewById(R.id.txt_itemName);
            txt_Price = (TextView) itemView.findViewById(R.id.txt_Price);
            txt_categoryName = (TextView) itemView.findViewById(R.id.txt_categoryName);
            productImage = (NetworkImageView) itemView.findViewById(R.id.productImage);
            linearLayout = (LinearLayout) itemView.findViewById(R.id.linearTransparent);
            viewDetail = (Button) itemView.findViewById(R.id.butViewDetail);
            addToCart = (Button) itemView.findViewById(R.id.but_addTCart);
            checkOut = (Button) itemView.findViewById(R.id.butCheckOut);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

按如下所示更改你的onQuerryTextSubmit

@Override
public boolean onQueryTextSubmit(String query) {
    System.out.println("Restaurant Tab onQueryTextSubmit =" + query);
    adapter.setFilter(query);
    return true;
}

同时初始化适配器并将其设置为oncreate中的recycler视图。获取数据后,您可以将其添加到arraylist并调用adapter.notifydatasetchanged。这样只会出现一个arraylist,并且将始终调用onquerytext submit并反映数据更改。

这也不是过滤数据的正确方法,因为这里过滤是在主线程上完成的,您的自定义适配器应该实现Filterable。在这里查看http://developer.android.com/reference/android/widget/Filterable.html