fetch images using picasso in adapter from fragment - android

I have a recycleview which fetches data from api with a custom adapter containing a textview and imageview and I implemented this in Activity and it works fine, but now I tried to use fragment instead of activity and every thing works fine except for the images that are not displayed after moving the code to fragment so this is my fragment:
public class TVFragment extends Fragment implements TVAdapter.TVAdapterOnClickHandler {
TVAdapter mAdapter;
RecyclerView mSportsList;
String sortsports="sports.php";
Context mContext ;
public static TVFragment newInstance() {
TVFragment fragment = new TVFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tv, container, false);
mSportsList = (RecyclerView) view.findViewById(R.id.rv_sports);
mContext = getActivity();
GridLayoutManager LayoutManagerSports = new GridLayoutManager(getActivity(), 3);
mSportsList.setLayoutManager(LayoutManagerSports);
mSportsList.setHasFixedSize(true);
mAdapter = new TVAdapter(this, mContext);
mSportsList.setAdapter(mAdapter);
loadTVData(sortsports);
return view;
}
private void loadTVData(String sortChannels) {
showTVDataView();
new FetchTVTask().execute(sortChannels);
}
#Override
public void onClick(TVItem channel) {
Context context = getActivity().getApplicationContext();
Class destinationClass = TVChannel.class;
Intent intentToStartDetailActivity = new Intent(context, destinationClass);
intentToStartDetailActivity.putExtra("TVChannel", channel);
startActivity(intentToStartDetailActivity);
}
private void showTVDataView() {
mSportsList.setVisibility(View.VISIBLE);
}
public class FetchTVTask extends AsyncTask<String, Void, ArrayList<TVItem>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<TVItem> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
String sortChannels = params[0];
URL channelRequestUrl = NetworkTV.buildUrl(sortChannels);
try {
String jsonTVResponse = NetworkTV.getResponseFromHttpUrl(channelRequestUrl);
ArrayList<TVItem> simpleJsonTVData = JsonTV.getSimpleTVStringsFromJson(getContext(), jsonTVResponse);
return simpleJsonTVData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(ArrayList<TVItem> TVData) {
if (TVData != null) {
showTVDataView();
mAdapter.setTVData(TVData);
} else {
}
}
}
}
then this is my adapter:
public class TVAdapter extends RecyclerView.Adapter<TVAdapter.RecyclerViewHolder> {
ArrayList<TVItem> mChannelItems;
private Context mContext;
private final TVAdapter.TVAdapterOnClickHandler mClickHandler;
public interface TVAdapterOnClickHandler {
void onClick(TVItem channel);
}
public TVAdapter(TVAdapterOnClickHandler clickHandler, Context context) {
this.mContext = context;
mClickHandler = clickHandler;
}
class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final TextView Cat;
public final ImageView Image;
public RecyclerViewHolder(View view) {
super(view);
Cat = (TextView)itemView.findViewById(R.id.channel_cat);
Image = (ImageView) itemView.findViewById(R.id.channel_image);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
TVItem channel = mChannelItems.get(adapterPosition);
mClickHandler.onClick(channel);
}
}
#Override
public TVAdapter.RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
mContext = viewGroup.getContext();
int layoutIdForListItem = R.layout.tv_list_item;
LayoutInflater inflater = LayoutInflater.from(mContext);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
return new TVAdapter.RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(TVAdapter.RecyclerViewHolder holder, int position) {
Picasso.with(mContext).load(mChannelItems.get(position).getFullImagePath()).resize(500,500).placeholder(R.drawable.placeholder).error(R.drawable.placeholder).into(holder.Image);
holder.Cat.setText(String.valueOf(mChannelItems.get(position).getTitle()));
}
#Override
public int getItemCount() {
if (null == mChannelItems)
return 0;
else {
return mChannelItems.size();
}
}
public void setTVData(ArrayList<TVItem> TVData) {
mChannelItems = TVData;
notifyDataSetChanged();
}
}
you can see these lines:
Picasso.with(mContext).load(mChannelItems.get(position).getFullImagePath()).resize(500,500).placeholder(R.drawable.placeholder).error(R.drawable.placeholder).into(holder.Image);
and:
holder.Cat.setText(String.valueOf(mChannelItems.get(position).getTitle()));
the cat still displayed well in textview but the images with picasso library not displayed anymore and I read a lot of solutions like pass the context from fragment to adapter but nothing work!
this is the debugging images:

viewgroup.getContext() Isn't the context needed, but the context from the fragment or an activity.
#Override
public TVAdapter.RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
//mContext = viewGroup.getContext(); This should fix it. You already init mContext in the constructor.
int layoutIdForListItem = R.layout.tv_list_item;
LayoutInflater inflater = LayoutInflater.from(mContext);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
return new TVAdapter.RecyclerViewHolder(view);
}

Why are you assigning value to mContext twice? Try removing mContext = viewGroup.getContext(); from code.

Related

I don't know how to import MensWearResponse I get an error?

MensWearResponse could not be imported. I tried the api and only the fragment is showing many errors. I am a news developer. If you know, I need to fix this error. I have given the image below. Picasso.with(context).load(imageUrlFromServer+mensWear.getFirst_wear()).into(imageView); These include errors
public class Phones extends Fragment {
private GridView gridView;
private List<Category> mensWears;
private GalleryAdapter adapter;
public Phones() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phones,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view,savedInstanceState);
gridView = view.findViewById(R.id.gridHolder);
gridView = view.findViewById(R.id.gridHolder);
Call<MensWearResponse> wearResponseCall =
Service.getInstance().getApi().getAllMensWears();
wearResponseCall.enqueue(new Callback<MensWearResponse>() {
#Override
public void onResponse(Call<MensWearResponse> call,Response<MensWearResponse> response) {
mensWears = response.body().getMensWears();
for (MensWear mwr : mensWears){
Log.d("Name", mwr.getFirst_wear());
}
adapter = new Category(getActivity(), mensWears);
gridView.setAdapter(adapter);
}
#Override
public void onFailure(Call<MensWearResponse> call,Throwable t) {
}
});
}
}
adapter
public class GalleryAdapter extends BaseAdapter {
private Context context;
private List<Category> mensWears;
public String imageUrlFromServer = "http:/10.0.2.2:5757/api/public/images/";
public GalleryAdapter(Context context, List<Category> mensWears) {
this.context = context;
this.mensWears = mensWears;
}
#Override
public int getCount() {
return mensWears.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i,View view,ViewGroup viewGroup) {
final Category mensWear = mensWears.get(i);
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.custom_gallery_layout, null);
}
//For text
TextView prdId = view.findViewById(R.id.);
prdId.setText(prdId.toString());
//For images
final ImageView imageView = view.findViewById(R.id.name);
if(!TextUtils.isEmpty(mensWear.getItemName())){
Picasso.with(context).load(imageUrlFromServer+mensWear.getFirst_wear())
.into(imageView);
}
return view;
}
}

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

How to open a new fragment when click on the CardView + RecyclerView

In my app I have 15 cardview's ,Now I want to show a fragment when I clicked the cardview's for that I have 15 fragments.
RecyclerViewAdapter.java
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyViewHolder> {
private Context mContext;
private List<reminder> mData;
public RecyclerviewAdapter(Context mContext, List<reminder> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.cardview, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mTextView.setText(mData.get(position).getmTitle());
holder.mImageView.setImageResource(mData.get(position).getmImages());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.mReminder_Text_Id);
mImageView = (ImageView) itemView.findViewById(R.id.mReminder_Image_Id);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (getAdapterPosition()) {
case 0 :
// "What Should I do here"
}
}
});
}
}
}
Reminders.java
public class Reminders extends Fragment {
private OnFragmentInteractionListener mListener;
List<reminder> lstreminder;
public Reminders() {
}
public static Reminders newInstance(String param1, String param2) {
Reminders fragment = new Reminders();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_reminders, container, false);
lstreminder = new ArrayList<>();
lstreminder.add(new reminder("Alarm",R.drawable.alarms));
lstreminder.add(new reminder("Birthday",R.drawable.birthdays));
lstreminder.add(new reminder("Anniversary",R.drawable.anniversaries));
lstreminder.add(new reminder("Buy Gifts",R.drawable.buygift));
lstreminder.add(new reminder("Bill Payments",R.drawable.billpayments));
lstreminder.add(new reminder("Call / SMS",R.drawable.call));
lstreminder.add(new reminder("Recharges",R.drawable.recharges));
lstreminder.add(new reminder("Meetings",R.drawable.meetings));
lstreminder.add(new reminder("Insurance",R.drawable.insurances));
lstreminder.add(new reminder("Exams",R.drawable.exams));
lstreminder.add(new reminder("Holidays",R.drawable.holidays));
lstreminder.add(new reminder("Medical",R.drawable.medical));
lstreminder.add(new reminder("Purchase",R.drawable.purchase));
lstreminder.add(new reminder("Travel",R.drawable.travel));
lstreminder.add(new reminder("Shows",R.drawable.shows));
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.mRecyclerView_id);
RecyclerviewAdapter recyclerviewAdapter = new RecyclerviewAdapter(getActivity(),lstreminder);
recyclerviewAdapter.setOnItemClickListner(new RecyclerviewAdapter.onItemClickListner() {
#Override
public void onClick(reminder str) {
}
});
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setAdapter(recyclerviewAdapter);
return rootView;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Image
here in switch case I want to open new fragments based on the adapter's position.
Is it possible please guide me to solve ,Or if I am in wrong path please guide me ...
make interface in recycler view adapter like below code..
onItemClickListner onItemClickListner;
public void setOnItemClickListner(RecyclerViewAdpater.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(String str);//pass your object types.
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
// below code handle click event on recycler view item.
String data=mStringList.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListner.onClick(data);
}
});
}
Your Code ..
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyViewHolder> {
private Context mContext;
private List<reminder> mData;
onItemClickListner onItemClickListner;
public void setOnItemClickListner(onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(reminder str);//pass your object types.
}
public RecyclerviewAdapter(Context mContext, List<reminder> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.cardview, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
reminder data=mData.get(position);
holder.mTextView.setText(mData.get(position).getmTitle());
holder.mImageView.setImageResource(mData.get(position).getmImages());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListner.onClick(data);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.mReminder_Text_Id);
mImageView = (ImageView) itemView.findViewById(R.id.mReminder_Image_Id);
}
}
}
then after define adapter value and bind into recycler view call below code.. in activity when bind adapter into recycler view.
recyclerViewAdpater.setOnItemClickListner(new RecyclerViewAdpater.onItemClickListner() {
#Override
public void onClick(String str) {
// here call your fragment
}
});
your code for fragment..
public class Reminders extends Fragment {
private OnFragmentInteractionListener mListener;
List<reminder> lstreminder;
public Reminders() {
}
public static Reminders newInstance(String param1, String param2) {
Reminders fragment = new Reminders();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_reminders, container, false);
lstreminder = new ArrayList<>();
lstreminder.add(new reminder("Alarm",R.drawable.alarms));
lstreminder.add(new reminder("Birthday",R.drawable.birthdays));
lstreminder.add(new reminder("Anniversary",R.drawable.anniversaries));
lstreminder.add(new reminder("Buy Gifts",R.drawable.buygift));
lstreminder.add(new reminder("Bill Payments",R.drawable.billpayments));
lstreminder.add(new reminder("Call / SMS",R.drawable.call));
lstreminder.add(new reminder("Recharges",R.drawable.recharges));
lstreminder.add(new reminder("Meetings",R.drawable.meetings));
lstreminder.add(new reminder("Insurance",R.drawable.insurances));
lstreminder.add(new reminder("Exams",R.drawable.exams));
lstreminder.add(new reminder("Holidays",R.drawable.holidays));
lstreminder.add(new reminder("Medical",R.drawable.medical));
lstreminder.add(new reminder("Purchase",R.drawable.purchase));
lstreminder.add(new reminder("Travel",R.drawable.travel));
lstreminder.add(new reminder("Shows",R.drawable.shows));
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.mRecyclerView_id);
RecyclerviewAdapter recyclerviewAdapter = new RecyclerviewAdapter(getActivity(),lstreminder);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setAdapter(recyclerviewAdapter);
recyclerviewAdapter.setOnItemClickListner(new RecyclerviewAdapter.onItemClickListner() {
#Override
public void onClick(reminder str) {
// here str is click item value in recyclerview.
// here perform your operation . str is give object reminder pojo class of selected item on recyclerview.
// below code you can make condition and check any value.
if(str.getItemName().equals("xyz")){
Fragment fragment = new MainFragment();// here give your fragment.
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
else if(str.getItemName().equals("ayx")){
Fragment fragment = new HomeFragment();// here give your fragment.
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
recyclerviewAdapter.notifyDataSetChanged();
}
});
return rootView;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Try like this:
public class NewAdapter extends RecyclerView.Adapter<NewAdapter.MyViewHolder> {
Context context;
LayoutInflater inflater;
Activity activity;
View view;
RecyclerView recyclerViewNew;
private ArrayList<reminder> mData;
public NewAdapter(RecyclerView recyclerView, Context context, ArrayList<reminder>
mData, Activity activity) {
this.context = context;
this.mData = mData;
this.activity = activity;
inflater = LayoutInflater.from(this.context);
this.recyclerViewNew = recyclerView;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_cases_fragment, parent, false);
MyViewHolder sectionViewHolder = new MyViewHolder(view);
return sectionViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final int pos = position;
holder.mTextView.setText(mData.get(position).getmTitle());
holder.mImageView.setImageResource(mData.get(position).getmImages());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = view.getContext();
Intent intent = new Intent();
switch (pos) {
case 0:
AppCompatActivity activity = (AppCompatActivity) view.getContext();
Fragment myFragment = new MyFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();
break;
}
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
ImageView mImageView;
CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.mReminder_Text_Id);
mImageView = (ImageView) itemView.findViewById(R.id.mReminder_Image_Id);
cardView = (CardView) itemView.findViewById(R.id.cardView);
}
}
}
Hope this helps you.

RecyclerView not showing anything after updating Adapter data

guys i need help with this matter i have been going through my code for a couple of days to figure whats going wrong but i couldn't figure it out.
I have a fragment with a RecyclerView i initialize the Adapter data with an image place holder and some default text and the fragment shows them as expected then using a loader i fetch data from the internet and parse and pass the new data to the Adapter (all of this happens as required) until the data reaches the Adapter then Taaadaaaa the initial data disappears and the new data is not showing actually the fragment shows a blank screen definitely i am doing something wrong please advise.
This is the fragment code
public class fragment_MovieStartGridlayout extends android.support.v4.app.Fragment implements MyGridAdapter.MyGridAdapterListener{
private static RecyclerView myRecyclerView;
private static MyGridAdapter myGridAdapter;
private static RecyclerView.LayoutManager rvLayoutManager;
private LoaderManager.LoaderCallbacks<ArrayList<HashMap>> dataLoaderCallbacks;
private OnFragmentInteractionListener mListener;
public fragment_MovieStartGridlayout() {
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataLoaderCallbacks = new LoaderManager.LoaderCallbacks<ArrayList<HashMap>>() {
#Override
public Loader<ArrayList<HashMap>> onCreateLoader(int id, Bundle args) {
return new DataLoader(getActivityContext(), MyUriBuilder.DISCOVER, null);
}
#Override
public void onLoadFinished(Loader<ArrayList<HashMap>> loader,ArrayList<HashMap> data) {
myGridAdapter.setMyAdapterData(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<HashMap>> loader) {
loader.reset();
}
};
getLoaderManager().initLoader(0, null, dataLoaderCallbacks);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragGridLayout = inflater.inflate(R.layout.fragment_gridlayout_movie_start, container, false);
myRecyclerView = (RecyclerView) fragGridLayout.findViewById(R.id.myViewRecycler);
rvLayoutManager = new GridLayoutManager(getActivityContext(),2);
myRecyclerView.setLayoutManager(rvLayoutManager);
myGridAdapter = new MyGridAdapter(getActivityContext());
myRecyclerView.setAdapter(myGridAdapter);
return fragGridLayout;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDataSetChanged(boolean state) {
if (state){
myGridAdapter.notifyDataSetChanged();
}
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(Uri uri);
}
public Context getActivityContext(){
return this.getActivity();
}
}
and this is the Adapter for the RecyclerView
public class MyGridAdapter extends RecyclerView.Adapter<MyGridAdapter.MyViewHolder> {
LayoutInflater layoutInflater;
private static ArrayList<HashMap> data=null;
private Context mContext;
public static Bitmap placeHolder;
public MyGridAdapter(Context context){
mContext = context;
setInitialData();
placeHolder = BitmapFactory.decodeResource(mContext.getResources(),R.drawable.android_blue);
}
public interface MyGridAdapterListener{
public void onDataSetChanged(boolean state);
}
private MyGridAdapterListener listener = null;
public void registerListener(MyGridAdapterListener newListener){
listener = newListener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
layoutInflater = LayoutInflater.from(context);
View v = layoutInflater.inflate(R.layout.gridlayout_item_movie_start, parent, false);
MyViewHolder vHolder=new MyViewHolder(v);
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
HashMap singleData = data.get(position);
String movieRate = String.valueOf(singleData.get(MyJSONDataParser.TAG_VOTE_AVERAGE)) ;
holder.movieTitle.setText((String)singleData.get(MyJSONDataParser.TAG_TITLE));
holder.moviePoster.setImageBitmap(placeHolder);
holder.movieRating.setRating(Float.valueOf(movieRate));
}
#Override
public int getItemCount() {
return data.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView movieTitle;
RoundedImageView moviePoster;
RatingBar movieRating;
public MyViewHolder(View v) {
super(v);
movieTitle = (TextView) v.findViewById(R.id.movieTitleTextView);
moviePoster = (RoundedImageView) v.findViewById(R.id.roundImageView);
movieRating = (RatingBar) v.findViewById(R.id.ratingBar);
}
}
private boolean dataChanged = false;
public void setMyAdapterData(ArrayList<HashMap> data){
this.data = data;
dataChanged = true;
if (listener != null){
listener.onDataSetChanged(dataChanged);
}
}
protected void setInitialData(){
HashMap initialItem = new HashMap();
ArrayList<HashMap> initialData = new ArrayList<>(20);
initialItem.put(MyJSONDataParser.TAG_TITLE, "Loading...");
initialItem.put(MyJSONDataParser.TAG_MOVIE_BITMAP, placeHolder);
initialItem.put(MyJSONDataParser.TAG_VOTE_AVERAGE, 3.3);
for (int i = 0;i<20;i++){
initialData.add(initialItem);
}
this.data = initialData;
}
}
I did call notifyDataSetChanged
but this was not the issue after alooooooooot of testing and Logging the problem was with setAdapterData method where i just passed the data reference from the loader to the adapter but this didn't work and i had to clone the arraylist instead of just passing the reference which sounds strange to me and i still don't understand why I had to do that if you can take a look at the setAdapterData method in MyGridAdapter class and tell me what do you think 
Try invoking notifyDataSetChanged() when you modify your adapter data:
public void setMyAdapterData(ArrayList<HashMap> data){
this.data = data;
dataChanged = true;
notifyDataSetChanged();
if (listener != null){
listener.onDataSetChanged(dataChanged);
}
}
I see that you attempt to do this in the callback on your listener, but perhaps it is null and therefore never firing the notification?
[COMMENT]
When I want to replace the entire collection of data in my adapter I often write a method similar to this:
public void setData(List<MyData> newData) {
this.data.clear();
this.data.addAll(newData);
this.notifyDataSetChanged();
}

RecyclerView notifyDataSetChanged not working after Parse query

I'm in a fragment trying to updated my recycler view, after querying Parse for some data. In the done method of the query I call notifyDataSetChagned, but the list is never displayed
package com.garciaericn.t2d.fragments;
public class DevicesCardViewFragment extends Fragment implements View.OnClickListener {
private OnFragmentInteractionListener mListener;
private BatteryHelper mBatteryHelper;
Intent mBatteryStatus;
private RecyclerView mRecyclerView;
private DeviceAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<Device> mDevices;
public DevicesCardViewFragment() {
// Required empty public constructor
mDevices = new ArrayList<Device>();
}
public static DevicesCardViewFragment newInstance() {
// Bundle parameters is necessary
return new DevicesCardViewFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get arguments
getDevices();
mBatteryHelper = new BatteryHelper(getActivity());
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
mBatteryStatus = getActivity().registerReceiver(null, intentFilter);
// Update stats of current device.
Toast.makeText(getActivity(), "Battery level: " + mBatteryHelper.getCurrentBatteryLevel() + "%", Toast.LENGTH_LONG).show();
// Update device stats
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_devices_list, container, false);
mListener.showAd();
// Obtain recycler view
mRecyclerView = (RecyclerView) view.findViewById(R.id.devices_recycler_view);
mRecyclerView.setHasFixedSize(true);
mAdapter = new DeviceAdapter(getActivity(), mDevices);
// Set adapter
mRecyclerView.setAdapter(mAdapter);
// Set layout manager
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public List<Device> getDevices() {
ParseQuery<Device> query = ParseQuery.getQuery(Device.DEVICES);
// new ParseQuery<Device>(Device.DEVICES);
query.whereEqualTo("deviceUser", ParseUser.getCurrentUser());
query.findInBackground(new FindCallback<Device>() {
#Override
public void done(List<Device> devices, ParseException e) {
if (e == null) {
// Loop through return devices
for (Device device : devices) {
Device currentDevice = new Device();
currentDevice.setDeviceName(device.getDeviceName());
currentDevice.setBatteryLevel(device.getBatteryLevel());
currentDevice.setIsCharging(device.isCharging());
mDevices.add(currentDevice);
}
mAdapter.notifyDataSetChanged();
} else {
// Something went wrong
Toast.makeText(getActivity(), "Error: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
});
return mDevices;
}
#Override
public void onClick(View v) {
// Click events go here
}
public static DevicesCardViewFragment newInstance(List<Device> mDevices) {
DevicesCardViewFragment fragment = new DevicesCardViewFragment();
Bundle args = new Bundle();
return fragment;
}
public interface OnFragmentInteractionListener {
public void showAd();
}
}
My recyclerViewAdapter looks like this:
package com.garciaericn.t2d.data;
public class DeviceAdapter extends RecyclerView.Adapter<DeviceAdapter.MyViewHolder> {
private final LayoutInflater inflater;
List<Device> data = Collections.emptyList();
public DeviceAdapter(Context context, List<Device> data) {
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.card_layout, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Device device = data.get(position);
holder.deviceNameTV.setText(device.getDeviceName());
holder.batteryLevelTV.setText(device.getBatteryLevel());
}
#Override
public int getItemCount() {
return 0;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
// Temp data set
private String[] mDataset;
TextView deviceNameTV;
TextView batteryLevelTV;
public MyViewHolder(View itemView) {
super(itemView);
deviceNameTV = (TextView) itemView.findViewById(R.id.device_name_tv);
batteryLevelTV = (TextView) itemView.findViewById(R.id.battery_level_tv);
}
}
}
Change getItemCount() to actually return the correct value:
#Override
public int getItemCount() {
return data.size()
}

Categories

Resources