How to implement onClick in FirestoreRecyclerAdapter to open a new Fragment? - java

I am trying to implement OnClick in my recyclerview,but i failed miserably with all the searches how to solve this problem.
I want by clicking on my cardview to go to another activity/even better fragment with another expandable lists,but i can't even do this for now.
Any help is highly appreciated
MainActivity code
package com.oleg.firestoretest;
public static final String TAG = "FireLog";
private CollectionReference noteBookRef;
private FirebaseFirestore mFirestore;
private NoteAdapter adapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirestore = FirebaseFirestore.getInstance();
noteBookRef = mFirestore.collection("Notebook");
setupRecyclerView();
}
private void setupRecyclerView() {
Query query = noteBookRef.orderBy("priority", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Note> options = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query,Note.class)
.build();
adapter = new NoteAdapter(options);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
public Note() {
}
public Note(String title, String content, int priority) {
this.title = title;
this.content = content;
this.priority = priority;
}
public String getTitle() {
return title;
}
public String getContent() {
return content;
}
public int getPriority() {
return priority;
}
}
public class NoteAdapter extends FirestoreRecyclerAdapter<Note, NoteAdapter.NoteHolder> {
private Context mContext;
public NoteAdapter(#NonNull FirestoreRecyclerOptions<Note> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull NoteHolder noteHolder, int i, #NonNull Note note) {
noteHolder.title.setText(note.getTitle());
noteHolder.content.setText(note.getContent());
noteHolder.priority.setText(String.valueOf(note.getPriority()));
}
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_item,
parent, false);
return new NoteHolder(v);
}
class NoteHolder extends RecyclerView.ViewHolder {
TextView title;
TextView content;
TextView priority;
public NoteHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title_text);
content = itemView.findViewById(R.id.content_text);
priority = itemView.findViewById(R.id.priority_text);
}
}
}

Here the Code u need:
class NoteHolder extends RecyclerView.ViewHolder {
TextView title;
TextView content;
TextView priority;
CardView cardView;
public NoteHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title_text);
content = itemView.findViewById(R.id.content_text);
priority = itemView.findViewById(R.id.priority_text);
cardView = itemView.findViewById(R.id.cardView);
}
private void bind(){
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this, SecoundActivity.class);
startActivity(intent);
}
});
}
}

Fixed it with this code!!!
public NoteHolder(#NonNull final View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.cardview);
title = itemView.findViewById(R.id.title_text);
content = itemView.findViewById(R.id.content_text);
priority = itemView.findViewById(R.id.priority_text);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemView.getContext().startActivity(new Intent(itemView.getContext(),Empty.class));
}
});
}

Related

Show the latest item firest in Firebase ui Realtime database [duplicate]

I try to use the FirebaseUI-Realtime Database Android lib to simply display a data set in a viepager2 with recycler-view adapter
When I get the data, I got the oldest data first, and i need to show the latest first . So I need a reverse order. How i can do it in RecyclerView adapter?
MainActivity.java
public class MainActivity extends AppCompatActivity {
ViewPager2 viewPager2;
videoadapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
viewPager2 = (ViewPager2) findViewById(R.id.vpager);
FirebaseRecyclerOptions<videomodel> options = new FirebaseRecyclerOptions.Builder<videomodel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("videos"), videomodel.class).build();
adapter = new videoadapter(options);
viewPager2.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
}
videoadapter.java
public class videoadapter extends
FirebaseRecyclerAdapter<videomodel, videoadapter.myviewholder> {
private Context context;
private AppCompatActivity activity;
private Timer _timer = new Timer();
private double positionc;
private TimerTask check;
private ProgressBar progressbar11;
private ViewPager2 viewPager;
public videoadapter(#NonNull FirebaseRecyclerOptions<videomodel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull videomodel model) {
holder.setdata(model);
holder.simpleExoPlayer.prepare();
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_video_row, parent, false);
return new myviewholder(view);
}
#Override
public void onViewAttachedToWindow(videoadapter.myviewholder holder) {
super.onViewAttachedToWindow(holder);
holder.playerView.getPlayer().seekTo(0);
holder.playerView.getPlayer().setPlayWhenReady(true);
holder.playerView.getPlayer().prepare();
}
#Override
public void onViewDetachedFromWindow(videoadapter.myviewholder holder) {
super.onViewDetachedFromWindow(holder);
holder.playerView.getPlayer().setPlayWhenReady(false);
holder.playerView.getPlayer().stop();
}
class myviewholder extends RecyclerView.ViewHolder {
PlayerView playerView;
SimpleExoPlayer simpleExoPlayer;
LinearLayout sec_mid;
ProgressBar progressbar1;
DefaultTrackSelector trackSelector;
ImageView play,pause;
TextView title,desc;
public myviewholder(#NonNull View view) {
super(view);
playerView = (PlayerView) view.findViewById(R.id.statusSliderVideo);
sec_mid = (LinearLayout) view.findViewById(R.id.sec_controlvid1);
progressbar1 = (ProgressBar) view.findViewById(R.id.progressbar11);
play = (ImageView) view.findViewById(R.id.exo_play);
pause = (ImageView) view.findViewById(R.id.exo_pause);
title = (TextView) view.findViewById(R.id.textVideoTitle);
desc = (TextView) view.findViewById(R.id.textVideoDescription);
}
void setdata(videomodel obj) {
progressbar1.getProgressDrawable().setColorFilter(Color.WHITE, android.graphics.PorterDuff.Mode.SRC_IN);
progressbar1.setIndeterminate(true);
title.setText(obj.getTitle());
desc.setText(obj.getDesc());
// get data
Uri videoUri = Uri.parse(obj.getUrl());
simpleExoPlayer = new SimpleExoPlayer.Builder(playerView.getContext()).build();
playerView.setPlayer(simpleExoPlayer);
playerView.setKeepScreenOn(true);
MediaItem mediaItem = MediaItem.fromUri(videoUri);
simpleExoPlayer.setMediaItem(mediaItem);
simpleExoPlayer.prepare();
playerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View _view) {
if (simpleExoPlayer.isPlaying()) {
simpleExoPlayer.pause();
} else {
simpleExoPlayer.play();
}
}
});
simpleExoPlayer.addListener(new Player.Listener() {
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == Player.STATE_BUFFERING) {
progressbar1.setIndeterminate(true);
} else {
progressbar1.setIndeterminate(false);
}
if (playbackState == Player.STATE_ENDED) {
simpleExoPlayer.seekTo(0);
simpleExoPlayer.setPlayWhenReady(true);
}
}
});
Activity activity = new Activity();
check = new TimerTask() {
#Override
public void run() {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
progressbar1.setMax((int) simpleExoPlayer.getDuration());
progressbar1.setProgress((int) simpleExoPlayer.getCurrentPosition());
}
});
}
};
_timer.scheduleAtFixedRate(check, (int) (0), (int) (1));
}
}
}
videomodel
public class videomodel {
String desc,title,url;
public videomodel(String desc, String title, String url) {
this.desc = desc;
this.title = title;
this.url = url;
}
videomodel()
{
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}

Having problem to fetching file from firestore recycle view [duplicate]

This question already has an answer here:
Firebase Android ListView not being displayed
(1 answer)
Closed 1 year ago.
I am an android developer beginner, I am having a problem fetch files from firestore recycle view in the main activity but I can fetch files from fragments.
This is my main activity
public class FoodInfoActivity extends AppCompatActivity {
RecyclerView recyclerView1,recyclerView2;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference notebookRef;
private NoteAdapter adapter;
FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_info);
fAuth = FirebaseAuth.getInstance();
setUpRecyclerView();
}
private void setUpRecyclerView() {
notebookRef = db.collection("FoodInside");
Query query = notebookRef;
FirestoreRecyclerOptions<FoodAdapter> options = new FirestoreRecyclerOptions.Builder<FoodAdapter>()
.setQuery(query, FoodAdapter.class)
.build();
adapter = new NoteAdapter(options);
RecyclerView recyclerView = findViewById(R.id.fi);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
}
This is my Note adapter where i use model class to fetch file
public class NoteAdapter extends FirestoreRecyclerAdapter<FoodAdapter, NoteAdapter.NoteHolder> {
public NoteAdapter(#NonNull FirestoreRecyclerOptions<FoodAdapter> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull NoteHolder holder, int position, #NonNull FoodAdapter foodAdapter) {
holder.textViewTitle.setText(foodAdapter.getRestaurant());
holder.textViewDescription.setText(foodAdapter.getItem());
holder.textViewPriority.setText(String.valueOf(foodAdapter.getPrice()));
}
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_recycle_layout,
parent, false);
return new NoteHolder(v);
}
class NoteHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
TextView textViewDescription;
TextView textViewPriority;
public NoteHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.textView95a);
textViewDescription = itemView.findViewById(R.id.textView123a);
textViewPriority = itemView.findViewById(R.id.textView124a);
}
}
}
This is my adapter class ,
public class FoodAdapter {
String Restaurant;
String Item;
String Price;
String item_id;
public FoodAdapter() {
}
public FoodAdapter(String restaurant, String item, String price,String item_id) {
Restaurant = restaurant;
Item = item;
Price = price;
this.item_id = item_id;
}
public String getRestaurant() {
return Restaurant;
}
public void setRestaurant(String restaurant) {
Restaurant = restaurant;
}
public String getItem() {
return Item;
}
public void setItem(String item) {
Item = item;
}
public String getPrice() {
return Price;
}
public void setPrice(String price) {
Price = price;
}
public String getItem_id() {
return item_id;
}
public void setItem_id(String item_id) {
this.item_id = item_id;
}
}
Why it is not working in main activity but work fragment. I am just afraid. and tired...working on the project. so need solution of this problem
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
Add this line to main activity.

Implementation onClick in FirestoreRecyclerAdapter to open a new Activity

In my app I have a recyclerView with elements from a Firestore database. I want by clicking on an element in the recyclerView (which is inside a fragment) to pass the data of the element to another activity. I've tried several solutions but none seem to work and I'm stuck. Please help me.
Adapter Class
public class InfoElementAdapter extends FirestoreRecyclerAdapter<InfoElement, InfoElementAdapter.InfoElementHolder> {
String urlImg;
public InfoElementAdapter(#NonNull FirestoreRecyclerOptions<InfoElement> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull InfoElementHolder holder, int position, #NonNull InfoElement model) {
holder.textViewNomeRest.setText(model.getNome());
holder.textViewDescrRest.setText(model.getDescrizione());
urlImg = model.getUrlImg();
Glide.with(holder.itemView.getContext()).load(urlImg).into(holder.imageView);
}
#NonNull
#Override
public InfoElementHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_single, parent, false );
return new InfoElementHolder(v) ;
}
class InfoElementHolder extends RecyclerView.ViewHolder {
TextView textViewNomeRest;
TextView textViewDescrRest;
ImageView imageView;
public InfoElementHolder(#NonNull View itemView) {
super(itemView);
textViewNomeRest = itemView.findViewById(R.id.txt_v_nome);
textViewDescrRest = itemView.findViewById(R.id.txt_v_descrizione);
imageView = itemView.findViewById(R.id.imageV);
}
}
}
Fragment with the recyclerView
public class RestaurantFragment extends Fragment {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference restaurantRef = db.collection("restaurant_db");
private InfoElementAdapter adapter;
private View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_restaurant, container, false);
setUpRecyclerView();
return view;
}
private void setUpRecyclerView() {
Query query = restaurantRef.orderBy("nome", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<InfoElement> options = new FirestoreRecyclerOptions.Builder<InfoElement>()
.setQuery(query, InfoElement.class)
.build();
adapter = new InfoElementAdapter(options);
RecyclerView recyclerView = view.findViewById(R.id.firestore_list1);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(Tools.getGridSpanCount(getActivity()), StaggeredGridLayoutManager.VERTICAL));
recyclerView.addItemDecoration(new Tools.SpacingItemDecoration(Tools.getGridSpanCount(getActivity()), Tools.dpToPx(getActivity(), 4),true));
recyclerView.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
if (adapter != null) {
adapter.stopListening();
}
}
}
InfoElement Class
public class InfoElement {
private String nome;
private String descrizione;
private String urlImg;
public InfoElement() {
}
public InfoElement(String nome, String descrizione, String urlImg) {
this.nome = nome;
this.descrizione = descrizione;
this.urlImg = urlImg;
}
public void setNome(String nome) {
this.nome = nome;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
public String getUrlImg() {
return urlImg;
}
public void setUrlImg(String urlImg) {
this.urlImg = urlImg;
}
public String getNome() {
return nome;
}
public String getDescrizione() {
return descrizione;
}
}
You can change onBindViewHolder by setting up a click listener for the ViewHolder itemView, and add your data object with putExtra, and retrieve it with getIntent().getSerializableExtra at the target activity.
#Override
protected void onBindViewHolder(#NonNull InfoElementHolder holder, int position, #NonNull InfoElement model) {
holder.textViewNomeRest.setText(model.getNome());
holder.textViewDescrRest.setText(model.getDescrizione());
urlImg = model.getUrlImg();
Glide.with(holder.itemView.getContext()).load(urlImg).into(holder.imageView);
holder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent (v.getContext(), ActivityB.class);
intent.putExtra("MyData", myData);
startActivity(intent);
}
});
}
To retrieve the data at the target Activity
getIntent().getSerializableExtra("MyData");

There is no compilation error but when running the code clicking the comment button, it is not leading to the activity I want

I did the code below, used the adapter to show the list, and a button to add a comment to list item, it shows the logcat "ViewPostIme pointer 0 and ViewPostIme pointer 1", upon clicking the comment button.
Upon compilation it doesn't show any error, I tried to use many references via google but nothing works out.
My basic idea is to call the comment button with an associated list item to perform the comment activity.
Adapter class
public class PostsAdapter extends FirestoreRecyclerAdapter<PostsModel, PostsAdapter.PostsHolder> {
private OnItemClickListener listener;
private View.OnClickListener buttonListener;
private String id;
private static final String TAG = "DocSnippets";
public PostsAdapter(#NonNull FirestoreRecyclerOptions<PostsModel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull PostsHolder holder, int position, #NonNull PostsModel model) {
//retrieve the fields here
holder.textViewDescription.setText(model.getPostContent());
holder.textViewPriority.setText(String.valueOf(model.getSpinnerC()));
holder.textViewPriority.setText(String.valueOf(model.getTimestamp()));
}
#NonNull
#Override
public PostsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_list_layout,
parent, false);
return new PostsHolder(v);
}
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
}
public void setOnClickListener(OnClickListener postKey) {
}
class PostsHolder extends RecyclerView.ViewHolder {
//first declare here the elements to be displayed in the cardview.
TextView textViewTitle;
TextView textViewDescription;
TextView textViewPriority;
Button commentsbutton;
public PostsHolder(final View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.post_etPostTitle);
textViewDescription = itemView.findViewById(R.id.post_description);
textViewPriority = itemView.findViewById(R.id.post_time);
commentsbutton = itemView.findViewById(R.id.commenting_button);
commentsbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && buttonListener != null) {
buttonListener.onClick(itemView);
}
}
});
}
}
public interface OnClickListener
{
void OnClickListener(DocumentSnapshot documentSnapshot, int position);
}
public void setOnClickListener(View.OnClickListener onClickListener) {
this.buttonListener = onClickListener;
}
public interface OnItemClickListener {
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
}
Fragment Class
public class HomeFragment extends Fragment {
RelativeLayout mParent;
//FloatingActionButton addButton;
private static final String TAG = "DocSnippets";
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference PostsRef = db.collection("posts");
private PostsAdapter adapter;
private FirestoreRecyclerOptions options;
private FirebaseAuth mAuth;
private String mUserId, id;
private Button commentsbutton;
RecyclerView recyclerView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//just change the fragment_dashboard
//with the fragment you want to inflate
//like if the class is HomeFragment it should have R.layout.home_fragment
//if it is DashboardFragment it should have R.layout.fragment_dashboard
View view = inflater.inflate(R.layout.fragment_home, container, false);
final FragmentActivity c = getActivity();
LinearLayoutManager layoutManager = new LinearLayoutManager(c);
Query query = PostsRef.orderBy("timestamp", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<PostsModel> options = new FirestoreRecyclerOptions.Builder<PostsModel>()
.setQuery(query, PostsModel.class)
.build();
adapter = new PostsAdapter(options);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(c));
recyclerView.setAdapter(adapter);
commentsbutton = (Button) view.findViewById(R.id.commenting_button);
mParent =view.findViewById(R.id.relative_home);
mAuth = FirebaseAuth.getInstance();
mUserId = mAuth.getUid();
adapter.setOnItemClickListener(new PostsAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
PostsModel note = documentSnapshot.toObject(PostsModel.class);
id = documentSnapshot.getId();
String path = documentSnapshot.getReference().getPath();
Log.d(TAG, "String post Id is: " + id);
}
});
adapter.setOnClickListener(new PostsAdapter.OnClickListener() {
#Override
public void OnClickListener(DocumentSnapshot documentSnapshot, int position) {
PostsModel note = documentSnapshot.toObject(PostsModel.class);
id = documentSnapshot.getId();
String path = documentSnapshot.getReference().getPath();
Log.d(TAG, "String post Id is: " + id);
Intent toCommentActivity = new Intent(getContext(), CommentActivity.class);
toCommentActivity.putExtra("PostKey", id);
getContext().startActivity(toCommentActivity);
}
});
return view;
}
private String getTime(long timestamp){
long ts = timestamp*1000;
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
String time = sdf.format(new Date(ts));
return time;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}

RecyclerView OnClick to take to another Fragment

I am stuck with this error for a long time now, I am new to JAVA.
I want to click an item on the RecyclerView (currently on a fragment) that got populated from Firebase. Once I click on it, it should take me to the next fragment by parcing some data and also the position of the item.
Here is my adapter, CustomAdapter.java
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
public CustomAdapter(ArrayList<Userpost> data) {
this.data = data;
}
public interface OnItemClickListener{
void onItemClick(Userpost userpost, int activityNumber);
}
private ArrayList<Userpost> data;
private static final int ACTIVITY_NUM = 4;
private OnItemClickListener listener;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textViewName;
TextView textViewVersion;
SquareImageView imageView;
private final Context context;
public View mCardView;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
this.textViewName = (TextView) itemView.findViewById(R.id.textViewName);
this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
this.imageView = (SquareImageView) itemView.findViewById(R.id.imageView);
this.mCardView = itemView.findViewById(R.id.card_view);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(context, "Position is " +getAdapterPosition(),Toast.LENGTH_SHORT).show();
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
Log.d(TAG, "MyViewHolder: setting up adapter for profile fragment");
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_layout, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(itemView);
return myViewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int Position) {
Log.d(TAG, "onBindViewHolder: setting up adapter for profile fragment");
TextView textViewName = holder.textViewName;
TextView textViewVersion = holder.textViewVersion;
final ImageView imageView = holder.imageView;
textViewName.setText(data.get(Position).getPheading());
textViewVersion.setText(data.get(Position).getDescriptionpost());
Picasso.with(holder.imageView.getContext()).load(data.get(Position).getImage_path()).into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Recycle Click" + Position, Toast.LENGTH_SHORT).show();
listener.onItemClick(data.get(Position), ACTIVITY_NUM);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
}
Here's fragment, ProfileFragment.java
public class ProfileFragment extends Fragment {
private static final String TAG = "ProfileFragment";
private static final int ACTIVITY_NUM = 4;
//firebase stuff
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
// Recycler View Widgets
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
private static ArrayList<Userpost> data;
private static ArrayList<Integer> removedItems;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
gridView = (GridView) view.findViewById(R.id.gridView);
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
cardView = (CardView) view.findViewById(R.id.card_view);
toolbar = (Toolbar) view.findViewById(R.id.profileToolBar);
bottomNavigationView = (BottomNavigationViewEx) view.findViewById(R.id.bottomNavViewBar);
mContext = getActivity();
mFirebaseMethods = new FirebaseMethods(getActivity());
//Recycler View class
super.onCreate(savedInstanceState);
data = new ArrayList<Userpost>();
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
updateArrayList();
private void updateArrayList() {
Log.d(TAG, "updateArrayList: setting up for profile fragment");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_user_posts))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildAdded: explore fragment");
data.add(dataSnapshot.getValue(Userpost.class));
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Userpost model = dataSnapshot.getValue(Userpost.class);
final int index = getItemIndex(model);
data.set(index, model);
adapter.notifyItemChanged(index);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private int getItemIndex(Userpost user) {
Log.d(TAG, "getItemIndex: setting up for profile fragment");
int index = -1;
for (int i = 0; i < data.size(); i++) {
if (data.get(i).image_path.equals(user.image_path)) {
index = i;
break;
}
}
return index;
}
Userpost.java is the model here.
And here is the logcat:
java.lang.NullPointerException: Attempt to invoke interface method 'void sahhaj.com.myapp.CustomAdapter$OnItemClickListener.onItemClick(myap.com.myapp.models.Userpost, int)' on a null object reference
at sahhaj.com.sahhajapp.CustomAdapter$1.onClick(CustomAdapter.java:112)
at android.view.View.performClick(View.java:5721)
at android.view.View$PerformClick.run(View.java:22620)
Your OnItemClickListener listener attribute is never set, so it is Null.
Check where you initialize it, if ever.
Change your RecyclerView array adapter class constructor like below.
public CustomAdapter(ArrayList<Userpost> data, OnItemClickListener listener) {
this.data = data;
this.listener = listener;
}
And in your Fragment change the RecyclerView array adapter object initializing like below.
adapter = new CustomAdapter(data, new CustomAdapter.OnItemClickListener() {
#Override
public void onItemClick(Userpost userpost, int activityNumber) {
// do whatever you want to do
}
});
And that's it. Now run the code you'll get your desired output.
**Call in Get Api **
implementation "com.android.support:cardview-v7:28.0.0"
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
<uses-permission android:name="android.permission.INTERNET" />
android:usesCleartextTraffic="true"
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="#+id/customRecyclerView"
android:layout_height="match_parent"
/>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/coverImage"
android:layout_width="80dp"
android:layout_height="80dp" />
<TextView
android:id="#+id/title"
android:textSize="15dp"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
public interface ApiInterface
{
#GET("/photos")
Call<List<RetroPhoto>> getAllPhotos();
}
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RestApiClient {
private static Retrofit retrofit;
private static final String BASE_URL = "https://jsonplaceholder.typicode.com";
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public class RetroPhoto {
#SerializedName("albumId")
private Integer albumId;
#SerializedName("id")
private Integer id;
#SerializedName("title")
private String title;
#SerializedName("url")
private String url;
#SerializedName("thumbnailUrl")
private String thumbnailUrl;
public RetroPhoto(Integer albumId, Integer id, String title, String url, String thumbnailUrl) {
this.albumId = albumId;
this.id = id;
this.title = title;
this.url = url;
this.thumbnailUrl = thumbnailUrl;
}
public Integer getAlbumId() {
return albumId;
}
public void setAlbumId(Integer albumId) {
this.albumId = albumId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
}
private CustomAdapter adapter;
private RecyclerView recyclerView;
ProgressDialog progressDoalog;
progressDoalog = new ProgressDialog(MainActivity.this);
progressDoalog.setMessage("Loading....");
progressDoalog.show();
/*Create handle for the RetrofitInstance interface*/
ApiInterface service = RestApiClient.getRetrofitInstance().create(ApiInterface.class);
Call<List<RetroPhoto>> call = service.getAllPhotos();
call.enqueue(new Callback<List<RetroPhoto>>() {
#Override
public void onResponse(Call<List<RetroPhoto>> call, Response<List<RetroPhoto>> response) {
progressDoalog.dismiss();
generateDataList(response.body());
}
#Override
public void onFailure(Call<List<RetroPhoto>> call, Throwable t) {
progressDoalog.dismiss();
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}
/*Method to generate List of data using RecyclerView with custom adapter*/
private void generateDataList(List<RetroPhoto> photoList) {
recyclerView = findViewById(R.id.customRecyclerView);
adapter = new CustomAdapter(this, photoList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
private List<RetroPhoto> dataList;
private Context context;
public CustomAdapter(Context context,List<RetroPhoto> dataList){
this.context = context;
this.dataList = dataList;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
public final View mView;
TextView txtTitle;
private ImageView coverImage;
CustomViewHolder(View itemView) {
super(itemView);
mView = itemView;
txtTitle = mView.findViewById(R.id.title);
coverImage = mView.findViewById(R.id.coverImage);
}
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.custom_row, parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
holder.txtTitle.setText(dataList.get(position).getTitle());
Picasso.get().load(dataList.get(position).getThumbnailUrl()).into(holder.coverImage);
// Picasso.Builder builder = new Picasso.Builder(context);
// builder.downloader(new OkHttp3Downloader(context));
// builder.build().load(dataList.get(position).getThumbnailUrl())
// .placeholder((R.drawable.ic_launcher_background))
// .error(R.drawable.ic_launcher_background)
// .into(holder.coverImage);
}
#Override
public int getItemCount() {
return dataList.size();
}
}

Categories