How to create Recyclerview adapter in android?

只愿长相守 提交于 2019-12-12 01:25:31

问题


I am using this LIB. It's working fine but I can not loading my data in adapter class. like. If i add some static data that will be added but whenever i tries to load from server that will not be added. finally i am trying with this approach.
But when i calls the Brandinfo and try to add data that will be error saying colon missing etc. please tell me how i can i add data to adapter to complete this recyclerview. Thanks. My Fragment class is

List<BrandInfo> mContentItems = new ArrayList<BrandInfo>();
pbDialog = new ProgressDialog(getActivity());
    // Showing progress dialog before making http request
    pbDialog.setMessage("Loading...");
    pbDialog.show();
    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d("BrandViewActivity", response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            brandInfo = new BrandInfo();
                            mContentItems.add(new BrandInfo().setBrandname(obj.getString("title")));
                            String title = obj.getString("title");
                            String location = obj.getString("location");
                            String image = obj.getString("image_path");
                            String category = obj.getString("category");

                            Log.d("fffffffffff", mContentItems.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("Error aa gai bhaya", "Error: " + error.getMessage());
            hidePDialog();

        }
    });

This is my Brandinfo class:

public class BrandInfo {
private String brandname;
private String brandinfo;
private String address;
private String detail;

public String getBrandname() {
    return brandname;
}
public void setBrandname(String brandname) {
    this.brandname = brandname;
}
public String getBrandInfo() {
    return brandinfo;
}
public void setBrandinfo(String brandinfo) {
    this.brandname = brandinfo;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}
public String getDetail() {
    return detail;
}
public void setSex(String detail) {
    this.detail = detail;
}

}

finally this is my adapter class:

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

private List<BrandInfo> brandLists = new ArrayList<BrandInfo>();
private ImageLoader imageLoader;

public TOAdapter(List<BrandInfo> brandLists) {
    this.brandLists = brandLists;
}

// Create new views (invoked by the layout manager)
@Override
public TOAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
    // create a new view
    View itemLayoutView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.list_item_card_big, null);

    // create ViewHolder

    ViewHolder viewHolder = new ViewHolder(itemLayoutView);
    return viewHolder;
}

// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {

    // - get data from your itemsData at this position
    // - replace the contents of the view with that itemsData

    BrandInfo brandList = new BrandInfo();



   imageLoader = AppController.getInstance().getImageLoader();
    viewHolder.txtViewTitle.setText(brandList.getBrandname());
    //viewHolder.thumbNail.setImageResource(itemsData[position].getImageUrl());
    if (imageLoader == null)
        imageLoader = AppController.getInstance().getImageLoader();
    viewHolder.thumbNail.setImageUrl(brandList.getBrandname(), imageLoader);


}

@Override
public int getItemCount() {
    String s = String.valueOf(brandLists.size());
    Toast.makeText(AppController.getInstance(),s,Toast.LENGTH_LONG).show();
    return brandLists.size();
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public TextView txtViewTitle;
    final NetworkImageView thumbNail;

    public ViewHolder(View itemLayoutView) {
        super(itemLayoutView);
        txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.brandtitle);

        thumbNail = (NetworkImageView) itemLayoutView
                .findViewById(R.id.thumbnail);
    }
}

}


回答1:


So what I would recommend is the following (which I use in my own project):

Create the following method in you TOAdapter:

public void refreshRecyclerViewBrands(List<BrandInfo> brandLists) {
    this.brandLists = brandLists;
    notifyDataSetChanged();
}

Then call the following method from where you initialized the recyclerviewadapter and your list:

mAdapter.refreshRecyclerViewBrands(mContentItems);

This basically takes the list you just got from volley and tells the recyclerview to use this new list and refresh the recyclerview. This worked for me so hopefully will work for you.

Another thing I noticed is in your onBindViewHolder your are setting the following:

BrandInfo brandList = new BrandInfo();

Then you use:

viewHolder.txtViewTitle.setText(brandList.getBrandname());

But brandlist.getBrandname is null. Never are you actually giving the brandlist object any values, rather use the following :

final BrandInfo brandList = brandLists.get(position);

Hope this helps.




回答2:


you should do like this

  JSONObject obj = response.getJSONObject(i);
  brandInfo = new BrandInfo();
  mContentItems.add(new                      
  BrandInfo(obj.getString("title"),
   obj.getString("title");
   obj.getString("location");
   obj.getString("image_path");
   obj.getString("category");

then i add my adapter like this CustomSourcingAdapter adapter=new
CustomSourcingAdapter(Sourcing_modes.this, publishPlacementList); lists.setAdapter(adapter);

this is my custom Adapter class
    public class CustomSourcingAdapter extends ArrayAdapter<SourcingModel> {

private final Activity context;

private final List<SourcingModel> publishPlacementList;

public CustomSourcingAdapter(Activity context,List<SourcingModel>       
publishPlacementList) {
    // TODO Auto-generated constructor stub

    super(context, R.layout.sorsinglist,publishPlacementList);
    // TODO Auto-generated constructor stub
    this.context=context;
    this.publishPlacementList=publishPlacementList;

}

static class ViewHolder {
    protected TextView placementtitle;
    protected TextView Noofposition;
    protected ImageButton next;
    protected TextView Department;

}

public View getView(int position,View converview,ViewGroup parent) {
    ViewHolder viewHolder = null;
    if (converview ==null ){
        LayoutInflater inflater=context.getLayoutInflater();
        converview=inflater.inflate(R.layout.sorsinglist, null);
        viewHolder = new ViewHolder();




        converview.setTag(viewHolder);
        converview.setTag(R.id.idplacetitle,viewHolder.placementtitle);
        converview.setTag(R.id.idnoofpos,viewHolder.Noofposition);
        converview.setTag(R.id.imreqserch,viewHolder.next);
        converview.setTag(R.id.iddepartment,viewHolder.Department);
    }else{
        viewHolder= (ViewHolder)converview.getTag();
    }

viewHolder.placementtitle.setText(publishPlacementList.get(position).getPositionName()); viewHolder.Noofposition.setText(publishPlacementList.get(position).getNoOfPosition()); viewHolder.Department.setText(publishPlacementList.get(position).getName());

    viewHolder.next.setTag(position);

       viewHolder.next.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int pos = (Integer) v.getTag();
            long  id = publishPlacementList.get(pos).getId();

            Intent it = new Intent(context, SourcingSecond.class);
            it.putExtra("id", id);
            context.startActivity(it);

        }
    });


    return converview;

};


来源:https://stackoverflow.com/questions/30456928/how-to-create-recyclerview-adapter-in-android

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