Mediaplayer not pausing while switching fragment - java

I am new to android studio. Please help. I have an app with 3 fragments, one have list of video view using recycler adapter, one have list of image view, other have same list of video view as no 1 fragment. First and last fragment are using same adapter. The problem is that while switching fragmment from first one to second video keeps playing.
//fragment code
public class funny_moments extends Fragment {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("funnymomments");
ArrayList<funny_momments_row> data;
funny_momments_adapter adapter;
VideoView mVideoView;
View pos;
private RecyclerView mRecyclerView;
public funny_moments() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_funny_moments, container, false);
mRecyclerView =(RecyclerView) view.findViewById(R.id.recylerview);
mVideoView = (VideoView)view.findViewById(R.id.videoView);
data = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot videoSnapshot : dataSnapshot.getChildren()){
funny_momments_row video = new funny_momments_row(videoSnapshot.child("like").getValue().toString(),videoSnapshot.child("url").getValue().toString());
data.add(video);
}
adapter = new funny_momments_adapter(getActivity(),data,mCommunication);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// Inflate the layout for this fragment
return view;
}
#Override
public void onPause() {
adapter.mMediaPlayer.pause();
super.onPause();
}
//adapter code
public class funny_momments_adapter extends RecyclerView.Adapter<funny_momments_adapter.funnyVideoHolder> {
private final LayoutInflater inflator;
List<funny_momments_row> data = Collections.emptyList();
communication mCommunicator;
Context mContext;
public funny_momments_adapter(Context context, List<funny_momments_row> data, communication communicator){
inflator = LayoutInflater.from(context);
this.data = data;
this.mContext = context;
mCommunicator = communicator;
}
#NonNull
#Override
public funnyVideoHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = inflator.inflate(R.layout.funny_momments_row,viewGroup,false);
funnyVideoHolder funnyHolder = new funnyVideoHolder(view,mCommunicator);
return funnyHolder;
}
#Override
public void onBindViewHolder(#NonNull final funnyVideoHolder viewHolder, int i) {
funny_momments_row current = data.get(i);
VideoView f1 = viewHolder.mVideoView;
viewHolder.mVideoView.setVideoURI(Uri.parse(current.getUrl()));
viewHolder.likecount.setText(current.getLike());
viewHolder.mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mp) {
FragmentManager manager = ((AppCompatActivity)mContext).getSupportFragmentManager();
Fragment f = manager.findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + 2);
mMediaPlayer = mp;
viewHolder.playpause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
mp.pause();
}
else {
mp.start();
}
}
});
}
});
viewHolder.playpause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (viewHolder.mVideoView.isPlaying()) {
viewHolder.mVideoView.requestFocus();
viewHolder.mVideoView.pause();
}
else {
viewHolder.mVideoView.requestFocus();
viewHolder.mVideoView.start();
}
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public class funnyVideoHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
VideoView mVideoView;
ImageView likeicon;
TextView likecount;
ImageView playpause;
communication mCommunication;
public funnyVideoHolder(#NonNull View itemView,communication communication) {
super(itemView);
mVideoView = (VideoView)itemView.findViewById(R.id.videoView);
likeicon = (ImageView)itemView.findViewById(R.id.likeicon);
likecount = (TextView)itemView.findViewById(R.id.likecount);
playpause = (ImageView)itemView.findViewById(R.id.playpause);
mCommunication = communication;
}
#Override
public void onClick(View v) {
mCommunication.respond(v);
}
}
}
I want to stop playback while switching fragment.

When you fragment from one fragment to another, previous fragment's onPause() is called (giving you the opportunity to pause the video) and new fragment's onResume() function is called. If new fragment was not already created, onStart,onCreate() etc method are called before onResume() is called.
What you can do, when a fragment gets out of focus, thus called onPause(), pause your video, and when a fragment get in focus, you can resume it if it was already create.
Fragment Lifecycle (source)

Related

How to setOnClickListener in adapter using RecyclerView to display inside fragment

I cannot access the ID of the item to view it in ToastMessage, or even store it in the database (use Room DataBase)
I have tried but the message does not appear
I need the reference ID to use for database storage and complete the process for storing the shopping cart
itemAdapter.java
public class itemAdapter extends RecyclerView.Adapter<itemAdapter.ItemViewHolder> {
private Context context;
private ArrayList<Items> arrayList;
private AdapterView.OnItemClickListener listener;
public itemAdapter(Context context, ArrayList<Items> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
return new ItemViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
holder.name.setText(arrayList.get(position).getItemName());
holder.desc.setText(arrayList.get(position).getItemDesc());
holder.price.setText(arrayList.get(position).getItemPrice());
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemIid(),Toast.LENGTH_SHORT);
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemPrice(),Toast.LENGTH_SHORT);
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
TextView name, desc, price;
ImageView remove, add;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.tvName);
desc = itemView.findViewById(R.id.tvDesc);
price = itemView.findViewById(R.id.tvPrice);
remove = itemView.findViewById(R.id.btnDelete);
add = itemView.findViewById(R.id.btnAdd);
}
}
}
MealsFragment.java
public class MealsFragment extends Fragment {
public MealsFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
itemAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meals, container, false);
}
#Override
public void onViewCreated( View view, Bundle savedInstanceState) {
ArrayList<Items> ItemsList = (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getContext().getApplicationContext())
.getAppDatabase()
.getDao()
.getItems("meals");
recyclerView = view.findViewById(R.id.rvMeals);
RecyclerView.LayoutManager manager = new LinearLayoutManager(
getContext(), RecyclerView.VERTICAL, false);
recyclerView.setLayoutManager(manager);
adapter = new itemAdapter(getContext(), ItemsList);
recyclerView.setAdapter(adapter);
}
}
Try the following instead
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemIid(),Toast.LENGTH_SHORT).show();
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemPrice(),Toast.LENGTH_SHORT).show();
}
});
The static method makeText of Toast is used to create the Toast object and show() method on the Toast object is used to display the Toast

Strange behavior of OnItemClickListener inside RecyclerView inside Fragment

Need help with android app (java)
My app starts with SplashActivity. During it I`m getting json via retrofit request and after successfull response I fill my DB
SplashActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
ISplashInteractor splashInteractor = new SplashInteractor();
moviePresenter = new MoviePresenter(this, splashInteractor);
moviePresenter.initDB();
}
after DB successfully loaded automatically starts MovieListActivity
public class MovieListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment allMoviesFragment = new AllMoviesFragment();
String tag = "MovieList";
transaction.replace(R.id.main_container, allMoviesFragment, tag);
transaction.commit();
}
}
and at once list of movies loads inside inner fragment AllMoviesFragment(inside recyclerView). till this point everything is ok.
now I set onRecyclerViewItemClickListener - it must open another fragment inside MovieListActivity but instead of this - my app restarts from begining and I observe loading of SpalshActivity again(I put progressbar during request) and again my RecyclerView...
my RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private List<MovieDetails> movieList;
private OnRecyclerViewItemClickListener onRecyclerViewItemClickListener;
public RecyclerViewAdapter(List<MovieDetails> movieList) {
this.movieList = movieList;
}
public void setOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener onRecyclerViewItemClickListener){
this.onRecyclerViewItemClickListener = onRecyclerViewItemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.simple_selectable_list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
MovieDetails movieDetails = (movieList.get(position));
holder.name.setText(movieDetails.getTitle());
holder.year.setText(String.valueOf(movieDetails.getReleaseYear()));
}
#Override
public int getItemCount() {
if (movieList == null)
return 0;
return movieList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView year;
public ViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.movie_name);
year = itemView.findViewById(R.id.release_year);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onRecyclerViewItemClickListener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
onRecyclerViewItemClickListener.onRecyclerViewItemClick(position);
}
}
}
});
}
}
public interface OnRecyclerViewItemClickListener {
void onRecyclerViewItemClick(int position);
}
}
my AllMoviesFragment
public class AllMoviesFragment extends Fragment implements RecyclerViewAdapter.OnRecyclerViewItemClickListener {
private static final String CURR_MOVIE = "Current Movie";
private static final String TAG = "MSApp";
List<MovieDetails> movieList;
RecyclerView recyclerView;
public AllMoviesFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
movieList = App.getAppInstance().getDatabaseInstance().getMovieDao().getAllMovies();
movieList.sort(new Comparator<MovieDetails>() {
#Override
public int compare(MovieDetails o1, MovieDetails o2) {
return o2.getReleaseYear() - o1.getReleaseYear();
}
});
View resultView = inflater.inflate(R.layout.fragment_all_movies, container, false);
recyclerView = resultView.findViewById(R.id.recycler_view);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(movieList);
adapter.setOnRecyclerViewItemClickListener(AllMoviesFragment.this);
recyclerView.setAdapter(adapter);
return resultView;
}
#Override
public void onRecyclerViewItemClick(int position) {
MovieDetails choosenMovie = movieList.get(position);
FragmentManager fragmentManager = getFragmentManager();
Fragment movieDetailsFragment = new MovieDetailsFragment();
Bundle args = new Bundle();
args.putParcelable(CURR_MOVIE, choosenMovie);
movieDetailsFragment.setArguments(args);
String tag = "MovieDetails";
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, movieDetailsFragment, tag);
transaction.addToBackStack(tag);
transaction.commit();
}
}
sorry for long post. I dont know how to cut it
I use App class for db access if it is important
#AkakiKapanadze
you was almost right
I didnot see the error message because it disappeared less 1 second
and class MovieDetailsFragment
after I remove binder of ButterKnife all work... I dont know WHY - I always use Butterknife inside Fragments

Changes to RecyclerView led to this Error :E/RecyclerView: No adapter attached; skipping layout

After implementing all the Recyclerview codes, i still end up with this Error :E/RecyclerView: No adapter attached; skipping layout.
Im not sure if it is because of the layout or where it is placed...
I changed the location of it multiple times and i had to revert back to an older version as some of the solutions i found on the internet caused it to crash.
public class MainMenu extends AppCompatActivity implements
IFirebaseLoadListener {
private Context context;
private List<ItemData> itemDataList;
private List<ItemGroup> dataList;
AlertDialog dialog;
IFirebaseLoadListener iFirebaseLoadListener;
RecyclerView my_recycler_view;
DatabaseReference myData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
myData = FirebaseDatabase.getInstance().getReference("Data");
dialog = new SpotsDialog.Builder().setContext(this).build();
iFirebaseLoadListener = this;
//View
my_recycler_view = (RecyclerView)findViewById(R.id.my_recyclr_view);
my_recycler_view.setHasFixedSize(true);
my_recycler_view.setLayoutManager(new LinearLayoutManager(this));
getFirebaseData();
}
private void getFirebaseData () {
dialog.show();
myData.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange (#NonNull DataSnapshot dataSnapshot) {
List<ItemGroup> itemGroups =new ArrayList<>();
for(DataSnapshot groupSnapShot:dataSnapshot.getChildren()){
ItemGroup itemGroup = new ItemGroup();
itemGroup.setHeaderTitle(groupSnapShot.child("headerTitle").getValue (String.class));
GenericTypeIndicator<ArrayList<ItemData>> genericTypeIndicator =new GenericTypeIndicator<ArrayList<ItemData>>(){};
itemGroup.setListItem(groupSnapShot.child("listItem").getValue(genericTypeIndicator));
itemGroups.add(itemGroup);
}
iFirebaseLoadListener.onFirebaseLoadSuccess(itemGroups);
}
#Override
public void onCancelled (#NonNull DatabaseError databaseError) {
iFirebaseLoadListener.onFirebaseLoadFailed(databaseError.getMessage());
}
});
}
#Override
public void onFirebaseLoadSuccess(List<ItemGroup> itemGroupList) {
MyItemGroupAdapter adapter = new
MyItemGroupAdapter(this,itemGroupList);
my_recycler_view.setAdapter(adapter);
dialog.dismiss();
}
#Override
public void onFirebaseLoadFailed(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
I have 2 other pages for my Adapters, "MyItemAdapter" and "MyItemGroupAdapter"
but im not sure why it isnt able to call them
My Adapters:
public class MyItemAdapter extends RecyclerView.Adapter<MyItemAdapter.MyViewHolder> {
private Context context;
private List<ItemData> itemDataList;
public MyItemAdapter(Context context, List<ItemData> itemDataList) {
this.context = context;
this.itemDataList = itemDataList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(context).inflate(R.layout.layout_item,viewGroup,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
myViewHolder.txt_item_title.setText(itemDataList.get(i).getName());
Picasso.get().load(itemDataList.get(i).getArt()).into(myViewHolder. img_item);
myViewHolder.setiItemClickListener(new IItemClickListener() {
#Override
public void onItemClickListener(View view, int position) {
Toast.makeText(context, ""+itemDataList.get(i).getName(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {return (itemDataList != null ? itemDataList.size() : 0);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txt_item_title;
ImageView img_item;
IItemClickListener iItemClickListener;
public void setiItemClickListener(IItemClickListener iItemClickListener) {
this.iItemClickListener = iItemClickListener;
}
public MyViewHolder(#NonNull View itemView) {
super(itemView);
txt_item_title = itemView.findViewById(R.id.name);
img_item = itemView.findViewById(R.id.art);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
iItemClickListener.onItemClickListener(view,getAdapterPosition());
}
}
}
There's no data for your RecyclerView to display when the view is created.
Inside of your onCreate you should create your adapter with empty or null data then call setAdapter() on your RecyclerView using the empty adapter. Later, you can update the adapter with new data and call notifyDataSetChanged() on your adapter to refresh it.

How to put a RecyclerView into a Fragment?

I am still new for the android development. Currently, I am trying to show a RecyclerView within a Fragment. I tried to show the RecyclerView without using Fragment and it worked fine. But when it come to using Fragment, nothing is shown.
Here is the MainActivity containing the Fragment:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ButterKnife.bind(this);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
mViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.fragment_container, missionListFragment).addToBackStack(null).commit();
}
And the Fragment's onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_mission_list, container, false);
//ButterKnife.bind(rootview);
mRecycler = (RecyclerView) rootView.findViewById(R.id.recycler);
mFirestore = FirebaseFirestore.getInstance();
mQuery = mFirestore.collection("COLLECTION_NAME").limit(LIMIT);
if (mQuery == null) {
Log.w(TAG, "No query, not initializing RecyclerView. Created data on server.");
}
mAdapter = new RecyclerViewAdapter(mQuery, this) {
#Override
protected void onDataChanged() {
}
#Override
protected void onError(FirebaseFirestoreException e) {
// Show a snackbar on errors
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Error: check logs for info.", Snackbar.LENGTH_LONG).show();
}
};
mRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecycler.setAdapter(mAdapter);
return rootView;
}
With the RecyclerViewAdapter:
public class RecyclerViewAdapter extends FirestoreAdapter<RecyclerViewAdapter.ViewHolder> {
private static final int UNAVAILABLE = 0, AVAILABLE = 1;
public interface OnItemSelectedListener {
void onItemSelected(DocumentSnapshot item);
}
private OnItemSelectedListener mListener;
public RecyclerViewAdapter(Query query, OnItemSelectedListener listener) {
super(query);
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new ViewHolder(inflater.inflate(R.layout.item, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(getSnapshot(position), mListener);
}
static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.view1)
TextView view1;
#BindView(R.id.view2)
TextView view2;
#BindView(R.id.view3)
TextView view3;
#BindView(R.id.view4)
TextView view4;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(final DocumentSnapshot snapshot,
final OnItemSelectedListener listener) {
Item item = snapshot.toObject(Item.class);
Resources resources = itemView.getResources();
view1.setText(item.getfield1());
view2.setText(Integer.toString(item.getfield2()));
if(item.getfield3() == AVAILABLE)
view3.setText("Available");
else
view3.setText("Unavailable");
view4.setText(item.getfield4().toString());
// Click listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onItemSelected(snapshot);
}
}
});
}
}
}
As you can notice above, I am getting data from the Firebase and displaying them as a RecyclerView. But I don't think it is the problem of empty query data, so please help.
It could be that data from firebase is not being retrieved, hence there is no content for recyclerview to display. Please check if your firebase connection is working fine and you are retrieving something from it

Set onclicklistener in recyclerview

My adaptor class:
public class Adaptor extends RecyclerView.Adapter<Adaptor.Holder>{
private ArrayList<Winkel> winkels;
private LayoutInflater inflater;
private ImageView icon;
private ItemCLickCallback itemCLickCallback;
public interface ItemCLickCallback {
void onItemClick(int p);
void onSecItemClick(int p);
}
public void setItemCLickCallback(final ItemCLickCallback itemCLickCallback1){
;this.itemCLickCallback = itemCLickCallback;
}
public Adaptor (ArrayList<Winkel> winkels,Context c){
this.inflater = LayoutInflater.from(c);
this.winkels = winkels;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_item,parent,false);
return new Holder(view);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
Winkel winkel = winkels.get(position);
holder.title.setText(winkel.getNaam());
if (winkel.isFavourtite()){
holder.icon.setImageResource(R.drawable.ic_star_black_18dp);
}
else{
holder.icon.setImageResource(R.drawable.ic_star_border_black_18dp);
}
}
#Override
public int getItemCount() {
return winkels.size();
}
class Holder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView title;
private View container;
private ImageView icon;
public Holder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
container = itemView.findViewById(R.id.cont_item_root);
icon = (ImageView) itemView.findViewById(R.id.im_item_icon_secondary);
icon.setOnClickListener(this);
container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.cont_item_root){
itemCLickCallback.onItemClick(getAdapterPosition());
}
else{
itemCLickCallback.onSecItemClick(getAdapterPosition());
}
}
}
}
#Override
public void onClick(View v) {
}
}
}
Code where it gets implemented (my issue is here at adaptor.setItemClickCallback(context)
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Adaptor adaptor = new Adaptor(winkels,context);
recyclerview.setLayoutManager(new LinearLayoutManager(context));
recyclerview.addItemDecoration(new VerticalSpace(30));
recyclerview.setAdapter(adaptor);
adaptor.setItemCLickCallback(context);
}
Called from fragment overview:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_overview, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycle);
ODKortrijkWebservice webs = new ODKortrijkWebservice(this.getActivity(),mRecyclerView);
webs.execute();
return view;
}
How do I set the context for ItemCLickCallback(this)? It should be context (at least I think so?) because that's what gets passed from the fragment but I can't seem to figure out how to get this to work, so some help would be appreciated. Basically I want to add onclicklisteners for every item in my recyclerview, and the recyclerview is created by using data from a webservice, hence why the adaptor class is called from the class where I get the data from the web service, which gets excecuted in my fragment. Thank you.
I recommend you to make ODKortrijkWebservice.Callback like following.
In your ODKortrijkWebservice:
public class ODKortrijkWebservice extends AsyncTask<...> {
private Callback mCallback;
public interface Callback {
void onSuccess(ArrayList<Winkel> winkels);
}
public ODKortrijkWebservice(Context context, Callback callback) {
...
mCallback = callback;
...
}
#Override
protected void onPostExecute(Void aVoid) {
...
mCallback.onSuccess(winkels);
}
}
In your Fragment:
public class YourFragment extends Fragment implements ODKortrijkWebservice.Callback, Adaptor.ItemCLickCallback {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_overview, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycle);
ODKortrijkWebservice webs = new ODKortrijkWebservice(this.getActivity(), this);
webs.execute();
return view;
}
#Override
public void onSuccess(ArrayList<Winkel> winkels) {
Adaptor adaptor = new Adaptor(winkels, getContext());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mRecyclerView.addItemDecoration(new VerticalSpace(30));
mRecyclerView.setAdapter(adaptor);
adaptor.setItemCLickCallback(this);
}
#Override
public void onItemClick(int p) {
}
#Override
public void onSecItemClick(int p) {
}
}
Here,
You need to create one interface at RecycleView.Adapter<>
private static OnItemClickListener listener;
// Define the listener interface
public interface OnItemClickListener {
void onItemClick(View itemView, int position);
}
// Define the method that allows the parent activity or fragment to define the listener
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
send require details with interface method
public class ViewHolder extends RecyclerView.ViewHolder{
TextView header_title;
public ViewHolder(final View itemView) {
super(itemView);
txt_country_name = (TextView)itemView.findViewById(R.id.header_title);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Triggers click upwards to the adapter on click
if (listener != null)
listener.onItemClick(itemView, getLayoutPosition());
}
});
}
}
call adapter listener
ListAdapter listAdapter;
listAdapter.setOnItemClickListener(new listAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(getActivity(), position+ " was clicked!", Toast.LENGTH_SHORT).show();
}
});

Categories