加载我的数据集并在我的StaggeredGridLayoutManager中显示

时间:2015-05-20 08:17:05

标签: android json android-recyclerview

我的StaggeredGridLayoutManager不显示任何内容。 arraylist iList的大小始终为0.我在queryProduct.execute("");中设置了一个断点,我可以观察到方法protected String doInBackground(String... params)永远不会被执行。为什么我的数据集没有加载到这里?

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;


        }



    }
}

1 个答案:

答案 0 :(得分:0)

我可以找到我的错误。我需要通知我的适配器,在这种情况下称为CardAdapter,差异更改。这可以通过方法notifyDataSetChanged()来实现。加载数据集后应使用adapter.notifyDataSetChanged()。 如果您想了解更多信息,可以访问此链接RecyclerView Adapter and ViewHolder update dynamically

此处我的更正后的代码

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();
        }
    }
}