Can't Call activity function from adapter - java

I would like to call activity function from Adapter. I am trying something like this:
((MainActivity)mCtx).SampleVoid();
But i've got the error: java.lang.ClassCastException: android.app.Application cannot be cast to
public void SampleVoid(){
Toast.makeText(this,"Testowa metoda",Toast.LENGTH_LONG).show();
}

That error is happening because you are trying to cast the Application context to the Activity context. First of all, I wouldn't recommend you sending and storing context inside the adapter. I would recommend you to create an interface for communication back to the Activity at specific action from the adapter. For example:
Activity code:
SomeAdapter adapter = new SomeAdapter();
adapter.setOnAdapterActionListener(new OnAdapterActionListener() {
#Override
public void onSomeAdapterAction() {
Toast.makeText(this,"Testowa metoda",Toast.LENGTH_LONG).show();
}
});
Adapter code:
public class SomeAdapter extends ArrayAdapter<String> { // extend from the same adapter that you are extending now.
private OnAdapterActionListener onAdapterActionListener;
public SomeAdapter(#NonNull Context context, int resource, #NonNull List<String> objects) {
super(context, resource, objects);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onAdapterActionListener != null) {
onAdapterActionListener.onSomeAdapterAction();
}
}
});
return view;
}
public void setOnAdapterActionListener(OnAdapterActionListener onAdapterActionListener) {
this.onAdapterActionListener = onAdapterActionListener;
}
}
interface OnAdapterActionListener {
void onSomeAdapterAction();
}

You can pass the activity through the Adapter constructor.
Generally you do this through interfaces
public class MainActivity extends AppCompatActivity implements MAdapter.Listener {
private MAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MAdapter(this);
}
#Override
public void onClick(int position) { }
}
Then
public class MAdapter {
private Listener listener;
MAdapter(Listener listener){
this.listener = listener;
}
interface Listener {
void onClick(int position);
}
}

Related

Adding click listener to two buttons in PagerAdpater CardViews

In my project, I have a PagerAdapter to inflate CardViews that hold text objects created by the user.
On each CardView I have edit and delete buttons to access methods to do with the ArrayList holding the text objects.
I have coded an interface in my adapter to handle clicks made within the text object creation activity. However, my instatiateItem method in my adapter is now showing on the #Override annotation "Method does not override method from its superclass". When I remove the #Override annotation I get an error in my Logcat:
java.lang.UnsupportedOperationException: Required method instantiateItem was not overridden
How do I implement a click listener for buttons on a CardView in a PagerAdapter?
Adapter code:
public class CreateAdapter extends PagerAdapter {
private List<PdfPage> pagesList;
private LayoutInflater layoutInflater;
private Context context;
private onItemClickListener mListener;
public interface onItemClickListener{
//click method for edit button
void onEditClick(int position);
//click method for delete button
void onDeleteClick(int position);
}
public void setOnItemClickListener(onItemClickListener listener){
mListener = listener;
}
public CreateAdapter(List<PdfPage> pagesList, Context context) {
this.pagesList = pagesList;
this.context = context;
}
#Override
public int getCount() {
return pagesList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view.equals(object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, final int position, final onItemClickListener listener) {
layoutInflater = LayoutInflater.from(context);
View view = null;
if(pagesList.get(position).getPageType() == "Text") {
view = layoutInflater.inflate(R.layout.create_text_cardview, container, false);
TextView inputText = view.findViewById(R.id.inputTextView);
ImageButton editButton = view.findViewById(R.id.imageButtonEdit);
ImageButton deleteButton = view.findViewById(R.id.imageButtonDelete);
//if this works, see 12:30 of video for image getter
inputText.setText(pagesList.get(position).getPageText());
//edit click listener
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position2 = pagesList.indexOf(pagesList.get(position));
listener.onEditClick(position2);
}
}
});
//delete click listener
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position3 = pagesList.indexOf(pagesList.get(position));
listener.onDeleteClick(position3);
}
}
});
container.addView(view, 0);
}
//put else statement here for image cardView
assert view != null;
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View)object);
}
Activity code:
public class CreateActivity extends AppCompatActivity {
ViewPager viewPager;
CreateAdapter createAdapter;
List<PdfPage> pdfPageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
pdfPageList = new ArrayList<>();
createAdapter = new CreateAdapter(pdfPageList, this);
viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(createAdapter);
viewPager.setPadding(130, 0, 130, 0);
}
#Override
protected void onStart() {
super.onStart();
createAdapter = new CreateAdapter(pdfPageList, this);
viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(createAdapter);
viewPager.setPadding(130, 0, 130, 0);
createAdapter.setOnItemClickListener(new CreateAdapter.onItemClickListener() {
#Override
public void onEditClick(int position) {
}
#Override
public void onDeleteClick(int position) {
pdfPageList.remove(position);
}
});
}
Your instantiateItem method does not override from it's superclass because you added an extra argument final onItemClickListener listener.
As you are using the same clickListener for all entries and passing the item position as an argument, I suggest that you pass the onItemClickListener in the adapter constructor, or just set it via
public void setOnItemClickListener(onItemClickListener listener){
mListener = listener;
}
Adapter code:
public class CreateAdapter extends PagerAdapter {
private List<PdfPage> pagesList;
private LayoutInflater layoutInflater;
private Context context;
private onItemClickListener mListener;
public interface onItemClickListener{
//click method for edit button
void onEditClick(int position);
//click method for delete button
void onDeleteClick(int position);
}
public void setOnItemClickListener(onItemClickListener listener){
mListener = listener;
}
public CreateAdapter(List<PdfPage> pagesList, Context context) {
this.pagesList = pagesList;
this.context = context;
}
#Override
public int getCount() {
return pagesList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view.equals(object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, final int position) {
layoutInflater = LayoutInflater.from(context);
View view = null;
if(pagesList.get(position).getPageType() == "Text") {
view = layoutInflater.inflate(R.layout.create_text_cardview, container, false);
TextView inputText = view.findViewById(R.id.inputTextView);
ImageButton editButton = view.findViewById(R.id.imageButtonEdit);
ImageButton deleteButton = view.findViewById(R.id.imageButtonDelete);
//if this works, see 12:30 of video for image getter
inputText.setText(pagesList.get(position).getPageText());
//edit click listener
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mlistener != null){
int position2 = pagesList.indexOf(pagesList.get(position));
mlistener.onEditClick(position2);
}
}
});
//delete click listener
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mlistener != null){
int position3 = pagesList.indexOf(pagesList.get(position));
mlistener.onDeleteClick(position3);
}
}
});
container.addView(view, 0);
}
//put else statement here for image cardView
assert view != null;
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View)object);
}
And your Activity code could stay as it is.

Passing data from RecyclerView.Adapter to fragment onClick

I'm trying to figure out how to get data from a clicked item in a RecyclerView to a listview in a Fragment. I can't seem to figure out how to do this, as I can't get my bundle to work.
I've tried various solutions offered here on Stackoverflow, but none of them have worked. I have managed to get the info from the recyclerview, but I am stuck trying to figure out how I can pass it to the fragment. Can someone please help me?
The Adapter class:
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> {
private Context context;
ArrayList<FoodActivity> list;
public FoodAdapter(ArrayList<FoodActivity> list){
this.list = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.foods.setText(list.get(position).getName());
holder.carbo.setText(list.get(position).getCarbohydrates());
holder.protein.setText(list.get(position).getProtein());
holder.fats.setText(list.get(position).getFats());
//Get items from recyclerview when user clicks them. Then send them to FoodFragment
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String foods = list.get(position).getName();
String carbo = list.get(position).getCarbohydrates();
String protein = list.get(position).getProtein();
String fats = list.get(position).getFats();
Toast.makeText(v.getContext(), "test: " + foods, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView foods, carbo, fats, protein;
public ViewHolder(View itemView) {
super(itemView);
carbo = itemView.findViewById(R.id.carbo);
protein = itemView.findViewById(R.id.protein);
fats = itemView.findViewById(R.id.fats);
foods = itemView.findViewById(R.id.food);
}
}
}
The Fragment where the data comes from:
public class TrackingFragment extends Fragment {
DatabaseReference databaseReference;
ArrayList<FoodActivity> list;
RecyclerView recyclerView;
SearchView searchView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tracking, container, false);
databaseReference = FirebaseDatabase.getInstance().getReference().child("foods");
recyclerView = view.findViewById(R.id.rv);
searchView = view.findViewById(R.id.searchFood);
return view;
}
#Override
public void onStart() {
super.onStart();
if(databaseReference != null){
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()){
list.add(ds.getValue(FoodActivity.class));
}
FoodAdapter adapter = new FoodAdapter(list);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
if(searchView != null){
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
}
}
private void search(String str){
ArrayList<FoodActivity> searchList = new ArrayList<>();
for(FoodActivity object : list){
if(object.getName().toLowerCase().contains(str.toLowerCase())){
searchList.add(object);
}
}
FoodAdapter foodAdapter = new FoodAdapter(searchList);
recyclerView.setAdapter(foodAdapter);
}
}
And the class where it needs to go:
public class FoodFragment extends Fragment {
ImageButton addFood;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food, container, false);
addFood = view.findViewById(R.id.addFood);
addFood.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container, new TrackingFragment());
fr.addToBackStack(null).commit();
}
});
return view;
}
}
The most simple is to add variables you need to your activity, set their values with onClick() and then retrieve data in other fragment:
in activity:
String foods;
public String getFoods() {
return foods;
}
public void setFoods(String foods) {
this.foods = foods;
}
in adapter:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((YourActivity)getActivity()).setFoods("Any value");
}
});
in destination fragment:
String foods = ((YourActivity)getActivity()).getFoods();
Add an interface to your adapter as follow
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> {
interface OnClickListener {
void onClick(FoodActivity clickedItem);
}
private OnClickListener mCallback;
private ArrayList<FoodActivity> list;
public FoodAdapter(ArrayList<FoodActivity> list){
this.list = list;
}
public void setOnClickListener(OnClickListener callback) {
mCallback = callback;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.foods.setText(list.get(position).getName());
holder.carbo.setText(list.get(position).getCarbohydrates());
holder.protein.setText(list.get(position).getProtein());
holder.fats.setText(list.get(position).getFats());
//Get items from recyclerview when user clicks them. Then send them to FoodFragment
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallback != null)
mCallback.onClick(list.get(position));
}
});
}
#Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView foods, carbo, fats, protein;
public ViewHolder(View itemView) {
super(itemView);
carbo = itemView.findViewById(R.id.carbo);
protein = itemView.findViewById(R.id.protein);
fats = itemView.findViewById(R.id.fats);
foods = itemView.findViewById(R.id.food);
}
}
}
Android sometimes is a little complicated, when it involves the full stack:
01 RecyclerView Adapter
/** 01. Some Adapter */
public class SomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private WeakReference<Context> mContext;
/** Constructor */
public SomeAdapter(#NonNull Context context) {
this.mContext = new WeakReference<>(context);
}
#NonNull
protected Context getContext() {
return this.mContext.get();
}
/** Call to Activity from within the adapter. */
private void someMethod() {
SomeActivity activity = (SomeActivity) getContext();
synchronized(activity) {activity.showLoginDialog();}
}
}
02 AppCompatActivity
/** 02. Some Activity */
public class SomeActivity extends AppCompatActivity {
#Nullable
private BaseFragment currentFragment = null;
/** Constructor */
public SomeActivity() {}
public void setCurrentFragment(Fragment fragment) {
this.currentFragment = fragment;
}
/** Call to the current Fragment. */
public void someMethod() {
if (currentFragment != null) {
currentFragment.someMethod();
}
}
}
03 Fragment
/** Some Fragment */
public class SomeFragment extends Fragment {
/** Constructor */
public SomeFragment() {}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
((BaseActivity) context).setCurrentFragment(this);
}
#Override
public void onDetach() {
super.onDetach();
((BaseActivity) getActivity()).setCurrentFragment(this);
}
}
To get your data from FoodAdapter to TrackingFragment, you can add TrackingFragment (or an interface it implements, ideally) as a parameter to the FoodAdapter constructor, then use that instance to forward your ViewHolder clicks to TrackingFragment for handling.
To get your data from TrackingFragment to FoodFragment, use the setTargetFragment/onActivityResult pattern for fragment <-> fragment communication. This answer has an example: https://stackoverflow.com/a/13733914/3238938

ArrayList not displaying in RecyclerView but no errors shown

I've have an arraylist that is not displaying in RecyclerView. The arraylist has data but my RecyclerView Adapter shows no error, nor is my fragment activity showing no errors. I am at a complete loss where the programming error is. The getItemCount seems correct, the holder seems correct and the Fragment seems to be correct but I know there is a mistake somewhere. Here is my code:
Fragment:
public class TestFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
List<PlanetData> items = new ArrayList<>();
RecyclerView mRecyclerView;
PlanetRecyclerViewAdapter adapter;
private OnFragmentInteractionListener mListener;
public TestFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
planetList();
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_test, container, false);
mRecyclerView = (RecyclerView)view.findViewById(R.id.planet_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(),DividerItemDecoration.VERTICAL));
adapter = new PlanetRecyclerViewAdapter(items, mRecyclerView.getContext());
mRecyclerView.setAdapter(adapter);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private List<PlanetData> planetList() {
List<PlanetData> planetvalues = new ArrayList<>();
planetvalues.add(new com.ksburneytwo.planetmathtest.PlanetData("12"));
planetvalues.add(new com.ksburneytwo.planetmathtest.PlanetData(Double.toString(Mercury.getMercuryRA())));
planetvalues.add(new com.ksburneytwo.planetmathtest.PlanetData(Double.toString(Venus.getVenusRA())));
planetvalues.add(new com.ksburneytwo.planetmathtest.PlanetData(Double.toString(Moon.getMoonRA())));
planetvalues.add(new com.ksburneytwo.planetmathtest.PlanetData(Double.toString(Mars.getMarsRA())));
planetvalues.add(new com.ksburneytwo.planetmathtest.PlanetData(Double.toString(Jupiter.getJupiterRA())));
planetvalues.add(new com.ksburneytwo.planetmathtest.PlanetData(Double.toString(Saturn.getSaturnRA())));
planetvalues.add(new com.ksburneytwo.planetmathtest.PlanetData(Double.toString(Uranus.getUranusRA())));
planetvalues.add(new com.ksburneytwo.planetmathtest.PlanetData(Double.toString(Neptune.getNeptuneRA())));
planetvalues.add(new com.ksburneytwo.planetmathtest.PlanetData(Double.toString(Pluto.getPlutoRA())));
System.out.println("This is Arraylist:" + planetvalues);
return planetvalues;
}
}
Here is the PlanetData class:
public class PlanetData {
private String PlanetRA;
public PlanetData(String PlanetRA) {
this.PlanetRA = PlanetRA;
}
#Override
public String toString() {
return PlanetRA;
}
public String getPlanetRA (){
return PlanetRA;
}
public void setPlanetRA(String PlanetRA){
this.PlanetRA = PlanetRA;
}
}
Here is my RecyclerView Adapter:
public class PlanetRecyclerViewAdapter extends RecyclerView.Adapter<PlanetRecyclerViewAdapter.ViewHolder> {
private List<PlanetData> mPlanetDataList;
Context mContext;
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView currentRA;
public ViewHolder(View itemView) {
super(itemView);
currentRA = (TextView) itemView.findViewById(R.id.planet_location);
}
}
public PlanetRecyclerViewAdapter(List<PlanetData> mPlanetDataList, Context mContext){
this.mPlanetDataList = mPlanetDataList;
this.mContext = mContext;
}
#Override
public PlanetRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.planet_recycler_item,parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder( PlanetRecyclerViewAdapter.ViewHolder holder, int position) {
holder.currentRA.setText(mPlanetDataList.get(position).getPlanetRA());
}
#Override
public int getItemCount() {
return mPlanetDataList.size();
}
}
I don't see you ever actually adding anything to the items list.
You call planetList() in onCreateView(), but you aren't using the result of it, and planetList() doesn't affect items in any way: it makes its own ArrayList and returns that.
Either remove planetValues from the planetList() method and reference items directly:
private void planetList() { //changed signature to "void"
items.add(...);
items.add(...);
//etc
}
Or set the result of planetList() to items when you call it:
items.addAll(planetList());
You haven't populated items.
items = planetList();

Adapter won't update

I am trying to display some items on a recycleView inside a fragment. The items come from another fragment. I first create the recycleView with a empty arrayList but then when a button is pressed, data is sent through interface and a method populates the ArrayList. I have debugged this the whole day and is working perfect, when I hit the button it logs the size of the ArrayList has gone up to one.
I was reading that I have to notify my adapter when the list changes, so I tried using notifyDataSetChange(), notifyItemInserted(dataReceived.size() -1) but neither seem to work out. whenever I check adapter.getItemCount() it throws me 0, even though the arraylist says throws 1.
here's my code inside the fragment Receiving the data:
public class FavoriteFragment extends Fragment {
private OnFragmentInteractionListener mListener;
RecyclerView myRecyclerView;
public ArrayList<RecycleViewItem> dataReceived;
public MyFavoriteAdapter adapter;
public FavoriteFragment() {
}
public void setDataReceived(ArrayList<RecycleViewItem> dataReceived){
this.dataReceived = dataReceived;
Log.d("INTERFACE", "Data received by the FavoriteFragment!!!!" + " " + this.dataReceived.get(0).getCardName());
for(int i = 0; i < dataReceived.size(); i++) {
//THIS LINE RETURNS A 1
Log.d("INTERFACE", "Items inside the dataReceived: " + dataReceived.size());
//NEITHER WORKED
//adapter.notifyItemInserted(dataReceived.size() -1);
//adapter.notifyDataSetChanged();
//THIS LINE WILL KEEP ON RETURNING 0
Log.d("INTERFACE", "Items inside the list inside the adapter: " + adapter.getItemCount());
}
}
public static FavoriteFragment newInstance() {
FavoriteFragment fragment = new FavoriteFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dataReceived = new ArrayList<>();
adapter = new MyFavoriteAdapter(dataReceived);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_favorite, container, false);
myRecyclerView = (RecyclerView) view.findViewById(R.id.recycleView);
myRecyclerView.setHasFixedSize(true);
LinearLayoutManager myLayoutManager = new LinearLayoutManager(getActivity());
myLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
if (myRecyclerView != null) {
myRecyclerView.setAdapter(adapter);
}
myRecyclerView.setLayoutManager(myLayoutManager);
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
this is the adapter:
public class MyFavoriteAdapter extends RecyclerView.Adapter<MyViewHolder>{
private ArrayList<RecycleViewItem> list = new ArrayList<RecycleViewItem>();
InterfaceListItemClickListener sender = null;
public MyFavoriteAdapter(ArrayList<RecycleViewItem> list) {
this.list = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_item_favorite, parent, false);
MyViewHolder holder = new MyViewHolder(view, sender);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
if(list.size() >= 1) {
holder.favoriteImageView.setImageResource(list.get(position).getImageResourceID());
holder.favoriteTextView.setText(list.get(position).getCardName());
}
}
#Override
public int getItemCount() {
return list.size();
}
}
Your adapter has a private variable list, and this must be modified for adapter.notifyDataSetChanged() to have any effect.
Here is your method:
public void setDataReceived(ArrayList<RecycleViewItem> dataReceived){
this.dataReceived = dataReceived;
...
}
Assigning the parameter dataReceived to your fragment's this.dataReceived doesn't affect your adapter's list in any way. Rather, you could do something like this instead:
public void setDataReceived(ArrayList<RecycleViewItem> dataReceived){
adapter.list.addAll(dataReceived);
...
}
You may have to make your adapter's list variable public, or expose it via a getter:
public ArrayList<RecycleViewItem> getList() {
return list
}
Or even add a method that can add items to it:
public void addAll(ArrayList<RecycleViewItem> items) {
list.addAll(items);
}
public void setDataReceived(ArrayList dataReceived){
this.dataReceived.addAll(dataReceived);
....
}
Do not recreate list

Add clickableItems to Listview

I wanna add clickableItems to Listview. But my problem is, that my class extands Fragment and i can not do that easily. Additionaly i wanna by clicking the item change the page to another page. My code is:
public class MyCoursesFragment extends Fragment implements OnItemClickListener, OnClickListener {
private static final String TAG = MyCoursesFragment.class.getName();
private ListView listView;
String listItem[]={"Vl1", "VL2"};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.mycourses_layout, container, false);
listView = (ListView) layout.findViewById(R.id.Course);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent intent = new Intent(getActivity().getBaseContext(), DocumentFragment.class);
intent.putExtra("id", "1");
listView.getContext().startActivity(intent);
FrontPageFragment.this.startActivity(intent);
}
});
return layout;
}
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
}
}
can you guys pls help me.
THX
Change this line because your context is wrong:
listView.getContext().startActivity(intent);
FrontPageFragment.this.startActivity(intent);
You need to start a new activity in the following way:
Intent intent = new Intent(getActivity(),DocumentFragment.class);
startActivity(intent);
What you can to do is set up a callback Interface and control everything from your parent Activity.
Your Activity should implement the interface and your Fragment should call those methods when your View or list item gets clicked.
Something along the lines of:
interface
public interface OnListItemClickCallback {
public void onListItemShortClick(View view);
public void onListItemLongClick(View view);
}
Fragment
public MyListFragment extends ListFragment
implements OnItemClickListener, OnItemLongClickListener {
private OnListItemClickCallback clickCallback;
...
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
// make sure the parent activity implements your interface
try
{
clickCallback = (OnListItemClickCallback) activity;
}
catch (ClassCastException e)
{
Log.e(TAG, "Parent Activity doesn't implement OnListItemClickCallback");
throw new ClassCastException(activity.toString()
+ " must implement OnListItemClickCallback");
}
}
#Override
public View onCreateView(Bundle b) {
...
getListView().setOnListItemClickListener(this):
getListView().setOnListItemLongClickListener(this):
}
#Override
public void onItemClick(...) {
clickCallback.onListItemShortClick(view)
}
// same idea for long click if you want it
}
Activity
public MyActivity extends Activity
implements OnListItemClickCallback {
...
#Override
public void onListItemShortClick(View view) {
// do something like replace your fragment
}
#Override
public void onListItemLongClick(View view) {
// do something else
}
}

Categories

Resources