What I'm trying to do is to pass a data from a specific user into another activity using it's userID as unique ID
It keeps send the same data into the other activity, I dont know how to do it
This is code is for the Fragment_Home where I use to get data from Firebase and populate it into the RecyclerView, and where the Onclick is in at the moment.
public class FragmentRO_Home extends Fragment {
private Intent intent;
private DatabaseReference database;
RecyclerView recyclerView;
Recycler_View_Adapter adapter;
TextView TV_nodata;
private String uid;
private String nombre;
public FragmentRO_Home() {
// Required empty public constructor qwe
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment_ro__home,container,false);
database = FirebaseDatabase.getInstance().getReference();
final List<Data> data = new ArrayList();
TV_nodata = (TextView)view.findViewById(R.id.TV_result);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
adapter = new Recycler_View_Adapter(data, getActivity());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
fill_with_data();
This is the onclick which I'm using with recyclerview and it's functionable.
recyclerView.addOnItemTouchListener(new CustomRVItemTouchListener(getActivity(), recyclerView, new RecyclerViewItemClickListener() {
#Override
public void onClick(View view, int position) {
if (position == 0){
intent = new Intent(getActivity(), ReportInformation.class);
intent.putExtra("idData",uid);
startActivity(intent);
}else if (position == 1){
intent = new Intent(getActivity(), ReportInformation.class);
intent.putExtra("idData",uid);
startActivity(intent);
}else if (position == 2){
intent = new Intent(getActivity(), ReportInformation.class);
intent.putExtra("idData",uid);
startActivity(intent);
}else if (position == 3){
intent = new Intent(getActivity(), ReportInformation.class);
intent.putExtra("idData",uid);
startActivity(intent);
}else if (position == 5){
intent = new Intent(getActivity(), ReportInformation.class);
intent.putExtra("idData",uid);
startActivity(intent);
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
return view;
}
This is the method to where I populated my recyclerview from getting data's in the firebase.
public void fill_with_data() {
database.child("data_home").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot d) {
if (d.exists()) {
List<Data> list = new ArrayList<>();
for (DataSnapshot dataw : d.getChildren()) {
Data data = dataw.getValue(Data.class);
list.add(data);
uid = (data.usirayd);
nombre = (data.title);
}
for (Data data : list) {
adapter.insert(new Data(data.title, data.description, data.condition, data.time,data.usirayd));
}
}else {
TV_nodata.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
recyclerView.setAdapter(adapter);
}
Try this code
recyclerView.addOnItemTouchListener(new CustomRVItemTouchListener(getActivity(), recyclerView, new RecyclerViewItemClickListener() {
#Override
public void onClick(View view, int position) {
if(data.size()>position){
if (data.get(position)!= null){
intent = new Intent(getActivity(), ReportInformation.class);
intent.putExtra("idData",data.get(position).usirayd);
startActivity(intent);
}
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
return view;
}
Your list is of Data type so what you need to do is make Data class parcleable and then get object form the clicked position and send it to activity.
Sample code is something like this
public void onClick(View view, int position) {
Data dataObject = list.get(position);
intent = new Intent(getActivity(), ReportInformation.class);
intent.putExtra("idData",uid);
intent.putExtra("Data",dataObject);
startActivity(intent);
}
If you want to send single id of clicked position then just get Id from list object and send like this
uid= list.get(postion).getUserId;
and send it in intent
and in other class/activity receice that parcelable object like this
Data dataObjectReceived = getIntent().getExtras().getParcelable("Data");
and if you want to get single entity then get it by its key
When clicking on the cardView you want to pass the data into your activity or fragment for that you need to make one interface for example in my case may use one FriendModel
Interface
public interface OnFriendListClickListener {
void onItemClick(FriendModel model, int position);
}
Activity
public class FriendListActivity extends AppCompactActivity
implements
OnFriendListClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_friend);
//...
rvRemoveFriendList.setAdapter(new FriendListAdapter(context, list, this));
}
#Override
public void onItemClick(FriendModel model, int position) {
//your code here
}
}
Adapter
public class FriendListAdapter extends RecyclerView.Adapter<FriendListAdapter.FriendListHolder> {
private List<FriendModel> friendList;
private Context context;
private OnFriendListClickListener listener;
public FriendListAdapter(Context context,
List<FriendModel> friendList,
OnFriendListClickListener listener,) {
this.context = context;
this.friendList = friendList;
this.listener = listener;
}
#Override
public FriendListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new FriendListHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_friend, parent, false));
}
#Override
public void onBindViewHolder(final FriendListHolder holder, int position) {
holder.tvFriendNumber.setText(friendList.get(position).getFriendMobile());
holder.llFriendListItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onItemClick(friendList.get(holder.getAdapterPosition()),
holder.getAdapterPosition());
}
});
}
//......
}
Related
Listener in Android Studio RecyclerView custom adapter is returning null.
This is the Interface
private OnItemClickListener mlistener;
public interface OnItemClickListener{
void onItemClick(int position, Boolean paid);
}
public void setOnItemClickListener(OnItemClickListener listener){
mlistener = listener;
}
And this is the View Holder with the Listener. This is intended to pass a Boolean to the main activity.
public CartViewHolder(View itemView, ArrayList<Shift> shifts, OnItemClickListener listener) {
super(itemView);
paid = itemView.findViewById(R.id.due_back_paid);
containerView = itemView.findViewById(R.id.container);
paid.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position, isChecked);
}
}
}
});
containerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Shift current = (Shift)containerView.getTag();
Intent intent = new Intent(v.getContext(), ViewShiftActivity.class);
intent.putExtra("thisShift", current);
intent.putExtra("shifts", shifts);
v.getContext().startActivity(intent);
}
});
}
}
public LoadAdapter(ArrayList<Shift> shifts){
shiftList = shifts;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.shift_row, parent, false);
CartViewHolder mvh = new CartViewHolder(view, shiftList, mlistener);
return mvh;
}
I have used this code in other projects and it works. I have can't seem to figure out what I am missing.
I've been asked to include the activity. The following is this code.
I have not added any code to the onItemClick here yet. waiting for the listener to work.
public class EditShiftActivity extends AppCompatActivity implements LoadAdapter.OnItemClickListener{
private ArrayList<Shift> shifts;
private RecyclerView lRecyclerView;
private LoadAdapter lAdapter;
private RecyclerView.LayoutManager lLayoutManager;
private View view;
private FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_shift);
Intent intent = getIntent();
shifts = intent.getParcelableArrayListExtra("shifts");
fab = findViewById(R.id.add_shift_edit);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(EditShiftActivity.this, AddShiftActivity.class);
intent1.putExtra("shifts", shifts);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
v.getContext().startActivity(intent1);
}
});
lRecyclerView = findViewById(R.id.shift_recycler);
lLayoutManager = new LinearLayoutManager(this);
lAdapter = new LoadAdapter(shifts);
lRecyclerView.setLayoutManager(lLayoutManager);
lRecyclerView.setAdapter(lAdapter);
}
#Override
public void onItemClick(int position, Boolean paid) {
}
}
Add below line in your code -
lAdapter = new LoadAdapter(shifts);
lAdapter.setOnItemClickListener(this);
You are retrieving the ArrayList<Shifts> from Intent. Check the size of shifts arraylist before sending to the Adapter. There is a chance that if the arraylist passed is empty then the adapter will return null and hence lRecyclerView will not be displayed.
Add this condition before passing data to adapter
//condition to check whether the arraylist is empty or not
if(!shifts.isEmpty()) {
lAdapter = new LoadAdapter(shifts);
//initialising the adapter
lRecyclerView.setAdapter(lAdapter);
}
I am working on an app and i want it to scroll to a particular position i clicked from an adapter into another activity like the Instagram way of checking the smaller picture in the profile fragment and scrolling to the exact position in the other activity, that is from smaller picture to big picture.
MyAdapterCode
public class DisplayDuetAdapter extends RecyclerView.Adapter<DisplayDuetAdapter.ImageViewHolder> {
private Context mContext;
private List<DisplayDuet> mDisplayDuet;
public int position;
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public DisplayDuetAdapter(Context context, List<DisplayDuet> displayDuet){
mContext = context;
mDisplayDuet = displayDuet;
}
#NonNull
#Override
public DisplayDuetAdapter.ImageViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.duet_display_item, viewGroup, false);
return new DisplayDuetAdapter.ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final DisplayDuetAdapter.ImageViewHolder imageViewHolder, int i) {
final DisplayDuet displayDuet = mDisplayDuet.get(i);
// Glide.with(mContext).load(displayDuet.getOriginalpics()).into(imageViewHolder.original_pic);
Picasso.get().load(displayDuet.getOriginalpics()).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.placeholder).into(imageViewHolder.original_pic, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(displayDuet.getOriginalpics()).placeholder(R.drawable.placeholder).into(imageViewHolder.original_pic);
}
});
// Glide.with(mContext).load(displayDuet.getPostimage()).into(imageViewHolder.post_pic);
Picasso.get().load(displayDuet.getPostimage()).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.placeholder).into(imageViewHolder.post_pic, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(displayDuet.getPostimage()).placeholder(R.drawable.placeholder).into(imageViewHolder.post_pic);
}
});
imageViewHolder.setiItemClickListener(new IItemClickListener() {
#Override
public void onItemClickListener(View view, int position) {
Intent intent = new Intent(mContext, DuetDisplayActivity.class);
intent.putExtra("postid", displayDuet.getPostid());
intent.putExtra("publisherid", displayDuet.getPublisher());
intent.putExtra("postduetid", displayDuet.getPostduetid());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mDisplayDuet.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView post_pic, original_pic;
IItemClickListener iItemClickListener;
public void setiItemClickListener(IItemClickListener iItemClickListener) {
this.iItemClickListener = iItemClickListener;
}
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
post_pic = itemView.findViewById(R.id.duet_pic_one);
original_pic = itemView.findViewById(R.id.duet_pic_two);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
iItemClickListener.onItemClickListener(view, getAdapterPosition());
}
}
}
And the other activity code:
public class DuetDisplayActivity extends AppCompatActivity {
private String postid, publisher, postduetid;
private ImageView duet_close;
int position = 2;
private RecyclerView duet_show_recyclerView;
private DuetShowAdapter postAdapter;
private List<DisplayDuet> postList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duet_display);
Intent intent = getIntent();
postid = intent.getStringExtra("postid");
publisher = intent.getStringExtra("publisherid");
postduetid = intent.getStringExtra("postduetid");
duet_close = findViewById(R.id.close);
duet_show_recyclerView = findViewById(R.id.duet_show_recyclerView);
duet_show_recyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
duet_show_recyclerView.setLayoutManager(mLayoutManager);
postList = new ArrayList<>();
postAdapter = new DuetShowAdapter(this, postList);
duet_show_recyclerView.findViewHolderForAdapterPosition(position);
duet_show_recyclerView.setAdapter(postAdapter);
SnapHelper startSnapHelper = new PagerSnapHelper();
duet_show_recyclerView.setOnFlingListener(null);
startSnapHelper.attachToRecyclerView(duet_show_recyclerView);
duet_close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
readPost();
}
private void readPost(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("DuetPics").child(postid);
reference.keepSynced(true);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
postList.clear();
for (DataSnapshot getsnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot : getsnapshot.getChildren()) {
DisplayDuet displayDuet = snapshot.getValue(DisplayDuet.class);
postList.add(displayDuet);
}
Collections.reverse(postList);
postAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
What I understand from your question is that you want to pass the clicked position from your DisplayDuetAdapter to your DuetDisplayActivity.
If that is the case then you can pass it by the intent.
so pass the pressed item position in the DisplayDuetAdapter like this:
imageViewHolder.setiItemClickListener(new IItemClickListener() {
#Override
public void onItemClickListener(View view, int position) {
Intent intent = new Intent(mContext, DuetDisplayActivity.class);
//pass position like this
intent.putExtra("position", i);
intent.putExtra("postid", displayDuet.getPostid());
intent.putExtra("publisherid", displayDuet.getPublisher());
intent.putExtra("postduetid", displayDuet.getPostduetid());
mContext.startActivity(intent);
}
});
And get the position in the DuetDisplayActivity like this:
private int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duet_display);
Intent intent = getIntent();
postid = intent.getStringExtra("postid");
publisher = intent.getStringExtra("publisherid");
postduetid = intent.getStringExtra("postduetid");
//get the passed position
position = intent.getIntExtra("position");
............
............
update:
do this:
//get the passed position
position = intent.getIntExtra("position",0);
I'm trying to implement RecyclerView onclick listener, but it is not working. I've tried a lot, and try to implement other way too, but not working at all.
My Main Class:
public class MainMenuDashboard extends AppCompatActivity{
private RecyclerView recyclerMenu;
private RecyclerViewMenuAdapter menuAdapter;
private Call<CategoryModel> categoryModelCall;
private TokenManager tokenManagerMainMenu;
private ApiService serviceMainMenu;
List<CategoryModel.Subset> menuList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu_dashboard);
tokenManagerMainMenu = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
serviceMainMenu = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManagerMainMenu);
recyclerMenu = findViewById(R.id.recyclerMenu);
menuList = new ArrayList<>();
GridLayoutManager layoutManager = new GridLayoutManager(MainMenuDashboard.this, 2, GridLayoutManager.VERTICAL, false);
recyclerMenu.setLayoutManager(layoutManager);
menuAdapter = new RecyclerViewMenuAdapter(menuList);
recyclerMenu.setAdapter(menuAdapter);
menuAdapter.notifyDataSetChanged();
mainMenuDashBoardToolbar = findViewById(R.id.mainMenuDashBoardToolbar);
setSupportActionBar(mainMenuDashBoardToolbar);
menuContent();
}
private void menuContent() {
categoryModelCall = serviceMainMenu.menuContent(incomingRoleId, true);
categoryModelCall.enqueue(new Callback<CategoryModel>() {
#Override
public void onResponse(#NotNull Call<CategoryModel> call, #NotNull Response<CategoryModel> response) {
if (response.isSuccessful() && response.body() != null && response.code() != 400) {
//findViewById(R.id.shimmerCategory).setVisibility(View.GONE);
CategoryModel categoryModel = response.body();
menuList = categoryModel.getSubset();
menuAdapter = new RecyclerViewMenuAdapter(menuList);
recyclerMenu.setAdapter(menuAdapter);
//menuAdapter.notifyDataSetChanged();
menuAdapter.setOnItemClickListener(new RecyclerViewMenuAdapter.ClickListenerMenu() {
#Override
public void onClick(int position) {
Toast.makeText(MainMenuDashboard.this, "Position "+position+" Clicked", Toast.LENGTH_SHORT).show();
menuAdapter.notifyDataSetChanged();
}
});
menuAdapter.notifyDataSetChanged();
}else {
if (response.code() == 401) {
Intent i = new Intent(MainMenuDashboard.this, MainActivity.class);
i.putExtra("USER_SESSION", true);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
tokenManagerMainMenu.deleteToken();
startActivity(i);
finish();
}
}
}
#Override
public void onFailure(#NotNull Call<CategoryModel> call, #NotNull Throwable t) {
}
});
}
}
My Adapter:
public class RecyclerViewMenuAdapter extends RecyclerView.Adapter<RecyclerViewMenuAdapter.RecyclerViewHolder> {
private static final String TAG = "NotesRecyclerAdapter";
private List<CategoryModel.Subset> subsetsCategories;
private ClickListenerMenu mClickListener;
private Context context;
public RecyclerViewMenuAdapter(List<CategoryModel.Subset> subsetsCategories) {
this.subsetsCategories = subsetsCategories;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler_main_menu_category, parent, false);
return new RecyclerViewHolder(view, mClickListener);
}
#Override
public void onBindViewHolder(#NonNull final RecyclerViewHolder viewHolder, final int position) {
String menuCategoryImage = subsetsCategories.get(position).getIcon();
Picasso.get().load(menuCategoryImage).placeholder(R.drawable.admin).into(viewHolder.menuThumb);
String menuCategoryName = subsetsCategories.get(position).getName();
viewHolder.menuName.setText(menuCategoryName);
//Item click
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
mClickListener.onClick(position);
//Toast.makeText(context, "Position "+position+" Clicked", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return subsetsCategories.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder{
ImageView menuThumb;
TextView menuName;
private ClickListenerMenu mListener;
//ClickListenerMenu clickListenerMenu;
public RecyclerViewHolder(View view, ClickListenerMenu clickListenerMenu) {
super(view);
menuThumb = view.findViewById(R.id.menuThumb);
menuName = view.findViewById(R.id.menuName);
mListener = clickListenerMenu;
}
}
public void setOnItemClickListener(ClickListenerMenu clickListener) {
mClickListener = clickListener;
}
public interface ClickListenerMenu {
void onClick(int position);
}
}
I still can't find where I did wrong!! Any insight will be very appreciated
Thank You
Add item click listener in your adapter.
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder viewHolder, int position) {
String menuCategoryImage = subsetsCategories.get(position).getIcon();
Picasso.get().load(menuCategoryImage).placeholder(R.drawable.admin).into(viewHolder.menuThumb);
String menuCategoryName = subsetsCategories.get(position).getName();
viewHolder.menuName.setText(menuCategoryName);
//Item click
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
// Do something
}
});
}
Initialise your recycler view outside and put this line menuAdapter.notifyDataSetChanged(); where you add data in your list.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu_dashboard);
tokenManagerMainMenu = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
serviceMainMenu = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManagerMainMenu);
recyclerMenu = findViewById(R.id.recyclerMenu);
menuList = new List<CategoryModel.Subset>();
GridLayoutManager layoutManager = new GridLayoutManager(MainMenuDashboard.this, 2, GridLayoutManager.VERTICAL, false);
recyclerMenu.setLayoutManager(layoutManager);
menuAdapter = new RecyclerViewMenuAdapter(menuList);
recyclerMenu.setAdapter(menuAdapter);
menuAdapter.notifyDataSetChanged();
menuContent();
}
I hope this can help you!
Add these line in the onBindViewHolder() method:
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//remove this lines
//mClickListener.onClick(position);
//notifyDataSetChanged();
//add this
context.startActivity(new Intent(context,SecondActivity.class))
}
});
and in your MainMenuDashboard class, initialize your Adapter like this:
menuAdapter = new RecyclerViewMenuAdapter(this,menuList);
also change your Adapter constructor like this:
public RecyclerViewMenuAdapter(Context context,List<CategoryModel.Subset> subsetsCategories) {
this.subsetsCategories = subsetsCategories;
this.context = context;
}
```
I'm using Viewpager for slider and initially Recyclerview... When I load image from Server to recycler it's done... Now what i want to do that when ever someone click on particular item, it should be opened in second activity in which ViewPager I use.. example: When I click first Image, it should open that image in viewPager(slider).... And Also when someone swipe on ViewPager's activity it should load more images....
Code is Below and don't know what to do next. Please Help me.
RecyclerView
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.myViewHolder> {
ArrayList<model> mdata;
Context context;
public RecyclerViewAdapter(){ }
public RecyclerViewAdapter(ArrayList<model> mdata, Context context) {
this.mdata = mdata;
this.context = context;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.item,viewGroup,false);
return new myViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final myViewHolder holder, int i) {
Picasso.get().load(mdata.get(holder.getAdapterPosition()).getWallpaper()).into(holder.wallpaper);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context,SecondActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("wallpaperUrl",mdata.get(holder.getAdapterPosition()).getWallpaper());
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return mdata.size();
}
public class myViewHolder extends RecyclerView.ViewHolder{
ImageView wallpaper;
Button set;
public myViewHolder(#NonNull View itemView) {
super(itemView);
wallpaper = itemView.findViewById(R.id.wallpaper);
set = itemView.findViewById(R.id.set);
}
}
Second Activity which have ViewPager:
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
btn = findViewById(R.id.setWallpaper);
mdata = new ArrayList<model>();
viewPager = findViewById(R.id.viewPager);
Intent intent = getIntent();
Integer[] colors_temp ={getResources().getColor(R.color.color1),
getResources().getColor(R.color.color2),
getResources().getColor(R.color.color3),
getResources().getColor(R.color.color4),
} ;
colors = colors_temp;
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffSet, int pixels) {
if (position < adapter.getCount() -1 && position <(colors.length) -1){
viewPager.setBackgroundColor(
(Integer) argbEvaluator.evaluate
(positionOffSet,
colors[position],
colors[position + 1]));
}else{
viewPager.setBackgroundColor(colors[colors.length - 1]);
}
}
#Override
public void onPageSelected(final int i) {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DownloadImage downloadImage = new DownloadImage();
Bitmap bitmap = null;
try{
bitmap =
downloadImage.execute(mdata.get(i).getWallpaper()).get();
}catch (Exception e){
e.printStackTrace();
Toast.makeText(SecondActivity.this, "Something went
Wrong! ", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
mDatabase = FirebaseDatabase.getInstance();
mReference = mDatabase.getReference().child("wallpapers");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
model data = dataSnapshot1.getValue(model.class);
mdata.add(data);
}
adapter = new Adapter(mdata,getApplicationContext());
viewPager.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(SecondActivity.this, "Failed! "+databaseError,
Toast.LENGTH_SHORT).show();
}
});
}
MyAdapter:
public class Adapter extends PagerAdapter {
ArrayList<model> mdata;
Context context;
LayoutInflater inflater;
public Adapter(){
}
public Adapter(ArrayList<model> mdata, Context context) {
this.mdata = mdata;
this.context = context;
}
#Override
public int getCount() {
return mdata.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object o) {
return view.equals(o);
}
#NonNull
#Override
public Object instantiateItem(#NonNull final ViewGroup container, final int position) {
inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.pager_item,container,false);
ImageView wallpaper;
Button btn;
wallpaper = view.findViewById(R.id.wallpaperImage);
Picasso.get().load(mdata.get(position).getWallpaper()).into(wallpaper);
container.addView(view,0);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View)object);
}
If you are loading the images from the server, and each image has an id, pass the id into then intent. When you open up the view that needs the image that was clicked, make a service call to retrieve the image from the server using it's id.
In your enter code here, add setOnclickListener to holser.iytemView, then create an intent for navigating to the second activity, and add this code in onBindViewHolder:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: LoadingProfileActivity");
Intent intent = new Intent(getContext(), SecondActivity.class);
/*
Extras
*/
mainActivityContext.startActivity(intent);
}
});
If you want to send the image or id that contained in this row add intent.putExtra() after the intent is created.
Like if I want to display the image in second activity ill put in
Intent intent = new Intent(getContext(), SecondActivity.class);
intent.putExtra("image_url", imageResource);
In SecondActivity firsts get the imageresource from the intent
String imageResouce = getIntent.getStringExtra("image_url");
Then display the image in image view
public class MainActivity extends Activity implements
GetDataContract.View,RecyclerItemClickListener {
private Presenter mPresenter;
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
CountryAdapter countryAdapter;
EditText etEnterName;
Button btAddItem;
List<CountryRes> allCountriesEditValue;
List<CountryRes> allCountriesData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getView();
}
private void getView() {
/*presentator */
mPresenter = new Presenter(this);
/*initiliaze of id*/
recyclerView = (RecyclerView) findViewById(R.id.recycler);
etEnterName = (EditText) findViewById(R.id.etEnterName);
btAddItem = (Button) findViewById(R.id.btAddItem);
linearLayoutManager = new LinearLayoutManager(this);
/*initiliaze the arraylist*/
allCountriesData=new ArrayList<>();
recyclerView.setLayoutManager(linearLayoutManager);
btAddItem.setOnClickListener(new AddButtonClick());
}
#Override
public void onGetDataFailure(String message) {
Log.d("Status", message);
}
#Override
public void onGetDataSuccess(String message, List<CountryRes>
allCountriesData) {
/*add the value mannulay*/
CountryRes countryRes = new CountryRes();
countryRes.setName(etEnterName.getText().toString());
allCountriesData.add(countryRes);
countryAdapter = new CountryAdapter(getApplicationContext(),
allCountriesData, (RecyclerItemClickListener) this);
recyclerView.setAdapter(countryAdapter);
/*set the data in the room*/
AppDataBase database = AppDataBase.getAppDatabase(this);
DataGenerator.with(database).generateCats(allCountriesData);
Logger.displayCatsInLog(database.catDao().loadAll());
countryAdapter.notifyDataSetChanged();
}
/*on item click*/
#Override
public void onDashBoardItemClick(String pos) {
Bundle bundle = new Bundle();
bundle.putString("TABVALUE", pos);
Intent intent = new Intent(getApplicationContext(),
DynamicTabsActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
private class AddButtonClick implements View.OnClickListener {
#Override
public void onClick(View view) {
mPresenter.getDataFromURL(getApplicationContext(), "");
}
}
}
class adapter
public class CountryAdapter extends
RecyclerView.Adapter<CountryAdapter.MyViewHolder> {
private Context context;
private List<CountryRes> list = new ArrayList<>();
private List<CountryRes> list_edit = new ArrayList<>();
private RecyclerItemClickListener onRecyclerItemClickListener;
public CountryAdapter(Context context, List<CountryRes> list,
RecyclerItemClickListener onRecyclerItemClickListener) {
this.context = context;
this.list = list;
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
}
#Override
public CountryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View layoutView;
layoutView =
LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent,
false);
return new FooterViewHolder(layoutView,
onRecyclerItemClickListener);
}
#Override
public void onBindViewHolder(CountryAdapter.MyViewHolder holder, int
position) {
holder.tvCountryName.setText(list.get(position).getName());
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvCountryName;
LinearLayout llListItem;
public MyViewHolder(View itemView) {
super(itemView);
tvCountryName = (TextView)
itemView.findViewById(R.id.tv_country_name);
llListItem = (LinearLayout)
itemView.findViewById(R.id.llListItem);
}
}
private class FooterViewHolder extends MyViewHolder {
public FooterViewHolder(View layoutView, final
RecyclerItemClickListener onRecyclerItemClickListener) {
super(layoutView);
llListItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onRecyclerItemClickListener != null) {
onRecyclerItemClickListener.onDashBoardItemClick(tvCountryName.getText().toS
tring());
}
}
});
}
}
}
Interface
public interface RecyclerItemClickListener {
void onDashBoardItemClick(String pos);
}
Case 1: Inside ViewHolder if you need to understand exactly position of clicked item you could call getAdapterPosition().
Case 2: You just need to receive all items of adapter. It is simple, make getter method which will return the items.
Case 3: Send info to activity, first make some specific event listener of your view inside ViewHolder, then event triggers (user clicks or other) and you call your interface method which you passed inside adapter, that was implemented in activity.
Tell me if you need an example, i will do it.
Try this one,
Button button= (Button) findViewById(R.id.your_button_id);
button.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
//create new ArrayList.
//ArrayList<CountryRes> showList=new ArrayList<>;
//now, put all stored data of a list in this arraylist.
showList.addAll(allCountriesData);
}
});