How to Use ViewPager Button On MainActivity Page? - android

How can I use Viewpager Adapter Button into MainActivity? I am developing a quiz app and I am comparing button value into MainActivity. How can I access ViewPagerAdapter class buttons In MainActivity?
#Override
protected void onStart() {
super.onStart();
Ref.child("Exam_Category").child("PRACTICE TEST").child("PREVIOUS YEAR PAPER'S").child(ct1).child(ct2).child("ENGLISH COMPREHENSION").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
for (DataSnapshot data : dataSnapshot.getChildren()) {
key = data.getKey().toString();
Ref.child("Exam_Category").child("PRACTICE TEST").child("PREVIOUS YEAR PAPER'S").child(ct1).child(ct2).child("ENGLISH COMPREHENSION").child(String.valueOf(key))
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
final questions studentDetails = dataSnapshot.getValue(questions.class);
list.add(studentDetails);
adapter = new RecyclerViewAdapter(Previous_Yr_Quiz.this, list);
viewPager.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
//total_q.setText(Question_No +" / "+key);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
This is My ViewPager Adapter
public class RecyclerViewAdapter extends PagerAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
public List<questions> list;
public RecyclerViewAdapter(Context context, List<questions> TempList) {
this.context = context;
this.list = TempList;
}
#Override
public int getCount() {
return list.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
// Declare Variables
TextView question;
final Button option1,option2,option3,option4;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.quiz_layout_listview, container,
false);
// Locate the TextViews in viewpager_item.xml
question = (TextView)itemView.findViewById(R.id.question);
option1 = (Button) itemView.findViewById(R.id.optiona);
option2 = (Button) itemView.findViewById(R.id.optionb);
option3 = (Button) itemView.findViewById(R.id.optionc);
option4 = (Button) itemView.findViewById(R.id.optiond);
// Capture position and set to the TextViews
questions studentDetails = list.get(position);
question.setText(studentDetails.getQuestion());
option1.setText(studentDetails.getOption1());
option1.setId(position);
option2.setText(studentDetails.getOption2());
option3.setText(studentDetails.getOption3());
option4.setText(studentDetails.getOption4());
option1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
option1.setBackgroundResource(R.drawable.wrong);
}
});
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
private int getItem(int i) {
return list.size();
}
}
How can used button options A, B, C, D OnClick in MainActivity because I compare button value into A, B, C, D buttons....

You have two options:
1) Make Buttons as class members and access them from your Activity by get methods.
2) Write an Interface that will have the callback methods so you know which Button is being clicked. Once you write the interface you pass it as a constructor parameter or by a set method. Something like:
interface QuizListener {
void answered(Button whichButton);
}
...
[RecyclerViewAdapter.java]
public RecyclerViewAdapter(Context context, List<questions> TempList, QuizListener quizListener) {
this.context = context;
this.list = TempList;
this.quizListener = quizListener;
}
...
option1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (quizListener != null) {
quizListener.answered(option1);
}
option1.setBackgroundResource(R.drawable.wrong);
}
});

Related

android Pass recyclerview item position to dialog button listener

Dialog with multiple buttons(cancalButton, deleteButton) is showed when click button in recyclerview item.
So I made two listener(cancelListener, deleteListener).
Show dialog is successful and cancelListener works well, But I can't do what I want in delteListener.
I wanna delete data in firebase when user click delete button in dialog.
So I have to know clicked recyclerview item's position to find data. (Because I can find data by getting key from array.get(position).getTimestamp.
How can I get item position in deleteListener?
public class AdapterExplorePlace extends RecyclerView.Adapter<AdapterExplorePlace.ViewHolder> implements Pin_BottomSheetDialog.BottomSheetListener {
ArrayList<ItemExplore> array;
Context context;
private AdapterExplorePlace.RecyclerViewClickListener listener;
private DialogDeletePin dialog;
DatabaseReference pinRef;
FirebaseAuth mAuth;
String currentPage;
#ColorInt int starColor;
#ColorInt int startextColor;
public AdapterExplorePlace(ArrayList<ItemExplore> array, Context context, AdapterExplorePlace.RecyclerViewClickListener listener) {
this.array = array;
this.context =context;
this.listener = listener;
}
#NonNull
#Override
public AdapterExplorePlace.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
SharedPreferences sharedPreferences = context.getSharedPreferences("file", MODE_PRIVATE);
starColor = sharedPreferences.getInt("starColor", 0);
startextColor = sharedPreferences.getInt("startextColor", 0);
currentPage = sharedPreferences.getString("currentPage", "");
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_explore_place,parent,false);
mAuth = FirebaseAuth.getInstance();
pinRef = FirebaseDatabase.getInstance().getReference("pinData").child(mAuth.getUid()).child(currentPage);
return new AdapterExplorePlace.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AdapterExplorePlace.ViewHolder holder, int position) {
if(array.get(position).getThumbnail() == null){
holder.explorePlaceImage.setImageResource(R.drawable.defalut_place_image);
}
else{
Glide.with(context)
.load(array.get(position).getThumbnail())
.centerCrop()
.dontAnimate()
.into(holder.explorePlaceImage);
}
holder.explorePlaceRegion.setText(String.valueOf(array.get(position).getPlaceAddress()));
holder.explorePlaceCategory.setText(String.valueOf(array.get(position).getPlaceCategory()));
holder.explorePlaceName.setText(String.valueOf(array.get(position).getPlaceName()));
holder.explorePlaceStyle.setText(String.valueOf(array.get(position).getPlaceStyle()));
holder.explorePlaceVisitedMember.setText(String.valueOf(array.get(position).getMember()));
holder.explorePlaceStyle.setTextColor(starColor);
holder.timestamp=String.valueOf(array.get(position).getTimestamp());
Drawable styleDrawable = ContextCompat.getDrawable(context,R.drawable.rounded);
styleDrawable.setColorFilter(new PorterDuffColorFilter(starColor, PorterDuff.Mode.SRC_IN));
holder.explorePlaceStyle.setBackground(styleDrawable);
pinRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot pinCheckSnap : snapshot.getChildren()){
Log.d("####Icon Check", String.valueOf(String.valueOf(pinCheckSnap.getValue()).contains(holder.timestamp)));
if(String.valueOf(pinCheckSnap.getValue()).contains(holder.timestamp)){
holder.btnExplorePlacePin.setBackgroundResource(R.drawable.ic_scrap_active);
holder.btnExplorePlacePin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog(position);
}
});
break;
}
else {
holder.btnExplorePlacePin.setBackgroundResource(R.drawable.ic_scrap_inactive);
holder.btnExplorePlacePin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle args = new Bundle();
args.putString("timestamp", holder.timestamp);
Pin_BottomSheetDialog bottomSheet = new Pin_BottomSheetDialog();
bottomSheet .setArguments(args);
bottomSheet.show(((FragmentActivity)context).getSupportFragmentManager(), "pinBottomSheet");
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return array.size();
}
#Override
public void onButtonClicked(String text) {
}
public interface RecyclerViewClickListener{
void onClick(View v, int position);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView explorePlaceImage;
TextView explorePlaceRegion;
TextView explorePlaceCategory;
TextView explorePlaceName;
TextView explorePlaceStyle;
TextView explorePlaceVisitedMember;
String timestamp;
ImageButton btnExplorePlacePin;
AdapterView.OnItemClickListener onItemClickListener;
public ViewHolder(#NonNull View itemView) {
super(itemView);
explorePlaceImage =itemView.findViewById(R.id.explorePlaceImage);
explorePlaceRegion =itemView.findViewById(R.id.explorePlaceRegion);
explorePlaceCategory =itemView.findViewById(R.id.explorePlaceCategory);
explorePlaceName =itemView.findViewById(R.id.explorePlaceName);
explorePlaceStyle =itemView.findViewById(R.id.explorePlaceStyle);
explorePlaceVisitedMember =itemView.findViewById(R.id.explorePlaceVisitedMember);
btnExplorePlacePin =itemView.findViewById(R.id.btnExplorePlacePin);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
listener.onClick(itemView, getAdapterPosition());
}
void setItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
}
private void openDialog(final int position){
dialog = new DialogDeletePin(context,cancelListener, deleteListener);
dialog.setCancelable(true);
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.show();
}
View.OnClickListener cancelListener = new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
};
View.OnClickListener deleteListener = new View.OnClickListener() {
public void onClick(View v) {
//I need to know item position for deleting data.
Log.d("####dialog","click delete");
dialog.dismiss();
}
};
}
DeleteDialogPin
class DialogDeletePin extends Dialog {
private Button btnCancelDeletePin;
private Button btnDeletePin;
private View.OnClickListener cancelListener;
private View.OnClickListener deleteListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 다이얼로그 외부 화면 흐리게 표현
WindowManager.LayoutParams lpWindow = new WindowManager.LayoutParams();
lpWindow.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
lpWindow.dimAmount = 0.6f;
getWindow().setAttributes(lpWindow);
setContentView(R.layout.dialog_delte_pin);
btnCancelDeletePin = findViewById(R.id.btnCancelDeletePin);
btnCancelDeletePin.setOnClickListener(cancelListener);
btnDeletePin = findViewById(R.id.btnDeletePin);
btnDeletePin.setOnClickListener(deleteListener);
//클릭이벤트
}
public DialogDeletePin(Context context, View.OnClickListener canceltListener, View.OnClickListener deleteListener) {
super(context, android.R.style.Theme_Translucent_NoTitleBar);
this.cancelListener = canceltListener;
this.deleteListener = deleteListener;
}
}
Since your method private void openDialog(final int position) has the position information. One of the way you can do it is just by creating a class for deleteListemer (DeleteListenerWithItemPos) and then pass the position as an argument at the constructor.
An example of how to implement is shown as follows:
private void openDialog(final int position){
deleteListener = new DeleteListenerWithItemPos(position);
dialog = new DialogDeletePin(context,cancelListener, deleteListener);
dialog.setCancelable(true);
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.show();
}
View.OnClickListener deleteListener;
public static class DeleteListenerWithItemPos implements View.OnClickListener() {
private int itemPos;
public DeleteListenerWithItemPos(int itemPos){
this.itemPos = itemPos;
}
public void onClick(View v) {=
itemPos; //get itemPos here
Log.d("####dialog","click delete");
dialog.dismiss();
}
}

Notifydatasetchanged() is causing blinking within child recyclerview

I am having an extremely hard time trying to disable animations for a nested recyclerview whenever the parent recyclerview calls ondatasetchanged(). So some context a recyclerview that holds tinder-like swap cards and a nested recyclerview within each card to scroll through user images. After every swipe ondatasetchanged is called and causing a bad flickering within the nested recyclerview. I have tried to disabled the animations from both parent and child recyclerviews and pretty much anything I can think of at this point. The code below is my view holder for each card.
public class CardStackHolder extends RecyclerView.ViewHolder implements OnItemSwipePercentageListener {
ImageButton profileInfoBtn;
RecyclerView images_recyclerView;
PagerSnapHelper snapHelper;
ProfileImagesAdapter imagesAdapter;
String profileName;
TextView nameBox;
TextView ageBox;
TextView workBox;
List<String> list;
public CardStackHolder(final View itemView) {
super(itemView);
profileInfoBtn = (ImageButton) itemView.findViewById(R.id.ID_datingRecyclerView_profileInfoBtn);
profileInfoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//show profile info dialog
User_Info_Dialog dialog = User_Info_Dialog.getDialog(mHostId, mCurrentProfile.getGender(), mCurrentProfile.getOrientation(), mCurrentProfile.getInterestedIn(), mCurrentProfile.getIntro(), mCurrentProfile.getStatus());
dialog.show(getChildFragmentManager(), "");
}
});
nameBox = (TextView) itemView.findViewById(R.id.ID_datingRecyclerView_profile_name);
ageBox = (TextView) itemView.findViewById(R.id.ID_datingRecyclerView_profile_age);
images_recyclerView = (RecyclerView) itemView.findViewById(R.id.ID_datingRecyclerView_profileImagesRecyclerView);
RecyclerView.ItemAnimator animator = images_recyclerView.getItemAnimator();
((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
animator.setChangeDuration(0);
animator.setRemoveDuration(0);
images_recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(images_recyclerView);
workBox = (TextView) itemView.findViewById(R.id.ID_datingRecyclerView_profile_work);
}
public void onBind(Context context, User_Profile profile) {
getImages(profile.getProfileId());
profileName = profile.getFirst_name();
profileName = profileName.substring(0, 1).toUpperCase() + profileName.substring(1);
nameBox.setText(profileName);
ageBox.setText(profile.getAge());
String workStr = profile.getWork();
workStr = workStr.substring(0, 1).toUpperCase() + workStr.substring(1);
workBox.setText(workStr);
mCurrentProfile = profile;
}
public void getImages(String id) {
mFirebaseDatabase.getReference().child("profile_pictures").child(id).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
list = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.hasChild("dating_card_imagePath")) {
list.add(snapshot.child("dating_card_imagePath").getValue().toString());
}
}
imagesAdapter = new ProfileImagesAdapter(list);
imagesAdapter.setHasStableIds(true);
images_recyclerView.setAdapter(imagesAdapter);
} else {
// no images found for profile
imagesAdapter = new ProfileImagesAdapter();
imagesAdapter.setHasStableIds(true);
images_recyclerView.setAdapter(imagesAdapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onItemSwipePercentage(double percentage) {
//log percentage moved
//Log.d("Enchanted", Double.toString(percentage));
if (percentage > -0.20 && percentage < 0.20) {
swipeResultImageView.setVisibility(View.GONE);
} else if (percentage < 0.20) {
swipeResultImageView.setImageResource(R.drawable.ic_swipe_no_like);
swipeResultImageView.setVisibility(View.VISIBLE);
} else if (percentage > -0.20) {
swipeResultImageView.setImageResource(R.drawable.ic_swipe_like);
swipeResultImageView.setVisibility(View.VISIBLE);
}
}
}
code below is my adapter
//CardStack Adapter
class CardStackAdapter extends RecyclerView.Adapter<CardStackHolder> {
LayoutInflater mInflater;
List<User_Profile> profileList;
RecyclerView.RecycledViewPool ImagePool;
public CardStackAdapter(Context context, List<User_Profile> list) {
mInflater = LayoutInflater.from(context);
profileList = new ArrayList<>(list);
ImagePool = new RecyclerView.RecycledViewPool();
}
#Override
public CardStackHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item_dating_profile_card, parent, false);
return new CardStackHolder(view);
}
#Override
public void onBindViewHolder(final CardStackHolder holder, int position) {
holder.images_recyclerView.setRecycledViewPool(ImagePool);
profileList.get(position).setItemId(holder.getItemId());
holder.onBind(mContext, profileList.get(position));
}
public void removeTopItem() {
profileList.remove(0);
notifyDataSetChanged();
}
public void addItemToTop() {
profileList.add(0, mPreviousProfile);
notifyItemInserted(0);
}
public void updateProfileList(List<User_Profile> p) {
ImagePool.clear();
profileList.clear();
profileList.addAll(p);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public int getItemCount() {
return profileList.size();
}
#Override
public long getItemId(int position) {
return profileList.get(position).getItemId();
}
}
Why are you calling notifyDataSetChanged() inside removeTopItem()?
Using notifyDataSetChanged() recreate all views again. You can notify recyclerview in which position item removed.
public void removeTopItem() {
profileList.remove(0);
notifyItemRemoved(0);
}

How to remove a ViewPager item from Firebase?

I am creating an App with ViewPager (with 2 String elements: Model Class: Title and Content). I have a floating action button and I want when pressing a specific button, to delete that item from Firebase & ViewPager.
I tried in MyAdapter Class to remove from the list my current item [ modelList.remove(position)] and in TravelNotes to create a method for delete from Firebase database reference.removeEventListener(this); but I don't know where to call it.
public class MyAdapter extends PagerAdapter {
Context context;
List<Model> modelList;
LayoutInflater inflater;
public MyAdapter(Context context, List<Model> modelList) {
this.context = context;
this.modelList = modelList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return modelList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object o) {
return view == o;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
((ViewPager)container).removeView((View) object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, final int position) {
View view = inflater.inflate(R.layout.adapter,container,false);
TextView model_titlu = view.findViewById(R.id.titleTextView);
TextView model_continut = view.findViewById(R.id.contentTextView);
FloatingActionButton fab_delete = view.findViewById(R.id.fab_delete);
model_titlu.setText(modelList.get(position).getTitlu());
model_continut.setText(modelList.get(position).getContinut());
fab_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Model m = modelList.get(position);
modelList.remove(position);
notifyDataSetChanged();
//how to delete?
}
});
container.addView(view);
return view;
}
}
public class TravelNotes extends AppCompatActivity implements IFirebaseLoadDone, ValueEventListener {
ViewPager viewPager;
MyAdapter adapter;
DatabaseReference databaseReference;
IFirebaseLoadDone iFirebaseLoadDone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_data);
databaseReference = FirebaseDatabase.getInstance().getReference("Movie");
iFirebaseLoadDone = this;
loadModel();
viewPager = findViewById(R.id.viewPager);
viewPager.setPageTransformer(true,new DepthPageTransformer());
}
private void loadModel() {
databaseReference.addValueEventListener(this);
}
//where to use this method?
private void delete(){
databaseReference.removeValue();
}
#Override
public void onFirebaseLoadSuccess(List<Model> modelList) {
adapter = new MyAdapter(this,modelList);
viewPager.setAdapter(adapter);
}
#Override
public void onFirebaseLoadFailed(String message) {
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<Model> modelList = new ArrayList<>();
for(DataSnapshot modelSnapshot:dataSnapshot.getChildren())
modelList.add(modelSnapshot.getValue(Model.class));
iFirebaseLoadDone.onFirebaseLoadSuccess(modelList);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadDone.onFirebaseLoadFailed(databaseError.getMessage());
}
#Override
protected void onDestroy() {
databaseReference.removeEventListener(this);
super.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
databaseReference.addValueEventListener(this);
}
#Override
protected void onStop() {
databaseReference.removeEventListener(this);
super.onStop();
}
}
Could you please advice what should I change in the code for deleting a specific item from ViewPager & Firebase?
Here is what helped me, in MyAdapter Class:
final ArrayList<String> keyList = new ArrayList<>();
TravelNotesActivity.databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Log.e("TAG", "MyAdaptor :" + ds.getKey());
keyList.add(ds.getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
fab_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
modelList.remove(position);
notifyDataSetChanged();
TravelNotesActivity.databaseReference.child(keyList.get(position)).removeValue();
keyList.remove(position);
}
});

How to get RecyclerView's Clicked data Position to View Pager Swipe?

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

How to get the Key when i clicked the item on recyclerview?

I'm creating an application with search and recycler view.
Here is my search_adapter:
public class search_adapter extends RecyclerView.Adapter<search_adapter.SearchViewHolder> {
private Context context;
private DatabaseReference mDatabase;
ArrayList<String> fullNameList;
ArrayList<String> dDateList;
private OnItemClickListener mListener;
Snapshot snapshot;
public search_adapter(Context context, ArrayList<String> fullNameList, ArrayList<String> dDateList) {
this.context = context;
this.fullNameList = fullNameList;
this.dDateList = dDateList;
}
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class SearchViewHolder extends RecyclerView.ViewHolder{
CardView clickCard;
TextView full_Name;
TextView death_Date;
public SearchViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
full_Name = (TextView) itemView.findViewById(R.id.person_name);
death_Date = (TextView) itemView.findViewById(R.id.person_death);
clickCard = (CardView) itemView.findViewById(R.id.cardClick);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener !=null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
#Override
public search_adapter.SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater mInflater = LayoutInflater.from(context);
view = mInflater.inflate(R.layout.recyclerview_adapter,parent,false);
return new search_adapter.SearchViewHolder(view, mListener);
}
public void onBindViewHolder(SearchViewHolder holder, final int position) {
holder.full_Name.setText(fullNameList.get(position));
holder.death_Date.setText(dDateList.get(position));
}
#Override
public int getItemCount() {
return fullNameList.size();
}
In this class, i create the view for the recycler view with onclick listener
I also include an interface so that i can pass the position of the clicked item.
Here is my search_activity class:
public class SearchActivity extends AppCompatActivity implements search_adapter.OnItemClickListener{
private RecyclerView mPerson;
private EditText mFindField;
public DatabaseReference mDatabase;
ArrayList<String> fullNameList;
ArrayList<String> dDateList;
private search_adapter searchAdapter;
int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
//Database Access//
mDatabase = FirebaseDatabase.getInstance().getReference();
//Recycler View//
mPerson = (RecyclerView)findViewById(R.id.person_list);
mPerson.setHasFixedSize(true);
mPerson.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
mPerson.setLayoutManager(new GridLayoutManager(this,3));
mFindField = (EditText) findViewById(R.id.search_field);
fullNameList = new ArrayList<>();
dDateList = new ArrayList<>();
mFindField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if (!editable.toString().isEmpty()){
setAdapter(editable.toString());
} else {
fullNameList.clear();
dDateList.clear();
mPerson.removeAllViews();
}
}
});
}
private void setAdapter(final String searchedString) {
mDatabase.child("person").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
fullNameList.clear();
dDateList.clear();
mPerson.removeAllViews();
int counter = 0;
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
String full_name = snapshot.child("fullName").getValue(String.class);
String dDate = snapshot.child("dDate").getValue(String.class);
if (full_name.toLowerCase().contains(searchedString.toLowerCase())){
fullNameList.add(full_name);
dDateList.add(dDate);
counter++;
} else if (dDate.toLowerCase().contains(searchedString.toLowerCase())){
fullNameList.add(full_name);
dDateList.add(dDate);
counter++;
}
if (counter == 15)
break;
}
searchAdapter = new search_adapter(SearchActivity.this, fullNameList, dDateList);
mPerson.setAdapter(searchAdapter);
searchAdapter.setOnItemClickListener(SearchActivity.this);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//new search//
#Override
public void onItemClick(int position) {
}
this is where the passed position will go,
but my problem is, I don't know how to get the key of that passed position, I try using getRef like the others did but it's not working.
My goal is for the user to clicked a data on the recycler view, open a new intent, and view all of the details of that certain clicked data.
Please help.
You have a list of names and a list of dates in your adapter, in the same way you can generate and add a list of keys, and in the viewholder onBind method you can bind the key to a field in your viewholder. And instead of sending position in your on click listener you can send your key.

Categories

Resources