How to create an interface between a fragment and an adapter - android

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

Related

how to remove all items from RecyclerView on toolbar icon delete in android

Hello friend a lot of search but not working plz help me.
my probem is delete all history from adaptor using on toolbar delete icon how to remove adaptor data
below code first show adaptor and mainactivity
public void removehistory(View view)
button click to remove items from adaptor how to solve this problem sorry for bad english and advance thanks
HistoryAdaptor
public class HistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Object> data;
private GenCallback<HistoryModel> clickListener;
private static final int NATIVE_AD = 1;
private static final int HISTORY_ITEM = 2;
private LayoutInflater inflater;
// private Button removedata;
public HistoryAdapter() {
this.data = new ArrayList<>();
inflater = (LayoutInflater) App.getInstance().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case NATIVE_AD:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ad_unified, null, false);
return new NativeAdHolder(view);
case HISTORY_ITEM:
default:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false);
return new ViewHolder(view);
}
// return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false));
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case NATIVE_AD:
((NativeAdHolder) holder).bind((UnifiedNativeAd) data.get(position));
break;
case HISTORY_ITEM:
default:
((ViewHolder) holder).bind((HistoryModel) data.get(position));
break;
}
}
#Override
public int getItemViewType(int position) {
if (data.get(position) instanceof UnifiedNativeAd) {
return NATIVE_AD;
} else {
return HISTORY_ITEM;
}
}
#Override
public int getItemCount() {
return data.size();
}
public void addItem(Object obj, int pos) {
this.data.add(pos, obj);
notifyItemInserted(pos);
}
public void updateData(ArrayList<HistoryModel> list) {
this.data.clear();
this.data.addAll(list);
notifyDataSetChanged();
}
public void clear() {
if (this.data != null && this.data.size() != 0) {
this.data.clear();
notifyDataSetChanged();
}
}
public void setClickListener(GenCallback<HistoryModel> clickListener) {
this.clickListener = clickListener;
}
public void showStarredOnly() {
/*Iterator<Object> iterator = data.iterator();
int pos = 0;
while (iterator.hasNext()) {
if (iterator.next() instanceof HistoryModel) {
HistoryModel historyModel = (HistoryModel) iterator.next();
if (!historyModel.isStarred()) {
iterator.remove();
// notifyItemRemoved(pos);
}
}
pos++;
}
notifyDataSetChanged();*/
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.tvFromLang)
TextView tvFromLang;
#BindView(R.id.tvFromText)
TextView tvFromText;
#BindView(R.id.tvToLang)
TextView tvToLang;
#BindView(R.id.tvToText)
TextView tvToText;
#BindView(R.id.ivStar)
ImageView ivStar;
#BindView(R.id.llMain)
CardView llMain;
#BindView(R.id.tvDate)
TextView tvDate;
public ViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
llMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clickListener != null) {
clickListener.onCallback((HistoryModel) data.get(getAdapterPosition()));
}
}
});
llMain.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int pos = getAdapterPosition();
HistoryModel historyModel = (HistoryModel) data.get(pos);
boolean isStar = historyModel.isStarred();
String from = historyModel.getFromLang();
String to = historyModel.getToLang();
Dialogs.INSTANCE.showActionsDialog(llMain.getContext(), isStar, from, to, new HistoryActionCallback() {
#Override
public void onClickCopyFrom() {
Utils.copyText(historyModel.getFromText());
Logger.logFabric(Constants.Events.COPY_FROM);
}
#Override
public void onClickCopyTo() {
Utils.copyText(historyModel.getToText());
Logger.logFabric(Constants.Events.COPY_TO);
}
#Override
public void onClickStar() {
Logger.logFabric(Constants.Events.MARKED_AS_FAV);
historyModel.setStarred(!isStar);
notifyItemChanged(pos);
RoomRepository.getNew().updateHistoryItem(historyModel);
// notifyDataSetChanged();
}
#Override
public void onClickDelete() {
String message = "Are you sure you want to delete?";
Dialogs.INSTANCE.showConfirmationDialog(view.getContext(), message, new View.OnClickListener() {
#Override
public void onClick(View view) {
RoomRepository.getNew().deleteHistoryRecord(historyModel.getTimeStamp());
data.remove(pos);
notifyItemRemoved(pos);
Dialogs.INSTANCE.dismissDialog();
Logger.logFabric(Constants.Events.ITEM_DELETED);
}
});
}
});
return false;
}
});
}
public void bind(HistoryModel item) {
StringBuilder builder = new StringBuilder();
builder.append(item.getFromLang()).append("(").append(item.getFromCode()).append(")");
tvFromLang.setText(builder);
tvFromText.setText(item.getFromText());
builder.setLength(0);
builder.append(item.getToLang()).append("(").append(item.getToCode()).append(")");
tvToLang.setText(builder);
tvToText.setText(item.getToText());
String date = Utils.formatDate(item.getTimeStamp(), "EEE, MMM d, yyyy");
tvDate.setText(date);
ivStar.setVisibility(item.isStarred() ? View.VISIBLE : View.GONE);
}
MainActivity
public class HistoryActivity extends AppCompatActivity {
private HistoryAdapter mAdapter;
private ArrayList<Object> data;
private Activity mCurrentActivity;
private RecyclerView rvHistory;
private Button clearh;
private GenCallback<HistoryModel> clickListener;
private ArrayList<HistoryModel> datamodel = new ArrayList<>();
private ArrayList<String> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
rvHistory = findViewById(R.id.rvHistory);
ImageView imgb = findViewById(R.id.imgback);
initAdapter();
getAdapter();
imgb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HistoryActivity.super.onBackPressed();
}
});
}
private void getAdapter() {
RoomRepository.getNew().getAllHistory(mCallback);
}
private void initAdapter() {
mAdapter = new HistoryAdapter();
LinearLayoutManager layoutManager = new LinearLayoutManager(mCurrentActivity);
rvHistory.setLayoutManager(layoutManager);
rvHistory.setAdapter(mAdapter);
}
private IRoomDataHandler mCallback = new RoomDataHandler() {
#Override
public void onGetAllHistory(ArrayList<HistoryModel> list) {
// if (isSafe()) {
mAdapter.updateData(list);
// showLoader(false);
// checkForNoData();
// if (AdUtils.getInstance().getNativeAd() != null) {
//
// }
}
#Override
public void onError(String error) {
// showLoader(false);
// checkForNoData();
}
};
public void removehistory(View view) {
//problem is here
mAdapter.notifyItemRemoved(i);
}
}
call clear() method from on click oh that button like this.
public void removehistory(View view) {
//problem is here
mAdapter.clear()
}

Onclick listner not triggering in fragment page adapter

I'm trying to display all contacts from phone to recyclerView when a user presses any item it should do some work. I have a list of contacts in a fragment which is inside a fragment page adapter when ever I click in the recyclerView item onClicklistener is not executing
I have used same code in a previous app but onclicklisteners are triggering
public class ListOfContacts extends Fragment implements OnContactListener {
private static final String TAG = "ListOfContacts";
ArrayList<ContactModel> arrayList = new ArrayList<>();
RecyclerView mRecyclerview;
ListOfContactsRAdapter listOfContactsRAdapter;
Cursor cursor;
public static ListOfContacts getInstance(ArrayList<ContactModel> arrayList) {
ListOfContacts listOfContacts = new ListOfContacts();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("listofcontacts", arrayList);
listOfContacts.setArguments(bundle);
return listOfContacts;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_of_contacts, container, false);
mRecyclerview = view.findViewById(R.id.loc_r_view);
listOfContactsRAdapter = new ListOfContactsRAdapter(getActivity(), this, arrayList);
mRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerview.setAdapter(listOfContactsRAdapter);
mRecyclerview.addItemDecoration(new DividerItemDecoration(mRecyclerview.getContext(), DividerItemDecoration.VERTICAL));
mRecyclerview.setHasFixedSize(true);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
arrayList.addAll(Objects.requireNonNull(getArguments().<ContactModel>getParcelableArrayList("listofcontacts")));
Log.d(TAG, "contact recived " + arrayList.get(0).getContactName());
} else {
if (getArguments().getStringArrayList("listofcontacts") != null)
arrayList.addAll(getArguments().<ContactModel>getParcelableArrayList("listofcontacts"));
}
}
}
#Override
public void onDueListener(int position) {
Log.d(TAG, "onDueListener: ");
ContactModel contactModel = new ContactModel();
contactModel.setContactName(arrayList.get(position).getContactName());
contactModel.setContactNumberp(arrayList.get(position).getContactNumberp());
contactModel.setState(true);
Intent intent = new Intent(getActivity(), AddDue.class);
intent.putExtra("userDetails", contactModel);
startActivity(intent);
}
}
public ListOfContactsRAdapter(Context context, OnContactListener a, ArrayList<ContactModel> arrayList) {
Log.d(TAG, "ListOfContactsRAdapter: +" + arrayList.size());
ContactListener = a;
this.arrayList = new ArrayList<>();
if (arrayList != null)
this.arrayList.addAll(arrayList);
mContext = context;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.loc_r_container, viewGroup, false);
customViewHolder = new CustomViewHolder(view, ContactListener);
return customViewHolder;
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder customViewHolder, int i) {
customViewHolder.contactName.setText(arrayList.get(i).getContactName());
customViewHolder.contactNumber.setText(arrayList.get(i).getContactNumberp());
customViewHolder.contactDp.setText(String.valueOf(arrayList.get(i).getContactName().charAt(0)));
}
#Override
public int getItemCount() {
Log.d(TAG, "getItemCount: ");
return arrayList.size();
}
static class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
OnContactListener Listener;
TextView contactName;
TextView contactNumber;
TextView contactDp;
Button button;
LinearLayout linearLayout;
CustomViewHolder(#NonNull View itemView, OnContactListener mOnContactListener) {
super(itemView);
contactName = itemView.findViewById(R.id.contact_name);
contactNumber = itemView.findViewById(R.id.contact_number);
button = itemView.findViewById(R.id.action);
contactDp = itemView.findViewById(R.id.contactDp);
linearLayout = itemView.findViewById(R.id.container);
linearLayout.setOnClickListener(this);
Listener = mOnContactListener;
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: ");
Listener.onDueListener(getAdapterPosition());
}
}
}
What i did is create an Interface in your RecyclerView Adapter:
public interface OnClickItem { // create an interface
void onClickItem(int position); // create callback function
}
Then in OnBindViewHolder:
customViewHolder.(yourView).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ContactListener.onClickItem(customViewHolder.getAdapterPosition());
}
});
In your Fragment:
public class ListOfContacts extends Fragment implements ListOfContactsRAdapter.OnClickItem { ...
Implement the method:
#Override
public void onClickItem(int position) {
...
}

Android: How do I make a single retrofit call in which it will display on different tabs , tablayout?

I'm creating an android app in which I will display photos in the tab layout. The requirement should only be 20 photos in each tab. How do I display the photos on the tab? I'm using viewpager and on my current code. Btw, this is the site that I used for my data: https://jsonplaceholder.typicode.com/photos
Thanks!
Adapter:
public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.MyViewHolder> {
private Context mContext;
List<Photos> photosList = new ArrayList<>();
public PhotoAdapter(Context mContext, List<Photos> photosList){
this.photosList = photosList;
this.mContext = mContext;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.photo_card, viewGroup, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder myViewHolder, int i) {
Photos photos = photosList.get(i);
Log.i("Position: ", i+1 + " Id: " + photos.getId());
myViewHolder.mTitleTextView.setText(photos.getTitle());
myViewHolder.mIdTextView.setText(photos.getId());
String thumbnail = photos.getUrl();
Glide.with(mContext)
.load(thumbnail)
.into(myViewHolder.mUrlImageView);
}
#Override
public int getItemCount() {
//return photosList.size();
return 20;
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView mTitleTextView, mIdTextView;
ImageView mUrlImageView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
mTitleTextView = (TextView) itemView.findViewById(R.id.titleTextView);
mIdTextView = (TextView) itemView.findViewById(R.id.idTextView);
mUrlImageView = (ImageView) itemView.findViewById(R.id.photoImageView);
}
}
Fragment: (Dynamic)
public class DyanamicFragment extends Fragment {
private RecyclerView mRecyclerView;
public List<Photos> photos = new ArrayList<>();
public static DyanamicFragment newInstance(){
return new DyanamicFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dynamic_fragment_layout, container, false);
initViews(view);
mRecyclerView = (RecyclerView) view.findViewById(R.id.PhotosRecyclerView);
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),4));
return view;
}
private void initViews(View view) {
TextView textView = view.findViewById(R.id.commonTextView);
textView.setText(String.valueOf("Category: " +getArguments().getInt("position")));
loadJSON();
}
private void loadJSON(){
Service serviceAPI = Client.getClient();
Call<JsonArray> loadPhotosCall = serviceAPI.readPhotosArray();
loadPhotosCall.enqueue(new Callback<JsonArray>() {
#Override
public void onResponse(Call<JsonArray> call, Response<JsonArray> response) {
try {
String photosString = response.body().toString();
Type listType = new TypeToken<List<Photos>>() {}.getType();
photos = getPhotosListFromJson(photosString, listType);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(new PhotoAdapter(getContext(), photos));
}catch (Exception e){
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Call<JsonArray> call, Throwable t) {
}
});
}
public static <T> List<T> getPhotosListFromJson(String jsonString, Type type){
if (!isValid(jsonString)){
return null;
}
return new Gson().fromJson(jsonString, type);
}
public static boolean isValid(String json){
try {
new JsonParser().parse(json);
return true;
}catch (JsonSyntaxException jse){
return false;
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Activity:
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private TabLayout mTabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
viewPager = findViewById(R.id.viewpager);
mTabLayout = findViewById(R.id.tabs);
viewPager.setOffscreenPageLimit(5);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mTabLayout.setOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
setDynamicFragmentToTabLayout();
}
private void setDynamicFragmentToTabLayout() {
for (int i = 1; i < 6; i++) {
if (i == 1){
mTabLayout.addTab(mTabLayout.newTab().setText("Photos: 1-20"));
}
if (i == 2){
mTabLayout.addTab(mTabLayout.newTab().setText("Photos: 21-40"));
}
if (i == 3){
mTabLayout.addTab(mTabLayout.newTab().setText("Photos: 41-60"));
}
if (i == 4){
mTabLayout.addTab(mTabLayout.newTab().setText("Photos: 61-80"));
}
if (i == 5){
mTabLayout.addTab(mTabLayout.newTab().setText("Photos: 81-100"));
}
}
DynamicFragmentAdapter mDynamicFragmentAdapter = new DynamicFragmentAdapter(getSupportFragmentManager(), mTabLayout.getTabCount());
viewPager.setAdapter(mDynamicFragmentAdapter);
viewPager.setCurrentItem(0);
}
}
You need to make the api call in the fragment or activity that has the view pager.
Then you can parse the response and set the required image data for each fragment when adding it to the view pager.
The fragments can then display the data that has been set to its list.

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

RecyclerView dosent show any elements following is my code

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

Categories

Resources