Android Recycler View - android

I am using RecyclerView to display my products, problem is when if I select the first products and scroll down to the end of list I see different products selected and when i scroll back to top of list the first item is not selected.
My Adapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
String u = "http://192.185.52.231/~sabby070/hyype/";
Context context1;
private java.util.List<ProductDetails> List;
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_list, parent, false);
return new MyViewHolder(itemView);
}
public RecyclerAdapter(List<ProductDetails> DataList, FragmentActivity activity) {
this.List = DataList;
context1 = activity;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView Likecount;
public ImageView Image;
public ImageView Imagelike, ImageUnlike;
public MyViewHolder(View view) {
super(view);
Likecount = (TextView) view.findViewById(R.id.textView_itemPrice);
Image = (ImageView) view.findViewById(R.id.imageView_imgtosold);
Imagelike = (ImageView)view.findViewById(R.id.Like_Button);
ImageUnlike = (ImageView)view.findViewById(R.id.UnLike_Button);
}
}
#Override
public void onBindViewHolder(final RecyclerAdapter.MyViewHolder holder, final int position) {
final ProductDetails detail = List.get(position);
holder.Likecount.setText(detail.getLikeCount());
Glide.with(context1).load(u+detail.getImage()).override(600, 200).diskCacheStrategy(DiskCacheStrategy.ALL).into(holder.Image);
holder.Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context1, ""+position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context1, Buy_Product.class);
intent.putExtra("Product Name",detail.getLikeCount());
intent.putExtra("Product Image",detail.getImage());
context1.startActivity(intent);
}
});
holder.Imagelike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.Imagelike.getVisibility()==View.VISIBLE)
{
holder.Imagelike.setVisibility(View.GONE);
holder.ImageUnlike.setVisibility(View.VISIBLE);
}
}
});
holder.ImageUnlike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.ImageUnlike.getVisibility()==View.VISIBLE)
{
holder.Imagelike.setVisibility(View.VISIBLE);
holder.ImageUnlike.setVisibility(View.GONE);
}
}
});
}
#Override
public int getItemCount() {
return List.size();
}
}
My class
public class Men_Fragment extends Fragment {
static String URL = "http://192.185.52.231/~sabby070/hyype/index.php?action=timeline&user_id=53&post_category=timeline";
private List<ProductDetails> DataList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerAdapter rAdapter;
String img;
String a;
Boolean list[];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_men_, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.men_recycler_view);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
for (int i = 0; i < response.length(); i++) {
JSONObject obj = jsonObject.getJSONObject(String.valueOf(i));
a = obj.getString("like_count");
img = obj.getString("video_thumb");
final ProductDetails details = new ProductDetails(a, img);
DataList.add(details);
rAdapter = new RecyclerAdapter(DataList, getActivity());
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(rAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
return view;
}
}

You have to take List(with boolean) and store selected values in that list and then use those values in onBindView()

In your ProductDetails class add a field boolean selected;
In your onClick() add List.get(position).setSelected(!List.get(position).isSelected()); to check/uncheck as needed.
Finaly in your onBindViewHolder(...) add
if(List.get(position).isSelected()){
holder.Imagelike.setVisibility(View.VISIBLE);
}else{
holder.ImageUnlike.setVisibility(View.GONE);
}

Related

Get selected item text from RecycleView when button clicked

I just want to create a list that will show currently selected item text when I click "Selanjutnya" button, but I don't know how to do that.
So when I click "Selanjutnya", it will show 22, 23. Currently, I use Big Nerd Ranch multi-select to make multi-selection work.
implementation 'com.bignerdranch.android:recyclerview-multiselect:+'
And here is my Codes.
Adapter
public class KetuaAbsenAdapter extends RecyclerView.Adapter<KetuaAbsenAdapter.ViewHolder> {
private List<KetuaAbsenList> listItems;
private Context context;
private MultiSelector mMultiSelector = new MultiSelector();
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.absen_list, parent, false);
return new ViewHolder(v);
}
public KetuaAbsenAdapter(List<KetuaAbsenList> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final KetuaAbsenList listItem = listItems.get(position);
holder.textViewMuridno.setText(listItem.getMuridno());
holder.textViewMuridnama.setText(listItem.getMuridnama());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends SwappingHolder implements View.OnClickListener {
public TextView textViewMuridno;
public TextView textViewMuridnama;
public TextView textViewMuridkelas;
public LinearLayout list_item_linear;
public ViewHolder(View itemView) {
super(itemView, mMultiSelector);
textViewMuridno = (TextView) itemView.findViewById(R.id.muridno);
textViewMuridnama = (TextView) itemView.findViewById(R.id.muridnama);
textViewMuridkelas = (TextView) itemView.findViewById(R.id.muridkelas);
list_item_linear = (LinearLayout) itemView.findViewById(R.id.list_item_linear);
list_item_linear.setOnClickListener(this);
itemView.setOnClickListener(this);
mMultiSelector.setSelectable(true);
}
#Override
public void onClick(View v) {
if (mMultiSelector.tapSelection(this)) {
Toast.makeText(context, "terpilih", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "tidak terpilih", Toast.LENGTH_LONG).show();
}
}
}
}
List Class
public class KetuaDaftarAbsen extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<KetuaAbsenList> listItems;
EditText YangTidakHadir;
Button KetuaLanjut;
Dialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ketua_daftar_absen);
YangTidakHadir = (EditText)findViewById(R.id.YangTidakHadir);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-message"));
}
public void loadRecyclerViewData(){
final String url = "https://gameblong.com/raset/daftar_absen.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
String status = jsonObject.getString("status");
if(status.equals("sukses")){
JSONArray array = jsonObject.getJSONArray("semua");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
KetuaAbsenList item = new KetuaAbsenList(
o.getString("murid_no"),
o.getString("murid_nama"),
o.getString("murid_kelas")
);
listItems.add(item);
}
} else {
}
adapter = new KetuaAbsenAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return params;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
final String muno = intent.getStringExtra("muridnomor");
KetuaLanjut = (Button)findViewById(R.id.KetuaLanjut);
KetuaLanjut.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(context, muno, Toast.LENGTH_LONG).show();
}
});
}
};
}
I can use mMultiSelector.getSelectedPositions(); on my Adapter, but only this only gives current selected position (like 0, 1),
You can create an Interface that you add to your adapter and a listener for it.
public interface OnAdapterItemClicked {
// you can name it what ever you need add pass more parameters
void itemClicked(String text);
}
then in your adapter, you initialise it and add the listener on the click event,
private OnAdapterItemClicked mListener = null;
...
#Override
public void onBindViewHolder(#NonNull YourAdapter.ViewHolder holder,
int position) {
...
holder.YourBtn.setOnClickListener(....{
mListener.itemClicked("string you need to pass")
});
...
}
...
public void setOnItemClickListener(OnAdapterItemClicked listener) {
this.mListener = listener;
}
finally in you activity/fragment you add a listener on the recyclerview
rv.setOnItemClickListener(new OnAdapterItemClicked () {
#Override
public void itemClicked(String text) {
Log.d(TAG, "itemClicked: "+text);
}
});
In your adapter, you can add onClickListener like this
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.absen_list, parent, false);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//your logic goes here
}
});
return new ViewHolder(v);
}

recyclerview doesn't show any thing in fragment

hi guys i have a card view that populate it's data from a json. I parse json with volley and it is successfull .
but in card view there is nothing to show
here is my json
{"photo":[{"id":"4","profile_id":"mahdi","caption":"hello","image_url":"https:\/\/hemispheric-suggest.000webhostapp.com\/img\/img\/birjand.jpg","profile_img_url":"https:\/\/hemispheric-suggest.000webhostapp.com\/prof\/prof\/prof_1.jpg","insert_time":"2017-07-09 11:21:44"}
and my fragment adapter :
private RecyclerView recyclerView;
private RequestQueue mRequestQueue;
ArrayList<Card> list = new ArrayList<>();
String url = "My url";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag,container,false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
mRequestQueue = Volley.newRequestQueue(getActivity());
list();
LinearLayoutManager MyLayoutManager = new LinearLayoutManager(getActivity());
MyLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setAdapter(new Adapter(list));
return view;
}
public class Adapter extends RecyclerView.Adapter<Adapter.MyviewHolder>{
// private ArrayList<Card> list;
public Adapter(ArrayList<Card> data) {
list = data;
}
public class MyviewHolder extends RecyclerView.ViewHolder{
public TextView textView;
public ImageView imageView;
public MyviewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.textView);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
}
}
#Override
public MyviewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_row,parent,false);
return new MyviewHolder(view);
}
#Override
public void onBindViewHolder(MyviewHolder holder, int position) {
Card card = list.get(position);
holder.textView.setText(card.getName());
Glide.with(getActivity()).load(card.getImg()).into(holder.imageView);
}
#Override
public int getItemCount() {
return list.size();
}
}
public void list() {
JsonObjectRequest object = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
JSONArray array = response.getJSONArray("photo");
for (int i = 0; i <array.length() ; i++) {
JSONObject temp = array.getJSONObject(i);
Card card = new Card();
card.setName(temp.getString("profile_id"));
card.setImg(temp.getString("image_url"));
list.add(card);
}
}catch (Exception ex){
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
mRequestQueue.add(object);
}
}
Volley is asynchronus, so when you call:
recyclerView.setAdapter(new Adapter(list));
just a few milliseconds after you enqueued your request, It's very likely that the list is still empty because Volley hasn't received any response yet. You should set your adapter once you get the response inside the onResponse callback.

android - recyclerview cannot click and get position

I have tried some code to can click recyclerview item and get position, but I can't click the recyclerview item.. the data I get from url. So I wan't switch activity with get the item user click..
how I can fix that?
this code for adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
private static final String TAG = RecyclerViewAdapter.class.getSimpleName();
List<GetDataAdapter> getDataAdapter;
ImageLoader imageLoader1;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context) {
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getDataAdapter1.getImageServerUrl(),
ImageLoader.getImageListener(
Viewholder.networkImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.networkImageView.setImageUrl(getDataAdapter1.getImageServerUrl(), imageLoader1);
Viewholder.ImageTitleNameView.setText(getDataAdapter1.getImageTitleName());
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleNameView;
public NetworkImageView networkImageView;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item);
networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1);
}
}
}
and this code for mainactivity
public class MainActivity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL = "http://androidblog.esy.es/ImageJsonData.php";
String JSON_IMAGE_TITLE_NAME = "image_title";
String JSON_IMAGE_URL = "image_url";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
getdataadapter
public class GetDataAdapter {
public String ImageServerUrl;
public String ImageTitleName;
public String getImageServerUrl() {
return ImageServerUrl;
}
public void setImageServerUrl(String imageServerUrl) {
this.ImageServerUrl = imageServerUrl;
}
public String getImageTitleName() {
return ImageTitleName;
}
public void setImageTitleNamee(String Imagetitlename) {
this.ImageTitleName = Imagetitlename;
}
}
You need to set onClickListener to your item view. You can do by following below steps:
Set onCLickListener to root view of your list item.
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
Add below code in onCreateViewHolder:
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Add your logic here
}
});
You can add listener while onBindViewHolder:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Add your logic here
}
});
Thanks.
Put a listener on your recycler item view and then in onclick, start intent to open new activity. Pass the data object you want to pass with the intent.
//make sure your model class GetDataAdapter implements Parcelable
holder.itemView.setOnclickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this, ActivityToOpen.class);
intent.putExtra("key",Your Object to pass);// getDataAdapter1 in your case
context.startActivity(intent);
}
});
then in your Startted activity receive your object like this
YourObject obj = getIntent().getParcelableExtra("key");
//Your case
GetDataAdapter obj = getIntent().getParcelableExtra("key");

adapter.setNotifyDatachanged() is not working as expected in android

This is my code file.
public class FragmentOfferList extends ListFragment {
private RecyclerView recyclerView;
private String TAG = FragmentOfferList.class.getSimpleName();
private static final String endpoint = "http://example.com/offer/offers.json";
private List<Offer> offers = new ArrayList<>();
private ProgressDialog pDialog;
RecyclerView.Adapter adapter;
public FragmentOfferList() {
}
public static FragmentOfferList newInstance(int num) {
FragmentOfferList f = new FragmentOfferList();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pDialog = new ProgressDialog(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.recycler_list, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new MyAdapter(offers, getActivity());
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Offer offer = Utility.getOffers().get(position);
Intent intent = new Intent(getActivity(), ActivityProductList.class);
intent.putExtra("query", offer.getQuery());
startActivity(intent);
//startActivity(new Intent(getActivity(), ActivityProductList.class));
}
#Override
public void onLongClick(View view, int position) {
}
}));
if (Utility.getOffers().size() == 0){
fetchOffers();
}
else{
Utility.displayToast("here");
offers = Utility.getOffers();
adapter.notifyDataSetChanged();
}
return v;
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<Offer> offers;
private Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, year, offer;
ImageView imageView;
public MyViewHolder(View view) {
super(view);
imageView = (ImageView) view.findViewById(R.id.thumbnail);
title = (TextView) view.findViewById(R.id.title);
offer = (TextView) view.findViewById(R.id.offer);
}
}
public MyAdapter(List<Offer> offers, Context context) {
this.offers = offers;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_offer, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Offer offer = offers.get(position);
holder.title.setText(offer.getName());
holder.offer.setText(offer.getOffer());
Glide.with(context).load(String.valueOf(offer.getUrl()))
.error(R.drawable.placeholder)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.imageView);
}
#Override
public int getItemCount() {
return offers.size();
}
}
private void fetchOffers() {
pDialog.setMessage("Downloading json...");
pDialog.show();
JsonArrayRequest req = new JsonArrayRequest(endpoint,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.hide();
offers.clear();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
Offer offer = new Offer();
offer.setOffer(object.getString("offer"));
offer.setName(object.getString("name"));
offer.setUrl(object.getString("url"));
offer.setQuery(object.getString("query"));
offers.add(offer);
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
}
Utility.setOffers(offers);
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
First time when Utility.getoffers().size() is 0, it fetches data, save it in Utility.setOffers(offers) and display on screen as expected. But next time (go back and to same activity), Utility.getoffers().size() is not 0 , i got data directly from Utility.getBrands().
After that i called adapter.notifyDataSetChaned(), but it is not working. Not working menas even though data sise is more than 0 but no data rendering on screen?
What is wrong here? am i missing anything?
You are not updating your offers list, but rather replacing it with another list that your adapter has no reference to. To fix this you can do the following:
offers.clear();
offers.addAll(Utility.getOffers());
adapter.notifyDataSetChanged();

I need to show some details from my web service to recyclerview but Its not work

This is my Fragment class in here I can't create instance of Person class. While try am to create instance of Person class, showing error as Person(String,String) in Person can not be applied to zero.
public class MainActivityFragment extends Fragment {
private final List<Person> mPersonList = new ArrayList<>();
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Context context = getActivity();
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
final RVAdapter rvAdapter = new RVAdapter(mPersonList);
recyclerView.setAdapter(rvAdapter);
RequestQueue requestQueue = Volley.newRequestQueue(context);
String url = "http://192.16.1.100/api/persons";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Person person=new Person();
person.phone_name = jsonObject.getString("name");
person.phone_price = jsonObject.getString("dddd");
mPersonList.add(i, person);
}
rvAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
});
requestQueue.add(jsonArrayRequest);
return view;
} }
My Person class
class Person {
public String phone_name;
public String phone_price;
Person(String phone_name, String phone_price) {
this.phone_name = phone_name;
this.phone_price = phone_price;
} }
My Adapter class is
public class RVAdapter extends
RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
List<Person> persons;
RVAdapter(List<Person> persons) {
this.persons = persons;
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview,
parent, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder holder, int position) {
holder.phoneName.setText(persons.get(position).phone_name);
holder.phonePrice.setText(persons.get(position).phone_price);
}
#Override
public int getItemCount() {
if (persons != null) {
return persons.size();
}
return 0;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView phoneName;
TextView phonePrice;
PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.card_view);
phoneName = (TextView) itemView.findViewById(R.id.phone_name);
phonePrice = (TextView) itemView.findViewById(R.id.phone_price);
}
} }
please try to change the following things
String phone_name = jsonObject.getString("name"
String phone_price = jsonObject.getString("dddd");
Person person=new Person(phone_name,phone_price);

Categories

Resources