RecyclerView dosent show any elements following is my code - android

Fragment_bookmovie2.java
public class Fragment_bookmovie2 extends android.support.v4.app.Fragment implements View.OnClickListener {
private static final String TAG ="Fragment_bookmovie2" ;
ArrayList<String> moviename= new ArrayList<>();
ArrayList<String> movieyear= new ArrayList<>();
ArrayList<String> moviebanner= new ArrayList<>();
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
Movie_listAdapter2 adapter ;
LinearLayout progress;
RelativeLayout ll;
public Fragment_bookmovie2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Log.e(TAG,"reched on create");
// first step - retrieve object
Backendless.Persistence.of(Booking.class).find(new AsyncCallback<BackendlessCollection<Booking>>() {
#Override
public void handleResponse(BackendlessCollection<Booking> response) {
for(Booking booking : response.getData()) {
if(!moviename.contains(booking.getMovie().get(0).getMovie_Name())) {
moviename.add(booking.getMovie().get(0).getMovie_Name());
movieyear.add(booking.getMovie().get(0).getYear());
moviebanner.add("https://api.backendless.com/" + BackendSetting.APPLICATION_ID + "/" + BackendSetting.VERSION + "/files/mypics/" + booking.getMovie().get(0).getImage());
}
}
adapter.notifyDataSetChanged();
ll.removeView(progress);
}
#Override
public void handleFault(BackendlessFault fault) {
Toast.makeText(getActivity(), fault.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
moviename.add("haha");
movieyear.add("hello");
moviebanner.add("http://www.w3schools.com/css/trolltunga.jpg");
// Inflate the layout for this fragment
ll = (RelativeLayout) inflater.inflate(R.layout.fragment_bookmovie2, container, false);
progress = (LinearLayout) ll.findViewById(R.id.progress_bookingFrag);
recyclerView = (RecyclerView) ll.findViewById(R.id.recycle_movielist);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new Movie_listAdapter2(getActivity(),moviename,movieyear,moviebanner);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return ll;
}
#Override
public void onClick(View view) {
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
/*#Override
public void onButtonClickListnerProceed(Integer pos) {
Intent booking_screen_redirect = new Intent(getActivity(), BookingScreen2.class);
booking_screen_redirect.putExtra("movie_name",moviename.get(pos));
this.onPause();
startActivity(booking_screen_redirect);
getActivity().overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}*/
}
Movie_listAdapter2.java
public class Movie_listAdapter2 extends RecyclerView.Adapter<Movie_listAdapter2.Movie_cards>{
final static String TAG="Movie_listAdapter2";
Context context_external;
ArrayList<String> moviename=new ArrayList<>();
ArrayList<String> movieyear=new ArrayList<>();
ArrayList<String> banner=new ArrayList<>();
public Movie_listAdapter2(Context context,ArrayList<String> resource, ArrayList<String> resource1, ArrayList<String> resource2) {
//set the context and the format of the layout inside the list item
//i.e R.layout.movie_list_adapter
//also the resource i.e the item names in an ArrayList
this.moviename = resource;
this.movieyear = resource1;
this.banner = resource2;
this.context_external=context;
Log.e(TAG,"size = "+movieyear.size()+" "+moviename.size());
}
public static class Movie_cards extends RecyclerView.ViewHolder {
CardView cv;
TextView movie_name;
TextView movie_year;
Button proceed;
ImageView movie_banner;
public Movie_cards(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.movie_list_card);
movie_name = (TextView)itemView.findViewById(R.id.tv_card_moviename);
movie_year = (TextView)itemView.findViewById(R.id.tv_card_movieyear);
movie_banner = (ImageView)itemView.findViewById(R.id.card_moviebanner);
proceed = (Button) itemView.findViewById(R.id.b_card_proceed);
}
}
#Override
public Movie_cards onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_card, parent, false);
Movie_cards pvh = new Movie_cards(v);
return pvh;
}
public void updateData(ArrayList<String> resource, ArrayList<String> resource1, ArrayList<String> resource2) {
this.moviename = resource;
this.movieyear = resource1;
this.banner = resource2;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(final Movie_cards holder, final int position) {
holder.movie_name.setText(moviename.get(position));
holder.movie_year.setText(movieyear.get(position));
Picasso.with(context_external)
.load(banner.get(position))
.placeholder(R.drawable.placeholder)
.networkPolicy(NetworkPolicy.OFFLINE)
.error(R.drawable.placeholder)
.fit()
.into(holder.movie_banner, new Callback() {
#Override
public void onSuccess() {
//i.e image was loaded from cache
}
#Override
public void onError() {
//image was downloaded as it wasn't available in cache
Picasso.with(context_external)
.load(banner.get(position))
.placeholder(R.drawable.placeholder)
.error(R.drawable.warning)
.fit()
.into(holder.movie_banner);
}
});
holder.proceed.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent booking_screen_redirect = new Intent(context_external, BookingScreen2.class);
booking_screen_redirect.putExtra("movie_name",moviename.get(position));
context_external.startActivity(booking_screen_redirect);
//overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}
});
}
#Override
public int getItemCount() {
return 0;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
the fragment displays empty and no items appear even though i have added the data to arraylists and passed to the adapter. please help . thanks in advance

Problem is in below code you are returning 0 that's why its not showing any item
#Override
public int getItemCount() {
return 0;
}
You should return your list's size here either moviename.size(); or movieyear.size()

Related

RecyclerView isn't fixed to top when Items are added

I have this RecyclerView that doesn't want to show the item at position 0 anymore, after enough items are added to make the RecyclerView scrollable. Instead it seems to stick to the bottom item and scroll down with this one, although the other items are added at position 0.
public class hauptseite extends AppCompatActivity {
private ArrayList<ExampleItem> mExampleList;
private RecyclerView mRecyclerView;
private ExampleAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ImageButton btnInput;
private EditText editTextInput;
private int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnInput = findViewById(R.id.btn_add);
editTextInput = findViewById(R.id.name_add);
createExampleList();
buildRecyclerView();
btnInput = findViewById(R.id.btn_add);
editTextInput = findViewById(R.id.name_add);
btnInput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editTextInput.getText().toString();
insertItem(name);
}
});
}
public void insertItem(String name) {
mExampleList.add(position, new ExampleItem(name));
mAdapter.notifyItemInserted(position);
editTextInput.setText("");
}
public void removeItem(int position) {
mExampleList.remove(position);
mAdapter.notifyItemRemoved(position);
}
public void createExampleList() {
mExampleList = new ArrayList<>();
}
public void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerName);
mRecyclerView.setHasFixedSize(false);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ExampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener(){
#Override
public void onDeleteClick(int position) {
removeItem(position);
}
});
}
And the adapter
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder{
public TextView mTextView1;
public ImageView mDeleteName;
public ExampleViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
mTextView1 = itemView.findViewById(R.id.name_added);
mDeleteName = itemView.findViewById(R.id.delete_name);
mDeleteName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onDeleteClick(position);
}
}
}
});
}
}
public ExampleAdapter(ArrayList<ExampleItem> exampleList) {
mExampleList = exampleList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mTextView1.setText(currentItem.getName1());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
So what do I need change when I want my RecyclerView to stay at the item in position 0 unless I start scrolling down?
You can scroll to the desired position on the insert:
mLayoutManager.scrollToPosition(yourPosition)
there is easy way to fix that.
do not add item at position 0 ... just reverse the default order of your recyclerView
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
yourRecyclerView.setLayoutManager(linearLayoutManager);
I see two good ways of solving this:
One: Don't hold position in your activity, but use the size of the ArrayList
public void insertItem(String name) {
mExampleList.add(new ExampleItem(name));
mAdapter.notifyItemInserted(mExampleList.size() - 1);
editTextInput.setText("");
}
Two: Move the example list and its methods into your adapter. This way you can also remove the interface for deletion and let the adapter handle it all. I also added a method to retrieve the current list of items from the adapter incase you need that data outside of the adapter.
Activity:
public class hauptseite extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ExampleAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ImageButton btnInput;
private EditText editTextInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnInput = findViewById(R.id.btn_add);
editTextInput = findViewById(R.id.name_add);
buildRecyclerView();
btnInput = findViewById(R.id.btn_add);
editTextInput = findViewById(R.id.name_add);
btnInput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editTextInput.getText().toString();
mAdapter.insertItem(name);
}
});
}
public void removeItem(int position) {
mAdapter.notifyItemRemoved(position);
}
public void createExampleList() {
mExampleList = new ArrayList<>();
}
public void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerName);
mRecyclerView.setHasFixedSize(false);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ExampleAdapter();
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
And the adapter:
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
public insertItem(String name) {
mExampleList.add(name);
this.notifyItemAdded(mExampleList.size() -1)
}
public removeItem(int position) {
mExampleList.remove(position);
this.notifyItemRemoved(position);
}
public ArrayList<ExampleItems> getItems() {
return mExampleList();
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder{
public TextView mTextView1;
public ImageView mDeleteName;
public ExampleViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
mTextView1 = itemView.findViewById(R.id.name_added);
mDeleteName = itemView.findViewById(R.id.delete_name);
mDeleteName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
removeItem(position);
}
}
}
});
}
}
public ExampleAdapter() {
mExampleList = new ExampleList();
}

How to create an interface between a fragment and an adapter

I have been able to create an interface in the adapter to communicate with the fragment.
This is the adapter code
public class AgroInfoAdapter extends RecyclerView.Adapter<AgroInfoAdapter.ViewHolder> {
private Context mContext;
ArrayList<JsonObject> extensionItem = new ArrayList<>();
public Typeface tf;
public AgroInfoAdapter.AgroInfoAdapterListener listener;
public AgroInfoAdapter(Context context, ArrayList<JsonObject> extensionItem) {
this.extensionItem = extensionItem;
this.mContext = context;
this.tf = Typeface.createFromAsset(context.getAssets(), "FiraSans-Light.ttf");
}
#Override
public AgroInfoAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_crop_info, null);
AgroInfoAdapter.ViewHolder viewHolder = new AgroInfoAdapter.ViewHolder(itemLayoutView);
return viewHolder;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.header)
public TextView header;
#BindView(R.id.body)
public TextView body;
#BindView(R.id.thumbnail)
public ImageView thumbnail;
#BindView(R.id.button)
public Button button;
#BindView(R.id.downloadProgressView)
DownloadProgressView downloadProgressView;
#BindView(R.id.row)
public LinearLayout row;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
ButterKnife.bind(this, itemLayoutView);
}
}
#Override
public void onBindViewHolder(AgroInfoAdapter.ViewHolder viewHolder, final int position) {
try {
JsonObject sl = extensionItem.get(position);
viewHolder.header.setText(sl.get("title").getAsString());
if ((sl.get("title").getAsString()).equals("Land preparation")) {
viewHolder.button.setVisibility(View.VISIBLE);
}
Glide.with(mContext).load(CONFIG.IMAGE_URL+ sl.get("photo_url").getAsString())
.thumbnail(0.5f)
.apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.fallback(R.drawable.fallback)
.placeholder(R.drawable.progress_animation)
.error(R.drawable.fallback)
)
.into(viewHolder.thumbnail);
String description="";
for (JsonElement e:sl.get("description").getAsJsonArray()){
if(!e.getAsString().trim().isEmpty() && CharMatcher.javaUpperCase().or(CharMatcher.javaLetter().negate()).matchesAllOf(e.getAsString().trim())) {
SpannableString s1 = new SpannableString(e.getAsString());
s1.setSpan(new BulletSpan(20), 1, e.getAsString().length(), 0);
description +=s1 + "\n\n";
}else if(!e.getAsString().trim().isEmpty()) {
SpannableString s1 = new SpannableString(e.getAsString());
s1.setSpan(new BulletSpan(20), 1, e.getAsString().length(), 0);
description +=s1 + "\n\n";;
viewHolder.body.setText(description);
viewHolder.body.setTypeface(tf);
}
}
} catch (Exception e) {
}
applyClickEvents(viewHolder, position);
}
public interface AgroInfoAdapterListener {
void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position);
}
private void applyClickEvents(final AgroInfoAdapter.ViewHolder holder, final int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onCartRowClicked(view, holder.downloadProgressView, position);
}
});
}
#Override
public int getItemCount() {
return extensionItem.size();
}
}
This is the frgament which I was connecting to the adapter
AgroInfoAdapter adapter;
#BindView(R.id.rv)
RelativeLayout _RecyclerViewLayout;
#BindView(R.id.empty_rv)
RelativeLayout _EmptyRecyclerViewLayout;
#BindView(R.id.recycler_desc)
RecyclerView recyclerView;
Toolbar mToolbar;
#BindView(R.id.progress_bar)
ProgressBar progressBar;
#BindView(R.id.rv_layout) RelativeLayout relativeLayout;
ArrayList<JsonObject> ins = new ArrayList<>();
AgroInfoActivity.OnCropperSpinnerSelectedListener listener;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listener = new AgroInfoActivity.OnCropperSpinnerSelectedListener() {
#Override
public void onItemSelected(String pos) {
new LongOperation().execute(pos);
}
};
((AgroInfoActivity)getActivity()).addCropperSpinnerSelectedListener(listener);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_ext_land, container, false);
ButterKnife.bind(this,view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(1, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new AgroInfoAdapter(getActivity(), ins);
recyclerView.setAdapter(adapter);
return view;
}
#Override
public void onResume() {
new LongOperation().execute(((AgroInfoActivity)getActivity()).cropsSpinner.getSelectedItem().toString());
super.onResume();
}
private class LongOperation extends AsyncTask<String, Void, ArrayList<JsonObject>> {
#Override
protected ArrayList<JsonObject> doInBackground(String... params) {
try {
couchdbCropInfo = new CouchdbCropInfo(getActivity());
return couchdbCropInfo.allCropInfo(params[0],TYPE);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<JsonObject> result) {
ins.addAll(result);
adapter.notifyDataSetChanged();
if (ins.isEmpty()) {
_RecyclerViewLayout.setVisibility(View.GONE);
_EmptyRecyclerViewLayout.setVisibility(View.VISIBLE);
} else {
_RecyclerViewLayout.setVisibility(View.VISIBLE);
_EmptyRecyclerViewLayout.setVisibility(View.GONE);
}
relativeLayout.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
#Override
protected void onPreExecute() {
relativeLayout.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
ins.clear();
}
#Override
protected void onProgressUpdate(Void... values) {}
}
#Override
public void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position) {
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getActivity()
.getFragmentManager()
.beginTransaction();
Fragment fragmentB = new PostFragment();
fragmentB.setArguments(bundle);
fragmentTransaction.replace(R.id.parent, fragmentB);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
Basically what I am trying to achieve is I want to call a fragment when I click the button. The activity is a tablaout with about 5 fragments.
When I click the button. What brings about this and how best can I solve it or could have done it? Thanks in advance.
In place where you declare adapter or in the constructor of adapter, initiate the listener.
In the fragment side,
class Test extends Fragment {
AdapterClass adapter = new AdapterClass();
adapter.setListner(..)
view.setAdapter(adapter);
#Override
public void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position) {
}
}
In Adapter class
class AdapterClass {
private AgroInfoAdapterListener listner;
public setListner(AgroInfoAdapterListener listner) {
this.listner = listner;
}
public interface AgroInfoAdapterListener {
void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position);
}
private void applyClickEvents(final AgroInfoAdapter.ViewHolder holder, final int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}

How to render render JSON data using retrofit and recylerview in android studio

I am trying use retrofit and recyclerview to display from a web app. I have the following models:
Main Activities
public class ProfileActivity extends AppCompatActivity {
private SalesAdapter mAdapter;
private RecyclerView mRecyclerView;
private SaleService mService;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView(R.layout.activity_profile );
mService = ApiUtils.getSaleService();
mRecyclerView = (RecyclerView) findViewById(R.id.rvItems);
mAdapter = new SalesAdapter(this, new ArrayList<Sale>(0), new SalesAdapter.ItemListener() {
#Override
public void onPostClick(long id) {
}
});
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
loadAnswers();
}
public void loadAnswers() {
mService.getSales().enqueue(new Callback<List<Sale>>() {
#Override
public void onResponse(Call<List<Sale>> call, Response<List<Sale>> response) {
if(response.isSuccessful()) {
mAdapter.UpdateSales(response.body());
} else {
int statuscode = response.code();
}
}
#Override
public void onFailure(Call<List<Sale>> call, Throwable t) {
}
});
}
}
Recyclerview Adapter
public class SalesAdapter extends RecyclerView.Adapter<SalesAdapter.ViewHolder>{
private Context mContext;
private List<Sale> mSales;
private ItemListener mItemListener;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView tvLocaleName;
ItemListener mItemListener;
public ViewHolder(View itemView, ItemListener itemListener) {
super(itemView);
tvLocaleName = (TextView) itemView.findViewById(android.R.id.text1);
this.mItemListener = itemListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Sale sale = getSales(getAdapterPosition());
this.mItemListener.onPostClick(sale.getId());
notifyDataSetChanged();
}
}
public SalesAdapter(Context mContext, List<Sale> mSales, ItemListener mItemListener) {
this.mContext = mContext;
this.mSales = mSales;
this.mItemListener = mItemListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
return new ViewHolder(view, this.mItemListener);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Sale sale = mSales.get(position);
TextView textView = holder.tvLocaleName;
textView.setText(sale.getLocaleName());
}
#Override
public int getItemCount() {
return mSales.size();
}
public void UpdateSales(List<Sale> sales) {
mSales = sales;
}
private Sale getSales(int position) {
return mSales.get(position);
}
public interface ItemListener {
void onPostClick(long id);
}
}
from the image you can see that i am able to get back the data, but how do I display in it the recyclerview? where am i going wrong with code?
Add a notifyDataSetChanged() call to your adapter after you refresh the list.
Your method should look like:
public void UpdateSales(List<Sale> sales) {
mSales = sales;
notifyDataSetChanged();
}
Check out this link to learn more about this method.

Calling setAdapter on Fragment (Recycler View) not working

I tried to set the adapter on fragment, but nothing shows up.
The object retrieves the data from API but doesn't show on the screen.
I have already put the break point on rvItem.setAdapter(mainAdapter); but nothings happen, the debug passes straight through.
public class ItemFragment extends Fragment {
private MainAdapter mainAdapter;
private ItemPresenter itemPresenter;
private GridLayoutManager mLayoutManager;
private List<ObjectAdapter> list = new ArrayList<>();
private String region = "br";
#Bind(R.id.rvItem)
RecyclerView rvItem;
public ItemFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_item, container, false);
ButterKnife.bind(this, view);
itemPresenter = new ItemPresenter();
mLayoutManager = new GridLayoutManager(getActivity(), 4);
rvItem.setLayoutManager(mLayoutManager);
getList();
return view;
}
private void getList() {
itemPresenter.loadItemList(region, "all", AppConfigs.api_key, new ItemListListener() {
#Override
public void onRequestStarted() {
}
#Override
public void onRequestFinished() {
}
#Override
public void onError(Throwable error) {
}
#Override
public void onItemListLoad(List<ItemDto> itemList) {
displayItemList(ObjectAdapter.convertItemToObjetct(itemList));
}
});
}
public void displayItemList(List<ObjectAdapter> itemList) {
list = itemList;
mainAdapter = new MainAdapter(getActivity(), list, new MainAdapter.OnObjectClickListener() {
#Override
public void OnObjectClickListener(ObjectAdapter objectAdapter) {
Toast.makeText(getActivity(), "Object Adapter" + objectAdapter.Id, Toast.LENGTH_SHORT).show();
}
});
rvItem.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged();
}
}
Adapter:
public class MainAdapter extends
RecyclerView.Adapter<MainAdapter.MainAdapterViewHolder> {
public List<ObjectAdapter> mObjecterList;
private final OnObjectClickListener listener;
private Context mContext;
public interface OnObjectClickListener {
void OnObjectClickListener(ObjectAdapter objectAdapter);
}
public MainAdapter(Context context, List<ObjectAdapter> objectAdapterList, OnObjectClickListener listener) {
this.mObjecterList = objectAdapterList;
this.listener = listener;
this.mContext = context;
}
#Override
public MainAdapter.MainAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main_adapter, parent, false);
return new MainAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(MainAdapter.MainAdapterViewHolder holder, int position) {
ObjectAdapter ob = mObjecterList.get(position);
holder.tvNameText.setText(ob.Name);
holder.bind(mObjecterList.get(position), listener);
String url = "";
switch (ob.Type){
case CHAMPION: url = String.format(AppConfigs.portraitChampion, ob.Portrait);
break;
case SPELL: url = String.format(AppConfigs.portraitSpell, ob.Portrait);
break;
case ITEM: url = String.format(AppConfigs.portraitItem, ob.Portrait);
break;
}
Picasso.with(mContext).load(url).into(holder.ivRetrato);
}
#Override
public int getItemCount() {
return this.mObjecterList.size();
}
public static class MainAdapterViewHolder extends RecyclerView.ViewHolder {
public TextView tvNameText;
public ImageView ivRetrato;
public MainAdapterViewHolder(View itemView) {
super(itemView);
this.tvNameText = (TextView) itemView.findViewById(R.id.tvNameText);
this.ivRetrato = (ImageView) itemView.findViewById(R.id.ivImagePortrait);
}
public void bind(final ObjectAdapter objectAdapterListItem, final OnObjectClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.OnObjectClickListener(objectAdapterListItem);
}
});
}
}
}
You need to set adapter directly at onCreateView method and call notifyDataSetChanged() of adapter when data loaded

OnClick action gives error in recycler grid layout

This is My MainActivity Code.In this we get error in setOnItemClickListener as null pointer exception and it stops my app.give me some suggestions where am i wrong. I am trying to achieve custom grid with image on top and title next to it.
public class MainActivity extends AppCompatActivity {
//RecyclerView recyclerView;
private static final String TAG = "MainActivity";
private final String android_version_names[] = {
"Donut",
"Eclair",
"Froyo",
"Gingerbread",
"Honeycomb",
"Ice Cream Sandwich",
"Jelly Bean",
"KitKat",
"Lollipop",
"Marshmallow"
};
private final String android_image_urls[] = {
"https://api.learn2crack.com/android/images/donut.png",
"https://api.learn2crack.com/android/images/eclair.png",
"https://api.learn2crack.com/android/images/froyo.png",
"https://api.learn2crack.com/android/images/ginger.png",
"https://api.learn2crack.com/android/images/honey.png",
"https://api.learn2crack.com/android/images/icecream.png",
"https://api.learn2crack.com/android/images/jellybean.png",
"https://api.learn2crack.com/android/images/kitkat.png",
"https://api.learn2crack.com/android/images/lollipop.png",
"https://api.learn2crack.com/android/images/marshmallow.png"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
recyclerView.setLayoutManager(layoutManager);
ArrayList<AndroidVersion> androidVersions = prepareData();
DataAdapter adapter = new DataAdapter(getApplicationContext(),androidVersions);
recyclerView.setAdapter(adapter);
DataAdapter mAdapter = null ;
mAdapter.setOnItemClickListener(new DataAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.d(TAG, "onItemClick position: " + position);
}
});
}
private ArrayList<AndroidVersion> prepareData(){
ArrayList<AndroidVersion> android_version = new ArrayList<>();
for(int i=0;i<android_version_names.length;i++){
AndroidVersion androidVersion = new AndroidVersion();
androidVersion.setAndroid_version_name(android_version_names[i]);
androidVersion.setAndroid_image_url(android_image_urls[i]);
android_version.add(androidVersion);
}
return android_version;
}
}
This Is My Adapter Code.
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<AndroidVersion> android;
private Context context;
private static ClickListener clickListener;
public DataAdapter(Context context,ArrayList<AndroidVersion> android) {
this.android = android;
this.context = context;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
viewHolder.tv_android.setText(android.get(i).getAndroid_version_name());
Picasso.with(context).load(android.get(i).getAndroid_image_url()).resize(240, 120).into(viewHolder.img_android);
}
#Override
public int getItemCount() {
return android.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView tv_android;
private ImageView img_android;
public ViewHolder(View view) {
super(view);
view.setOnClickListener(this);
tv_android = (TextView)view.findViewById(R.id.tv_android);
img_android = (ImageView) view.findViewById(R.id.img_android);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(ClickListener clickListener) {
DataAdapter.clickListener = clickListener;
}
public interface ClickListener {
void onItemClick(int position, View v);
}
}
you are setting mAdapter = null before setting setOnItemClickListener, remove it
DataAdapter mAdapter = null ; //remove this line
adapter.setOnItemClickListener(new DataAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.d(TAG, "onItemClick position: " + position);
}
});
you are calling wrong adapter, your actual variable is adapter and you are calling it with mAdapter, that also by setting its value to ull
Try this
DataAdapter adapter = new DataAdapter(getApplicationContext(),androidVersions);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new DataAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.d(TAG, "onItemClick position: " + position);
}
});

Categories

Resources