1

My StaggeredGridLayoutManager dont show anything. the arraylist iList always has size 0. I have put a breakpoint in queryProduct.execute(""); and I can observe that the method protected String doInBackground(String... params) never is executed . Why not my dataset isnt loaded here?

public class OnSale extends CustomFragment
{

    /** The product list. */
    private ArrayList<Producto> iList;
    private QueryProduct queryProduct;

    /* (non-Javadoc)
     * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
     */
    @SuppressLint({ "InflateParams", "InlinedApi" })
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        View v = inflater.inflate(R.layout.on_sale, null);

        ((MainActivity) getActivity()).toolbar.setTitle("On Sale");
        ((MainActivity) getActivity()).toolbar.findViewById(
                R.id.spinner_toolbar).setVisibility(View.GONE);

        /*if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP)
        {
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }*/

        setHasOptionsMenu(true);

        setupView(v);
        return v;
    }

    /* (non-Javadoc)
     * @see com.whatshere.custom.CustomFragment#onClick(android.view.View)
     */
    @Override
    public void onClick(View v)
    {
        super.onClick(v);
    }

    /**
     * Setup the view components for this fragment. You write your code for
     * initializing the views, setting the adapters, touch and click listeners
     * etc.
     *
     * @param v
     *            the base view of fragment
     */
    private void setupView(View v)
    {



        RecyclerView recList = (RecyclerView) v.findViewById(R.id.lista_de_productos_on_sale);
        loadDummyData();
        recList.setHasFixedSize(true);
        StaggeredGridLayoutManager llm = new StaggeredGridLayoutManager(2,
                StaggeredGridLayoutManager.VERTICAL);
        recList.setLayoutManager(llm);
        CardAdapter ca = new CardAdapter();
        recList.setAdapter(ca);

    }

    /**
     * The Class CardAdapter is the adapter for showing products in Card format
     * inside the RecyclerView. It shows dummy product image and dummy contents,
     * so you need to display actual contents as per your need.
     */
    private class CardAdapter extends
            RecyclerView.Adapter<CardAdapter.CardViewHolder>
    {

        /* (non-Javadoc)
         * @see android.support.v7.widget.RecyclerView.Adapter#getItemCount()
         */
        @Override
        public int getItemCount()
        {
            return iList.size();
        }

        /* (non-Javadoc)
         * @see android.support.v7.widget.RecyclerView.Adapter#onBindViewHolder(android.support.v7.widget.RecyclerView.ViewHolder, int)
         */
        @Override
        public void onBindViewHolder(CardViewHolder vh, int i)
        {

            Producto d = iList.get(i);
            vh.lbl1.setText(d.getTexts()[0]);
            vh.lbl2.setText(d.getTexts()[1]);
            vh.lbl3.setText(d.getTexts()[2]);
            vh.img.setImageBitmap(d.getResources());
        }

        /* (non-Javadoc)
         * @see android.support.v7.widget.RecyclerView.Adapter#onCreateViewHolder(android.view.ViewGroup, int)
         */
        @Override
        public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i)
        {
            View itemView = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.grid_item, viewGroup, false);
            itemView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v)
                {
                    startActivity(new Intent(getActivity(), ProductDetail.class));
                }
            });
            return new CardViewHolder(itemView);
        }

        /**
         * The Class CardViewHolder is the View Holder class for Adapter views.
         */
        public class CardViewHolder extends RecyclerView.ViewHolder
        {

            /** The lbl3. */
            protected TextView lbl1, lbl2, lbl3;

            /** The img. */
            protected ImageView img;

            /**
             * Instantiates a new card view holder.
             *
             * @param v
             *            the v
             */
            public CardViewHolder(View v)
            {
                super(v);
                lbl1 = (TextView) v.findViewById(R.id.lbl1);
                lbl2 = (TextView) v.findViewById(R.id.lbl2);
                lbl3 = (TextView) v.findViewById(R.id.lbl3);
                img = (ImageView) v.findViewById(R.id.img);
            }
        }
    }

    /**
     * Load dummy product data for displaying on the RecyclerView. You need to
     * write your own code for loading real products from Web-service or API and
     * displaying them on RecyclerView.
     */
    private void loadDummyData()
    {
        iList= new ArrayList<Producto>();
        queryProduct =new QueryProduct();
        queryProduct.execute("");
    }

    /* (non-Javadoc)
     * @see android.support.v4.app.Fragment#onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater)
     */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
    {
        inflater.inflate(R.menu.search_exp, menu);
        menu.findItem(R.id.menu_grid).setVisible(false);
        super.onCreateOptionsMenu(menu, inflater);

    }

    class QueryProduct extends AsyncTask<String, Void, String> {

        ArrayList<Producto> alistaDeProductos=new ArrayList<Producto>();



        @Override
        protected String doInBackground(String... params) {
            String result = "";



            String s = "";
            InputStream isr = null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://aaaaa/app/getAllCustomers.php"); // YOUR PHP
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                isr = entity.getContent();
            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection " + e.toString());


            }
            // convert response to string
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(isr, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                isr.close();

                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error  converting result " + e.toString());

            }

            // parse json data
            try {

                JSONArray jArray = new JSONArray(result);
                Integer size=jArray.length();

                for (int i = 0; i < jArray.length(); i++) {

                    JSONObject json = jArray.getJSONObject(i);


                    InputStream in = new java.net.URL(json.getString("imagen")).openStream();

                    Bitmap loadedImage= BitmapFactory.decodeStream(in);
//
                    Producto producto=new Producto(new String[]{"50",json.getString("descripcion"),json.getString("preciodia"),json.getString("marca")},loadedImage);

                    iList.add(producto);







                }


            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();



            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }



            return s;


        }



    }
}
tipiwiny
  • 399
  • 1
  • 3
  • 18
  • This may help you http://stackoverflow.com/questions/10328645/asynctask-called-from-handler-will-not-execute-doinbackground/10406894#10406894 – Andrew Fielden May 20 '15 at 10:02

1 Answers1

0

I can found my mistake. I need notify a my adapter, in this case called CardAdapter , the diferents changes. This can be achieved thanks to method notifyDataSetChanged(). You should use adapter.notifyDataSetChanged() after of load your dataset. if you want to read more information you can visit this link RecyclerView Adapter and ViewHolder update dynamically

Here my corrected code

public class OnSale extends CustomFragment
{

    /** The product list. */
    private ArrayList<Producto> iList;
    private QueryProduct queryProduct;
    CardAdapter ca = new CardAdapter();


    /* (non-Javadoc)
     * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
     */
    @SuppressLint({ "InflateParams", "InlinedApi" })
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        View v = inflater.inflate(R.layout.on_sale, null);

        ((MainActivity) getActivity()).toolbar.setTitle("On Sale");
        ((MainActivity) getActivity()).toolbar.findViewById(
                R.id.spinner_toolbar).setVisibility(View.GONE);

        /*if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP)
        {
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }*/

        setHasOptionsMenu(true);

        setupView(v);
        return v;
    }

    /* (non-Javadoc)
     * @see com.whatshere.custom.CustomFragment#onClick(android.view.View)
     */
    @Override
    public void onClick(View v)
    {
        super.onClick(v);
    }

    /**
     * Setup the view components for this fragment. You write your code for
     * initializing the views, setting the adapters, touch and click listeners
     * etc.
     *
     * @param v
     *            the base view of fragment
     */
    private void setupView(View v)
    {



        RecyclerView recList = (RecyclerView) v.findViewById(R.id.lista_de_productos_on_sale);

        recList.setHasFixedSize(true);
        StaggeredGridLayoutManager llm = new StaggeredGridLayoutManager(2,
                StaggeredGridLayoutManager.VERTICAL);
        recList.setLayoutManager(llm);

        loadDummyData();




        recList.setAdapter(ca);


    }

    /**
     * The Class CardAdapter is the adapter for showing products in Card format
     * inside the RecyclerView. It shows dummy product image and dummy contents,
     * so you need to display actual contents as per your need.
     */
    private class CardAdapter extends
            RecyclerView.Adapter<CardAdapter.CardViewHolder>
    {

        /* (non-Javadoc)
         * @see android.support.v7.widget.RecyclerView.Adapter#getItemCount()
         */
        @Override
        public int getItemCount()
        {
            return iList.size();
        }

        /* (non-Javadoc)
         * @see android.support.v7.widget.RecyclerView.Adapter#onBindViewHolder(android.support.v7.widget.RecyclerView.ViewHolder, int)
         */
        @Override
        public void onBindViewHolder(CardViewHolder vh, int i)
        {

            Producto d = iList.get(i);
            vh.lbl1.setText(d.getTexts()[0]);
            vh.lbl2.setText(d.getTexts()[1]);
            vh.lbl3.setText(d.getTexts()[2]);
            vh.img.setImageBitmap(d.getResources());


        }

        /* (non-Javadoc)
         * @see android.support.v7.widget.RecyclerView.Adapter#onCreateViewHolder(android.view.ViewGroup, int)
         */
        @Override
        public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i)
        {
            View itemView = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.grid_item, viewGroup, false);
            itemView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v)
                {
                    startActivity(new Intent(getActivity(), ProductDetail.class));
                }
            });
            return new CardViewHolder(itemView);
        }

        /**
         * The Class CardViewHolder is the View Holder class for Adapter views.
         */
        public class CardViewHolder extends RecyclerView.ViewHolder
        {

            /** The lbl3. */
            protected TextView lbl1, lbl2, lbl3;

            /** The img. */
            protected ImageView img;

            /**
             * Instantiates a new card view holder.
             *
             * @param v
             *            the v
             */
            public CardViewHolder(View v)
            {
                super(v);
                lbl1 = (TextView) v.findViewById(R.id.lbl1);
                lbl2 = (TextView) v.findViewById(R.id.lbl2);
                lbl3 = (TextView) v.findViewById(R.id.lbl3);
                img = (ImageView) v.findViewById(R.id.img);
            }
        }
    }

    /**
     * Load dummy product data for displaying on the RecyclerView. You need to
     * write your own code for loading real products from Web-service or API and
     * displaying them on RecyclerView.
     */
    private void loadDummyData()
    {
        iList= new ArrayList<Producto>();
        queryProduct =new QueryProduct();
        queryProduct.execute("");

    }

    /* (non-Javadoc)
     * @see android.support.v4.app.Fragment#onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater)
     */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
    {
        inflater.inflate(R.menu.search_exp, menu);
        menu.findItem(R.id.menu_grid).setVisible(false);
        super.onCreateOptionsMenu(menu, inflater);

    }

    class QueryProduct extends AsyncTask<String, Void, String> {

        ArrayList<Producto> alistaDeProductos=new ArrayList<Producto>();



        @Override
        protected String doInBackground(String... params) {
            String result = "";



            String s = "";
            InputStream isr = null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://aaa.php"); // YOUR PHP
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                isr = entity.getContent();
            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection " + e.toString());


            }
            // convert response to string
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(isr, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                isr.close();

                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error  converting result " + e.toString());

            }

            // parse json data
            try {

                JSONArray jArray = new JSONArray(result);


                for (int i = 0; i < jArray.length(); i++) {

                    JSONObject json = jArray.getJSONObject(i);


                    InputStream in = new java.net.URL(json.getString("imagen")).openStream();

                    Bitmap loadedImage= BitmapFactory.decodeStream(in);
//
                    Producto producto=new Producto(new String[]{"50",json.getString("descripcion"),json.getString("preciodia"),json.getString("marca")},loadedImage);

                    iList.add(producto);









                }


            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();



            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }





            return s;


        }

        @Override
        protected void onPostExecute(String s) {
            ca.notifyDataSetChanged();
        }
    }
}
Community
  • 1
  • 1
tipiwiny
  • 399
  • 1
  • 3
  • 18