I have activity and 3 fragments in ViewPage.
In last fragment I have recycleView, if i move to this page i want to refresh recycle view and its work only if I call:
mAdapter = new LocationAdapter(mListener.loadLocationList());
mRecyclerView.setAdapter(mAdapter);
This should work aswell after call notifyDataSetChanged but didn't.
What can we wrong ?
in last fragment:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new LocationAdapter(mListener.loadLocationList());
mRecyclerView.setAdapter(mAdapter);
}
private class HistoryFragmentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (HISTORY_FRAGMENT_SELECTED.equals(intent.getAction())){
updateLocationList();
}
}
}
private void updateLocationList() {
mAdapter = new LocationAdapter(mListener.loadLocationList());
mRecyclerView.setAdapter(mAdapter);
}
i wanted notifydatasetchanged instead of 2 lines in updatelocationlist()
LocationAdapter:
public class LocationAdapter extends RecyclerView.Adapter<LocationAdapter.LocationViewHolder> {
private LinkedList<LatLng> mDataset;
public static class LocationViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mTextView;
public LocationViewHolder(View v) {
super(v);
mTextView = v;
}
}
public LocationAdapter(LinkedList<LatLng> myDataset) {
mDataset = myDataset;
}
#NonNull
#Override
public LocationAdapter.LocationViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View v = layoutInflater.inflate(R.layout.my_text_view, parent, false);
LocationViewHolder vh = new LocationViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(#NonNull LocationAdapter.LocationViewHolder locationViewHolder, int position) {
TextView textView = locationViewHolder.mTextView.findViewById(R.id.textView3);
textView.setText(String.valueOf(mDataset.get(position)));
}
#Override
public int getItemCount() {
return mDataset.size();
}
}
The problem is you set data only in your adapter's constructor.
When you call notifyDataSetChanged you can't expect that your adapter will take new data magically. You have to set it by yourself.
My suggestion would be add a setData method in your adapter and call it before notifyDataSetChanged.
Something like this in your adapter:
public void setData(LinkedList<LatLng> myDataset) {
mDataset = myDataset
}
and in your caller:
private void updateLocationList() {
mAdapter.setData(mListener.loadLocationList());
mAdapter.notifyDataSetChanged();
}
Related
I cannot access the ID of the item to view it in ToastMessage, or even store it in the database (use Room DataBase)
I have tried but the message does not appear
I need the reference ID to use for database storage and complete the process for storing the shopping cart
itemAdapter.java
public class itemAdapter extends RecyclerView.Adapter<itemAdapter.ItemViewHolder> {
private Context context;
private ArrayList<Items> arrayList;
private AdapterView.OnItemClickListener listener;
public itemAdapter(Context context, ArrayList<Items> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
return new ItemViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
holder.name.setText(arrayList.get(position).getItemName());
holder.desc.setText(arrayList.get(position).getItemDesc());
holder.price.setText(arrayList.get(position).getItemPrice());
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemIid(),Toast.LENGTH_SHORT);
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemPrice(),Toast.LENGTH_SHORT);
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
TextView name, desc, price;
ImageView remove, add;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.tvName);
desc = itemView.findViewById(R.id.tvDesc);
price = itemView.findViewById(R.id.tvPrice);
remove = itemView.findViewById(R.id.btnDelete);
add = itemView.findViewById(R.id.btnAdd);
}
}
}
MealsFragment.java
public class MealsFragment extends Fragment {
public MealsFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
itemAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meals, container, false);
}
#Override
public void onViewCreated( View view, Bundle savedInstanceState) {
ArrayList<Items> ItemsList = (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getContext().getApplicationContext())
.getAppDatabase()
.getDao()
.getItems("meals");
recyclerView = view.findViewById(R.id.rvMeals);
RecyclerView.LayoutManager manager = new LinearLayoutManager(
getContext(), RecyclerView.VERTICAL, false);
recyclerView.setLayoutManager(manager);
adapter = new itemAdapter(getContext(), ItemsList);
recyclerView.setAdapter(adapter);
}
}
Try the following instead
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemIid(),Toast.LENGTH_SHORT).show();
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemPrice(),Toast.LENGTH_SHORT).show();
}
});
The static method makeText of Toast is used to create the Toast object and show() method on the Toast object is used to display the Toast
I tried to make a setListener on adapter to make something Action on the app. But the problem was when using this line of code to call setClickListener
adapter.setClickListener(this);
it gives me this error when using (this)
Required type: ItemClickListener
Provided: HomeImagesFragment
Here are my codes
Picassotest "Adapter for RecyclerView"
public class Picassotest extends RecyclerView.Adapter<Picassotest.ViewHolder> {
private String[] mData;
private Context context;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public Picassotest(Context context, String[] data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.context = context;
}
// inflates the cell layout from xml when needed
#Override
#NonNull
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.images_list, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each cell
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Picasso
.with(context)
.load(mData[position])
.fit() // to resize the image to imageView
.placeholder(R.drawable.loading_image) // load image
.transform(new PicassoRoundedTransformation(20, 0)) // Add radius to the images
.noFade()
.into(holder.mimageView);
}
// total number of cells
#Override
public int getItemCount() {
return mData.length;
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView mimageView;
ViewHolder(View itemView) {
super(itemView);
mimageView = itemView.findViewById(R.id.list_image);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mData[id];
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
HomeImagesFragment "Fragment"
public class HomeImagesFragment extends Fragment {
private Picassotest adapter;
String[] chooseImages;
public HomeImagesFragment(String[] chooseImages) {
this.chooseImages = chooseImages;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.images_fragment_home, container, false);
/* ArrayList for chooseImages */
chooseImages = new String[]{
"https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
"https://whatt.cc/wp-content/uploads/2018/07/4443.jpg",
"https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
};
/* make new object and find the view "GridView" */
RecyclerView recyclerView = rootView.findViewById(R.id.recyclerview_image_choose);
// Calculate the items and auto-fit it on the screen
int mNoOfColumns = Utility.calculateNoOfColumns(getActivity(), 140);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), mNoOfColumns));
adapter = new Picassotest(getActivity(), chooseImages);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
return rootView;
}
public void onItemClick(int position) {
// get the image
String image = chooseImages[position];
Intent intent = new Intent(getActivity(), PicassoImageDisplayWallpaperAdapter.class);
intent.putExtra("imageUrl", image);
getActivity().startActivity(intent);
}
You need to create an interface like below code
interface ItemClickListener{
public void onItemClick(int position);
}
You need to implements ItemClickListener in your HomeImagesFragment
SAMPLE CODE
public class HomeImagesFragment extends Fragment implements ItemClickListener{
private Picassotest adapter;
String[] chooseImages;
public HomeImagesFragment(String[] chooseImages) {
this.chooseImages = chooseImages;
}
#Override
public void onItemClick(int position) {
// you will clikcked item position here
String image = chooseImages[position];
Intent intent = new Intent(getActivity(), PicassoImageDisplayWallpaperAdapter.class);
intent.putExtra("imageUrl", image);
getActivity().startActivity(intent);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.images_fragment_home, container, false);
/* ArrayList for chooseImages */
chooseImages = new String[]{
"https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
"https://whatt.cc/wp-content/uploads/2018/07/4443.jpg",
"https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
};
/* make new object and find the view "GridView" */
RecyclerView recyclerView = rootView.findViewById(R.id.recyclerview_image_choose);
// Calculate the items and auto-fit it on the screen
int mNoOfColumns = Utility.calculateNoOfColumns(getActivity(), 140);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), mNoOfColumns));
adapter = new Picassotest(getActivity(), chooseImages);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
return rootView;
}
public void onItemClick(int position) {
// get the image
String image = chooseImages[position];
Intent intent = new Intent(getActivity(), PicassoImageDisplayWallpaperAdapter.class);
intent.putExtra("imageUrl", image);
getActivity().startActivity(intent);
}
(Additional) Another way if you use Kotlin:
Sample Code
In Adapter class (Picassotest):
class Picassotest : RecyclerView.Adapter<Picassotest.ViewHolder>{
internal var itemClickListener: (Int) -> Unit = {}
inner class ViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
init{
itemView.setOnClickListener{
itemClickListener.invoke(adapterPosition)
}
}
}
}
In HomeImagesFragment:
class HomeImagesFragment{
adapter = new Picassotest(getActivity(), chooseImages)
adapter.itemClickListener = { position->
//TODO handle item on click here
}
}
I Uploaded some data to sqlite and I want to delete each data from the recyclerview by pressing a button. so how can I achieve this? I want to get the id from recyclerview to the mainactivity then delete the data from sqlite and update reyclerview. How can I achieve this?
MainActivity
public class SelectedProblems extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selecte_problem_drawal);
mRecyclerView = (RecyclerView) findViewById(R.id.selected_problem_recycle_view); // Instantiate Recyclerview
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems(), listener);
mRecyclerView.setAdapter(selectedProblemsAdapter);
Button remove = findviewbyid(R.id.remove);
remove.setOnClickListener(new View.OnClickListener() {
}
}
SelectedProblemsAdapter
public SelectedProblemsAdapter(Context context, Cursor cursor, OnItemClick listener) {
this.context = context;
this.cursor = cursor;
listener = listener;
}
#Override
public SelectedProblemsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_selected_problems_content, null, false);
return new SelectedProblemsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SelectedProblemsViewHolder holder, final int position) {
if (this.cursor != null){
}
}
#Override
public int getItemCount() {
return (null != cursor ? cursor.getCount(): 0);
}
public void update(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
class SelectedProblemsViewHolder extends RecyclerView.ViewHolder{
TextView selectedProblems, selectedProblemPrice, selectedProblemTotal;
Button remove_problem_from_cart;
public SelectedProblemsViewHolder(View itemView) {
super(itemView);
selectedProblems = itemView.findViewById(R.id.selected_problems);
selectedProblemPrice = itemView.findViewById(R.id.selected_problem_price);
selectedProblemTotal = itemView.findViewById(R.id.selectedProblemTotal);
remove_problem_from_cart = itemView.findViewById(R.id.remove_problem_from_cart);
}
}
}
MainActivity
public class SelectedProblems extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selecte_problem_drawal);
mRecyclerView = (RecyclerView) findViewById(R.id.selected_problem_recycle_view); // Instantiate Recyclerview
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems(), listener);
mRecyclerView.setAdapter(selectedProblemsAdapter);
Button remove = findviewbyid(R.id.remove);
remove.setOnClickListener(new View.OnClickListener() {
}
}
SelectedProblemsAdapter
public SelectedProblemsAdapter(Context context, Cursor cursor, OnItemClick listener) {
this.context = context;
this.cursor = cursor;
listener = listener;
}
#Override
public SelectedProblemsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_selected_problems_content, null, false);
return new SelectedProblemsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SelectedProblemsViewHolder holder, final int position) {
if (this.cursor != null){
// it will call your interface method which is implemented in Activity
holder.yourView_name.setOnClickListener(new View.OnClickListener() {
listener.yourmethod();
}
}
}
#Override
public int getItemCount() {
return (null != cursor ? cursor.getCount(): 0);
}
public void update(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
class SelectedProblemsViewHolder extends RecyclerView.ViewHolder{
TextView selectedProblems, selectedProblemPrice, selectedProblemTotal;
Button remove_problem_from_cart;
public SelectedProblemsViewHolder(View itemView) {
super(itemView);
selectedProblems = itemView.findViewById(R.id.selected_problems);
selectedProblemPrice = itemView.findViewById(R.id.selected_problem_price);
selectedProblemTotal = itemView.findViewById(R.id.selectedProblemTotal);
remove_problem_from_cart = itemView.findViewById(R.id.remove_problem_from_cart);
}
}
}
You can achieve it by implementing an interface.
Step 1: Create an interface with an abstract function that takes in the type of data as its parameters.
public interface OnDataItemClickListener {
void onItemClick(YourItem yourItem);
}
Step 2: Make the activity implement the interface and override its methods.
public class SelectedProblems extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selecte_problem_drawal);
mRecyclerView = (RecyclerView) findViewById(R.id.selected_problem_recycle_view); //
//Instantiate Recyclerview
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems());
mRecyclerView.setAdapter(selectedProblemsAdapter);
}
#Override
public void onItemClick(YourItem yourItem) {
}
Step 3: Pass the interface through the adapter's constructor.
//Global variable of the interface
private onDataItemClickListener onclickListner;
// while instatiating the adapter
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems(), onClickListener);
Step 4: In the onBindViewHolder method, use the interface instance(received through the constructor) to call the methods, which will help pass the data to the main activity/ activity.
public SelectedProblemsAdapter(Context context, Cursor cursor, OnDataItemClickListener listener) {
this.context = context;
this.cursor = cursor;
listener = listener;
}
#Override
public SelectedProblemsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_selected_problems_content, null, false);
return new SelectedProblemsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SelectedProblemsViewHolder holder, final int position) {
if (this.cursor != null){
holder.yourView.setOnClickListener(new View.OnClickListener() {
// onItemClick is the abstract function present in the interface.
listener.onItemClicked(" your data item ");
// here the data item/position etc, which you want to delete will be passed on to the main acticity.
}
}
}
#Override
public int getItemCount() {
return (null != cursor ? cursor.getCount(): 0);
}
public void update(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
class SelectedProblemsViewHolder extends RecyclerView.ViewHolder{
TextView selectedProblems, selectedProblemPrice, selectedProblemTotal;
Button remove_problem_from_cart;
public SelectedProblemsViewHolder(View itemView) {
super(itemView);
selectedProblems = itemView.findViewById(R.id.selected_problems);
selectedProblemPrice = itemView.findViewById(R.id.selected_problem_price);
selectedProblemTotal = itemView.findViewById(R.id.selectedProblemTotal);
remove_problem_from_cart = itemView.findViewById(R.id.remove_problem_from_cart);
}
}
}
Step 5: Finally write the code to delete the object through the overridden interface method, in the main activity.
#Override
public void onItemClick(YourItem yourItem) {
yourItem.delete();
// you can use any number of functions to perform with your dataItem here.
selectedProblemsAdapter.update()
//call your update function here to change the list in recycler view.
}
Note: If you are using a view model and live data, you do not need to write the notifyDataSetChanged() function.The data gets updated automatically.
This will help you to delete or perform any number of operations on your data, which is passed from your adapter to the main activity.
I am trying to run some code I got from some online tutorial of writing a fragment with a recyclerview in it but I am experiencing some difficulty in opening an activity from the onclick event. My adapter is below
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.MyViewHolder> {
private final ArrayList<ItemModel> mArrayList;
private Context mcontext;
ItemAdapter(ArrayList<ItemModel> mArrayList) {
this.mArrayList = mArrayList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
mcontext = parent.getContext();
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listing_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
//Glide.with(mcontext).load(mArrayList.get(position).getImage()).into(holder.item_image);
holder.item_name.setText(mArrayList.get(position).getTitle());
holder.item_description.setText(mArrayList.get(position).getDescription());
holder.item_tags.setText(mArrayList.get(position).getTags());
Log.d("MyAdapter", "position: " + position);
}
#Override
public int getItemCount() {
return mArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final ImageView item_image;
private final TextView item_name;
private final TextView item_description;
private final TextView item_tags;
private final LinearLayout cardViewLayout;
MyViewHolder(View view) {
super(view);
item_image = view.findViewById(R.id.item_image);
item_name = view.findViewById(R.id.item_name);
item_description = view.findViewById(R.id.item_description);
item_tags = view.findViewById(R.id.item_tags);
cardViewLayout = view.findViewById(R.id.cardViewLayout);
cardViewLayout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent intent = new Intent(mcontext, ItemView.class);
mcontext.startActivity(intent);
}
}
}
When I run the code nothing happens when i click on a item and neither do I see any error in the logcat
Instead, try like this,
ItemAdapter(Context context, ArrayList<ItemModel> mArrayList) {
this.mArrayList = mArrayList;
this.mContext = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listing_item, parent, false);
return new MyViewHolder(view);
}
In your fragment, while setting adapter
ItemAdapter itemAdapter=new ItemAdapter(getActivity(),itemList);
You can have a listener sent from the fragment to adapter. Instead of trying to start an activity from the adapter, you can send it back to the fragment to open the activity.
1. Define an interface
public interface MyAdapterListener {
void openActivity(/*any values to be sent*/);
}
2. The fragment should implement MyAdapterListener
3. send the listener object to an adapter in a constructor
ItemAdapter(ArrayList<ItemModel> mArrayList, MyAdapterListener listener) {..
mListener = listener;
}
4. On Adapter - View Holder: in onClick() return to fragment
public void onClick(View view) {
mListener.openActivity(/*any values to be sent*/);
}
I was of the idea that on your application of the adapter in some activity you simply call the activity on the setOnItemClickListener of the adapter
private void loadItemsData() {
RecyclerView itemsRecyclerView = view.findViewById(R.id.posts_recycler_view);
itemsRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
itemsRecyclerView.setLayoutManager(layoutManager);
ItemAdapter myadapter = new ItemAdapter(new ArrayList<MyItem>(), getContext());
myadapter.setOnItemClickListener(new ItemAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, PostItems items) {
ViewItem.passingIntent(getActivity(), items.postid);
}
});
itemsRecyclerView.setAdapter(ListAdapter );
}
then once done that you come to the receiver activity and make way to get the variables being passed on to it
public static void passingIntent(Activity activity, Integer postid){
Intent intent = new Intent(activity, ViewItem.class);
intent.putExtra(MY_ITEM, postid);
activity.startActivity(intent);
}
I have used this approach in one of my apps lately
Try setting your click listener in onBindViewHolder like below
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
//Glide.with(mcontext).load(mArrayList.get(position).getImage()).into(holder.item_image);
holder.item_name.setText(mArrayList.get(position).getTitle());
holder.item_description.setText(mArrayList.get(position).getDescription());
holder.item_tags.setText(mArrayList.get(position).getTags());
holder.setOnClickListener(this) // put this line
Log.d("MyAdapter", "position: " + position);
}
Then of course you will override onClick in adapter rather than viewholder
So I saw this tutorial that creates a recyclerview in fragments of navigation drawer. In this tutorial, the data is stored in an array. What I am trying to do right now is to store the data in an ArrayList.
Here is my code in ‘Tutor’ Fragment:
public class Tutors extends Fragment
{
View myView;
private ArrayList<TutorModel> tutorModelList = new ArrayList<>();
private RecyclerView recyclerView;
private MyAdapter tutorAdapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getTutorData();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.admin_manage_tutors,
container, false);
recyclerView = myView.findViewById(R.id.recycler_view);
tutorAdapter = new MyAdapter(tutorModelList);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(tutorAdapter);
return myView;
}
public void getTutorData()
{
TutorModel tutor = new TutorModel("Juan", "Computer Programming");
tutorModelList.add(tutor);
tutor = new TutorModel("Santiago", "French History");
tutorModelList.add(tutor);
tutor = new TutorModel("Jose", "Philippine History");
tutorModelList.add(tutor);
tutorAdapter.notifyDataSetChanged();
}
}
This is the code of my Adapter:
public class MyAdapter extends
RecyclerView.Adapter<MyAdapter.MyViewHolder> {
public List<TutorModel> tutorList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, subjects;
public MyViewHolder(View view) {
super(view);
name = view.findViewById(R.id.name_tutor);
subjects = view.findViewById(R.id.subjects_tutor);
}
}
public MyAdapter(List<TutorModel> tutorList) {
this.tutorList = tutorList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.tutor_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
TutorModel tutor = tutorList.get(position);
holder.name.setText(tutor.getTutorName());
holder.subjects.setText(tutor.getTutorSubject());
}
#Override
public int getItemCount() {
return tutorList.size();
}
}
And this is my getter/setter code:
public class TutorModel
{
String tutorName, tutorSubject;
public String getTutorName() {
return tutorName;
}
public void setTutorName(String tutorName) {
this.tutorName = tutorName;
}
public String getTutorSubject() {
return tutorSubject;
}
public void setTutorSubject(String tutorSubject) {
this.tutorSubject = tutorSubject;
}
public TutorModel(String tutorName, String tutorSubject) {
this.tutorName = tutorName;
this.tutorSubject = tutorSubject;
}
public TutorModel() {
}
}
When I try to run the app, it crashes.
onCreateView will be invoked after onCreate but getTutorData(); is notifying the adapter which is yet to be initialized by onCreateView so initialize your adapter before getTutorData(); method call
or better way is call getTutorData inside onCreateView
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.admin_manage_tutors,
container, false);
recyclerView = myView.findViewById(R.id.recycler_view);
tutorAdapter = new MyAdapter(tutorModelList);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(tutorAdapter);
getTutorData();
return myView;
}
You have initialized your tutorAdapter in onCreateView() but onCreate gets called before onCreateView so your adapter is null..just edit your onCreate like the code below..
#Override
public void onCreate(#Nullable Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
tutorAdapter = new MyAdapter(tutorModelList);
getTutorData(); }