Dynamicaly loading data to Gridview

拟墨画扇 提交于 2019-12-20 02:56:06

问题


While i am working on gridview i faced following problems, any help will be appreciated,

  1. When I load data to my gridview it loads only first 3 items of the array but there are 18 items to be load. why it doesn't load other 15 items. (Log.i it shows all the 18 items in my LogCat).

  2. Since there are only 18 items belongs to the MainCategoryID=1, it should load only 18 grids, but this loads 28 grids(that is because there are 28 items inside responseJson). I want to limit it to 18 grids. (Inside the loaded 28 grids, there are 3 items loaded and there have repeated in couple of places and other grids are empty grids)

PizzaFragment class

public class PizzaFragment extends ListFragment implements OnTaskCompleted {

    private TranslateAnimation anim;
    GridView grid;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.menu_grid_main, container, false);

        new PizzaMenuAsyncTask(getActivity(), this).execute();


        grid = (GridView) view.findViewById(R.id.grid);
        return view;
    }

    @Override
    public void onTaskCompleted(JSONArray responseJson) {

        try
        {
            String[] Description = new String[responseJson.length()];
            String[] ImageURL = new String[responseJson.length()];
            for (int i = 0; i < responseJson.length(); i++)
            {
                JSONObject object = responseJson.getJSONObject(i);
                if ((object.getString("MainCategoryID")).equals("1"))
                {
                    Log.i("MainCategoryID ", object.getString("ImageURL"));
                    ImageURL[i] = object.getString("ImageURL");
                    Log.i("MainCategoryID ", object.getString("Description"));
                    Description[i] = object.getString("Description");

                   CustomGrid adapter = new CustomGrid(getActivity(), Description, ImageURL);
                grid.setAdapter(adapter);
                }

            }
        }
            catch (JSONException e) {
            e.printStackTrace();
        }
    }

CustomGrid

public class CustomGrid extends BaseAdapter {

    private Context mContext;
    private final String[] Description;
    private final String[] ImageURL;

    public CustomGrid(Context c, String[] Description, String[] ImageURL) {
        mContext = c;
        this.ImageURL = ImageURL;
        this.Description = Description;
    }

    @Override
    public int getCount() {
        return Description.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

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

        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {

            grid = new View(mContext);
            grid = inflater.inflate(R.layout.fragment_pizza, null);
            TextView textView = (TextView) grid.findViewById(R.id.grid_text);
            ImageView imageView = (ImageView) grid
                    .findViewById(R.id.grid_image);
            textView.setText(Description[position]);
            Picasso.with(mContext).load(ImageURL[position]).into(imageView);
        } else {
            grid = (View) convertView;
        }

        return grid;
    }
}

this is how my screen looks like (this is not the real image but this is how it looks)


回答1:


Once check the loop onTaskCompleted method. you are creating instance of the adapter and setting to gridview inside loop i think its wrong after observing and checking your code i found the first issue.

Second the way you are handling Adapter view inflating method for populating row is also wrong and i can say not a proper way...

So once check the below code for the adapter and onTaskCompleted method.

@Override
    public void onTaskCompleted(JSONArray responseJson) {

        try {
            String[] Description = new String[responseJson.length()];
            String[] ImageURL = new String[responseJson.length()];
            JSONArray jArrayCategoryWise = new JSONArray();
            for (int i = 0; i < responseJson.length(); i++) {
                JSONObject object = responseJson.getJSONObject(i);
                if ("1".equalsIgnoreCase(object.getString("MainCategoryID"))) {
                    // add to another jsonarray if MainCategoryID == 1
                    jArrayCategoryWise.put(object);
                }
            }

            /******
             * You can also create class with getter setter method for the
             * Description and ImageUrl.Make the arraylist of the class after
             * parsing jsonArray.
             */
            // which will required on more iteration of your json array response
            CustomGrid adapter = new CustomGrid(getActivity(),
                    jArrayCategoryWise);
            grid.setAdapter(adapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

Once check the data is coming properly or not.or are you adding anything in between

ADAPTER

    public class CustomGrid extends BaseAdapter {

    private Context context;
    private Context mContext;
    // private final String[] Description;
    // private final String[] ImageURL;
    private JSONArray json;
    private int size = 0;

    public CustomGrid(Context c, JSONArray json) {
        this.context = c;
        this.json = json;
        if (this.json != null)
            size = this.json.length();
        // You can also create class with getter setter method (getter setter
        // for Descriptions and ImageUrl). and pass arraylist of that class

        // this.Description = Description;
        // this.ImageURL = ImageURL;
    }

    @Override
    public int getCount() {
        return size;
    }

    @Override
    public Object getItem(int position) {
        return this.json.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(
                    R.layout.custom_trips_frag_row, parent, false);
            holder.ivImage = (ImageView) convertView
                    .findViewById(R.id.grid_image);
            holder.tvHeader = (TextView) convertView
                    .findViewById(R.id.grid_text);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        JSONObject jObjectRowData = this.json.getJSONObject(position);
        holder.tvHeader.setText(jObjectRowData.getString("Description"));
        Picasso.with(this.context).load(jObjectRowData.getString("ImageURL"))
                .into(holder.ivImage);

        return convertView;
    }

    private class ViewHolder {
        private TextView tvHeader;
        private ImageView ivImage;
    }
}

Please check the answer.. hope i gt ur quesion correctly and you gt your answer ... * Suggestion * ONCE CHECK THE ViewHolder class pattern for the BaseAdapter.




回答2:


First, change your adapter to expends the

extends ArrayAdapter<String>

Change the constructor: public CustomGrid(Context c) { super(c, R.layout.fragment_pizza); } Now Change getView() method:

// Get the item
        String item = getItem(position);

Set this item text to your view and if you require more data sets, create the model class and change extends ArrayAdapter<String> with extends ArrayAdapter<ModelClass> and

 // Get the item
            ModelClass item = getItem(position);

Now in your Activity class, initilize the ModelClass, set it's variables and add to the adapter using add or addAll methods.



来源:https://stackoverflow.com/questions/28166003/dynamicaly-loading-data-to-gridview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!