当数据来自后端时,如何在从gridview单击项目时刷新布局

时间:2017-01-13 09:47:41

标签: android json android-recyclerview

enter image description here当我点击黑心按钮时,我用红心按钮替换它,但它反映了我再次来到这个页面。不是在点击的同时。 所以帮我解决这个问题。 我在下面添加了图片。

这是我的活动课

  public class Productpage extends AppCompatActivity implements SearchView.OnQueryTextListener {
        private FloatingActionButton fab;
    //    GridView gridView;
        RecyclerView recyclerView;
        private GridLayoutManager lLayout;
        String trading,flag,newest,high,low,newest1="newest",custid,catid;
        MyAdapter1 mAdapter;
        SearchView mSearchView;
        ArrayList<productinfo> sliderList;
        String []para;
        Intent intent;
        int spanCount = 2; // 3 columns
        int spacing = 2; // 50px
        boolean includeEdge = false;
        Button btncart;
        String cartcount;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_productpage);
    //        gridView = (GridView)findViewById(R.id.gridview);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
            setSupportActionBar(toolbar);
          /*  View inflated = getLayoutInflater().inflate(R.layout.action_bar_notifitcation_icon, null);
            toolbar.addView(inflated);*/
           // btncart=(Button) toolbar.findViewById(R.id.actionNotifications);
            lLayout = new GridLayoutManager(getApplicationContext(), 2);
            recyclerView = (RecyclerView) findViewById(R.id.recyclerMen);
            recyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(lLayout);
            SharedPreferences sharedPref2 = getApplicationContext().getSharedPreferences("notificationcart", Context.MODE_PRIVATE);
            cartcount=sharedPref2.getString("cartcount","");
            getproductdata();
            fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                 /*   Toast.makeText(getApplicationContext(),"filter is open here",Toast.LENGTH_LONG).show();*/
                    Intent intent=new Intent(getApplicationContext(),FilteredBy.class);
                    startActivity(intent);
                }
            });



            intent=getIntent();
            String action=intent.getAction();
            if(action.equals("home")){
                flag=intent.getStringExtra("flag");
                custid=intent.getStringExtra("custid");
                catid=intent.getStringExtra("cat_id");
                Toast.makeText(Productpage.this,flag+""+custid+""+catid,Toast.LENGTH_LONG).show();
                }
            else if(action.equals("filter")){
                flag=intent.getStringExtra("flagfilter");
                para=intent.getStringArrayExtra("category");
                Toast.makeText(Productpage.this,flag,Toast.LENGTH_LONG).show();
            }
    // else if (action.equals("trading")){
    //            trading = intent.getStringExtra("trading");
    //            Toast.makeText(Productpage.this, trading, Toast.LENGTH_LONG).show();
    //        }else if (action.equals("newest")){
    //            newest = intent.getStringExtra("newest");
    //            Toast.makeText(Productpage.this, newest, Toast.LENGTH_LONG).show();
    //        }else if (action.equals("high")){
    //            high = intent.getStringExtra("priceasc");
    //            Toast.makeText(Productpage.this, high, Toast.LENGTH_LONG).show();
    //        }else if (action.equals("low")){
    //            low = intent.getStringExtra("pricedesc");
    //            Toast.makeText(Productpage.this, low, Toast.LENGTH_LONG).show();
    //        }
        }

        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.

            getMenuInflater().inflate(R.menu.main, menu);
            MenuItem searchItem = menu.findItem(R.id.action_search);
            mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
            setupSearchView();
            return super.onCreateOptionsMenu(menu);
        }

        @Override
        public boolean onPrepareOptionsMenu(Menu menu) {

            //Get a reference to your item by id
            MenuItem item = menu.findItem(R.id.actionNotifications);
            MenuItem item1=menu.findItem(R.id.actionNotifications);
            //Here, you get access to the view of your item, in this case, the layout of the item has a FrameLayout as root view but you can change it to whatever you use
            RelativeLayout rootView = (RelativeLayout) item.getActionView();

            //Then you access to your control by finding it in the rootView
            Button control = (Button) rootView.findViewById(R.id.button1cart);
            TextView txt1noticount=(TextView)rootView.findViewById(R.id.txtCount);
            txt1noticount.setText(cartcount);
            control.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i=new Intent(Productpage.this,SimpleActivity.class);
                    startActivity(i);
                    // Toast.makeText(Productpage.this, "keval", Toast.LENGTH_SHORT).show();
                }
            });
            //And from here you can do whatever you want with your control

            return true;
        }



        public void getproductdata() {
            StringRequest request = new StringRequest(Request.Method.POST,
                    StaticDataUtility.Server_URL + "" + StaticDataUtility.catwise_product, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject joResp = new JSONObject(response);
                        sliderList = new ArrayList<>();
                        int success = joResp.getInt("Success");
                        if (success == 1) {
    //                        industryListBeanArrayList.clear();
                            JSONArray jsonArray = joResp.getJSONArray("result");
    //                        JSONObject joResult = joResp.getJSONObject("result");
    //                        JSONArray jaDetail = joResult.getJSONArray("industry_detail");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject joDetail = jsonArray.getJSONObject(i);
                                productinfo slider = new productinfo();
                                if (joDetail.has("product_id")) {
                                    slider.setProduct_id(joDetail.getString("product_id"));
                                } else {
                                    slider.setProduct_id("0");
                                }
                                if (joDetail.has("product_name")) {
                                    slider.setProduct_name(joDetail.getString("product_name"));
                                } else {
                                    slider.setProduct_name("No Item Found");
                                }
                                if (joDetail.has("product_image")) {
                                    slider.setProduct_image(joDetail.getString("product_image"));
                                } else {
                                    slider.setProduct_image("No Data");
                                }

                                if (joDetail.has("price")) {
                                    slider.setPrice(joDetail.getString("price"));
                                } else {
                                    slider.setPrice("0");
                                }
                                if (joDetail.has("special_price")) {
                                    slider.setSpecial_price(joDetail.getString("special_price"));
                                } else {
                                    slider.setSpecial_price("0");
                                }

                                if (joDetail.has("discount")) {
                                    slider.setDiscount(joDetail.getString("discount"));
                                } else {
                                    slider.setDiscount("0");
                                }
                                if (joDetail.has("is_wishlist")) {
                                    slider.setIs_wishlist(joDetail.getString("is_wishlist"));
                                } else {
                                    slider.setIs_wishlist("0");
                                }
                                sliderList.add(slider);
                            }
    //                        gridView.setAdapter(new MyAdapter1(getApplicationContext(),sliderList));
                            mAdapter = new MyAdapter1(Productpage.this,sliderList);
                         recyclerView.setAdapter(mAdapter);

                        } else {
                            Toast.makeText(Productpage.this, "Sorry Data Are Not Available ", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                        }
                    }) {
                @Override
                protected Map<String, String> getParams() {
                    HashMap<String, String> params = new HashMap<>();
                    if(flag.toString().trim().equals("true")){
                        params.put("cat_id", catid);
                        params.put("customer_id",custid);
                       // params.put("sort_by","newest");
                    }else{
                        params.put("cat_id",catid);
                        params.put("customer_id",custid);
                        if(!(intent.getStringExtra("flagfilter").equals("false"))){
                            String keval=intent.getStringExtra("flagfilter").toString();
                            if(intent.getStringExtra("flagfilter").trim().equals("Newest")) {
                                params.put("sort_by", "newest");
                            }
                            if(intent.getStringExtra("flagfilter").trim().equals("Trending")) {
                                params.put("sort_by", "trending");
                            }
                            if(intent.getStringExtra("flagfilter").trim().equals("Price: High To Low")) {
                                params.put("sort_by", "price_desc");
                            }
                            if(intent.getStringExtra("flagfilter").trim().equals("Price: Low To High")) {
                                params.put("sort_by", "price_asc");
                            }
                            if(intent.getStringExtra("category").trim().equals("Price: Low To High")){

                            }
                        }
    //                    if (trading.toString().trim().equals(trading)){
    //                      //  params.put("cat_id","292");
    //                        params.put("sort_by","trending");
    //                    }else if (newest1.toString().trim().equals(newest)){
    //                        //params.put("cat_id","292");
    //                        params.put("sort_by","newest");
    //                    }else if (high.toString().trim().equals(high)){
    //                        //params.put("cat_id","292");
    //                        params.put("sort_by","pricedesc");
    //                    }else if (low.toString().trim().equals(low)){
    //                        //params.put("cat_id","292");
    //                        params.put("sort_by","priceasc");
    //                    }
                    }

                    Log.e("params", params.toString());
                    return params;
                }
            };
            request.setRetryPolicy(new
                    DefaultRetryPolicy(60000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            // Adding request to request queue
            Volley.newRequestQueue(this).add(request);
        }


        private void setupSearchView() {
            mSearchView.setIconifiedByDefault(true);
            mSearchView.setOnQueryTextListener(this);
            mSearchView.setSubmitButtonEnabled(true);
            mSearchView.setQueryHint("Search Here");

        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            // mAdapter.filter(query);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            final List<productinfo> filteredModelList = filter((ArrayList<productinfo>)sliderList, newText);
            mAdapter.setFilter(filteredModelList);
            return true;
        }
        private List<productinfo> filter(ArrayList<productinfo> models, String query) {
            query = query.toLowerCase();
            final List<productinfo> filteredModelList = new ArrayList<>();
            for (productinfo model : models) {
                final String text = model.getProduct_name().toLowerCase();
                if (text.contains(query)) {
                    filteredModelList.add(model);
                }
            }
            return filteredModelList;
        }

        @Override
        public void onBackPressed() {
            super.onBackPressed();
            Intent i=new Intent(Productpage.this,Homepage.class);
            startActivity(i);
            finish();
        }
    }



this is my adapter class.
public class MyAdapter1 extends RecyclerView.Adapter<Home_Row_Holder1> {
Context mcontex;
    private static StrikethroughSpan STRIKE_THROUGH_SPAN;
    String title11;
    public String productid,customerid;
    String str1;
    ArrayList<productinfo> feedItemList=new ArrayList<>();
    String flag;
    String wishid;

    MyAdapter1 adpter;
    public MyAdapter1( Context mcontex, ArrayList<productinfo> feedItemList) {
        this.mcontex = mcontex;
        this.feedItemList = feedItemList;

    }

    @Override
    public Home_Row_Holder1 onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, null);
        Home_Row_Holder1 mh = new Home_Row_Holder1(v);
        return mh;
    }

    @Override
    public void onBindViewHolder(final Home_Row_Holder1 holder,final int i) {

        if(feedItemList.get(i).getProduct_name().length()>=13)
        {
            title11=feedItemList.get(i).getProduct_name().substring(0, 13)+"...";
            holder.row_1_name.setText(title11);
        }else {
            holder.row_1_name.setText(feedItemList.get(i).getProduct_name());
        }
        holder.row_3.setText(feedItemList.get(i).getSpecial_price());
        Picasso.with(mcontex).load(feedItemList.get(i).getProduct_image().trim()).placeholder(R.drawable.logo1).into(holder.product_img_home_1);
//        holder.row_1_price.setText(feedItemList.get(i).getPrice());
        STRIKE_THROUGH_SPAN = new StrikethroughSpan();
        holder.row_1_price.setText(feedItemList.get(i).getPrice(), TextView.BufferType.SPANNABLE);
        Spannable spannable = (Spannable) holder.row_1_price.getText();
        spannable.setSpan(STRIKE_THROUGH_SPAN, 0, feedItemList.get(i).getPrice().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        holder.row_2_price.setText(" "+feedItemList.get(i).getDiscount()+"%");

        if(feedItemList.get(i).getIs_wishlist().equals("0")){
            holder.wishadd.setImageResource(R.drawable.wish);
        }else {
            holder.wishadd.setImageResource(R.drawable.wishred);

        }
       /* if (flag.equals("false")) {
            holder.wishadd.findViewById(R.id.wishadd).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });*/
      //  }
        //  holder.prodid.setText(feedItemList.get(i).getProduct_id());
        holder.wishadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//
                    /*if(view.getId()==R.id.wishaddproductpage){
                        holder.wishadd.setImageResource(R.drawable.wishred);
                    }*/
                str1=feedItemList.get(i).getProduct_id();
                wishid=feedItemList.get(i).getIs_wishlist();

                if(wishid.equals("0")){
                   // holder.wishadd.setImageResource(R.drawable.wishred);
                    new Wishaddproduct().execute();
                }

                         //   flag="false";
                        if(wishid.equals("1")){
                           // flag="false";
                     //       holder.wishadd.setImageResource(R.drawable.wish);
                            new Deletewish().execute();

                        }
                  //  holder.wishadd.setImageResource(R.drawable.wishred);



            }
        });
        customerid= Homepage.strcustid;
        productid=feedItemList.get(i).getProduct_id();
        holder.product_img_home_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Context context = v.getContext();
                // Toast.makeText(mContext,String.valueOf(R.id.recycler+"   "+R.id.recyclerMen+"    "+recyclerView.getId() ),Toast.LENGTH_LONG).show();
               /* SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(mContext);
                SharedPreferences.Editor editor=sp.edit();
                editor.putString("product_id",feedItemList.get(i).getProduct_id());
                editor.putString("product_image",feedItemList.get(i).getImage());
                if(feedItemList.get(i).getProduct_name().length()>=10)
                {
                    title11=feedItemList.get(i).getProduct_name().substring(0, 10)+"...";
                    editor.putString("product_name",title11);
                }else {
                    editor.putString("product_name",feedItemList.get(i).getProduct_name());
                }
                editor.putString("product_name",feedItemList.get(i).getProduct_name());
                editor.putString("product_name",feedItemList.get(i).getProduct_name());
                editor.putString("product_description",feedItemList.get(i).getProduct_description());
                editor.putString("product_price",feedItemList.get(i).getProduct_price());
                editor.commit();*/

                Intent intent = new Intent(mcontex,singleactivity.class);

                intent.putExtra("productid",feedItemList.get(i).getProduct_id());
               // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
               // Toast.makeText(mContext,feedItemList.get(i).getProduct_id(),Toast.LENGTH_SHORT).show();
               // str1=feedItemList.get(i).getProduct_id();
                Toast.makeText(mcontex,"kkkkkkkkkk"+str1,Toast.LENGTH_SHORT).show();

            }
        });
    }
    @Override
    public int getItemCount() {
        return (null != feedItemList ? feedItemList.size() : 0);
    }

    public void setFilter(List<productinfo> countrymodel) {
        feedItemList = new ArrayList<>();
        feedItemList.addAll(countrymodel);
        notifyDataSetChanged();
    }

    private class Wishaddproduct extends AsyncTask<String,String,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... strings) {

            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("customer_id",customerid)
                    .appendQueryParameter("product_id",str1);
            HttpHandler parser = new HttpHandler();
            parser.makePostServiceCall( StaticDataUtility.Server_URL+""+ StaticDataUtility.wishlistadd, builder, parser.POST);

            return String.valueOf(true);

        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(mcontex,wishid, Toast.LENGTH_SHORT).show();

           // Toast.makeText(mcontex,str1+ "hello"+customerid, Toast.LENGTH_SHORT).show();

           updateResults(feedItemList);
           // Home_Row_Holder1.wishadd.setImageResource(R.drawable.wishred);

        }
    }

    private class Deletewish extends AsyncTask<String,String,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... strings) {

            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("customer_id",customerid)
                    .appendQueryParameter("product_id",str1);
            HttpHandler parser = new HttpHandler();
            parser.makePostServiceCall( StaticDataUtility.Server_URL+""+ StaticDataUtility.wishdelete, builder, parser.POST);

            return String.valueOf(true);

        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
       //     Home_Row_Holder1.wishadd.setImageResource(R.drawable.wish);
           // Toast.makeText(mcontex,str1+ "hello"+customerid, Toast.LENGTH_SHORT).show();
            updateResults(feedItemList);
        }
    }

    public void updateResults(ArrayList<productinfo> results ) {
        feedItemList = results;
        //Triggers the list update
         //
        // feedItemList.clear();
        feedItemList.addAll(results);
        this.notifyDataSetChanged();
      //  this.notifyItemRangeChanged((int) adpter.getItemId(i), feedItemList.size());
    }

}

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以通知适配器有关数据更改的信息。

$scope.do_something = function(string) {
    alert(string);
};