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
Related
since several days I try to handle data in recyclerview in viewpager2. The viewpager has an adapter managing the data in recyclerview. But everything I try to do seems to not work. Maybe I missundersteand the purpose or something. I hope you can help me.
This activity manages the viewpager and its adapter. It sends the data to the inner recyclerview:
public class AudioFilePanel extends AppCompatActivity
{
private String currentTab;
private ViewPagerAdapter adapter;
private ViewPager2 viewPager;
private TabLayout tabLayout;
private Map<String, List<String>> content;
private String path;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_file_panel);
viewPager = findViewById(R.id.view_pager2);
tabLayout = findViewById(R.id.tabs);
Button addFilesByTag = findViewById(R.id.add_files_with_tag);
if (null == currentTab)
{
currentTab = "music";
}
content = listByTag();
adapter = new ViewPagerAdapter(getApplicationContext(), new ArrayList<>(content.values()));
viewPager.setAdapter(adapter);
new TabLayoutMediator(tabLayout, viewPager,
(tab, position) -> tab.setText(content.keySet().toArray()[position].toString())).attach();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
#Override
public void onTabSelected(TabLayout.Tab tab)
{
currentTab = tab.getText().toString();
}
#Override
public void onTabUnselected(TabLayout.Tab tab)
{
}
#Override
public void onTabReselected(TabLayout.Tab tab)
{
}
});
addFilesByTag.setOnClickListener(l ->
{
Intent fileBrowser = new Intent(AudioFilePanel.this, FileBrowser.class);
startActivityForResult(fileBrowser, 1);
});
}
private void updateViweData()
{
content = listByTag();
adapter = new ViewPagerAdapter(getApplicationContext(), new ArrayList<>(content.values()));
viewPager.setAdapter(adapter);
}
private Map<String, List<String>> listByTag()
{
Map<String, List<String>> result = new HashMap<>();
DirectoryDao dao = new DirectoryDao(getApplicationContext());
String[] categories = {"music", "ambience", "effect"};
for (String category : categories)
{
List<String> directories =
dao.getDirectoriesForCategory(category).stream().map(Directory::getPath).collect(Collectors.toList());
result.put(category, directories);
}
return result;
}
This is the view pager adapter. It takes the data directly from the activity and should trigger data update in the inner recyclerview every time when an item will be clicked. See line 118-128:
public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewHolder>
{
private List<List<String>> filesListsByCategory;
private LayoutInflater mInflater;
private Context ctx;
private ItemListAdapter adapter;
private List<String> categoryFiles;
public ViewPagerAdapter(Context context, List<List<String>> data)
{
this.mInflater = LayoutInflater.from(context);
this.filesListsByCategory = data;
this.ctx = context;
}
#NotNull
#Override
public ViewHolder onCreateViewHolder(#NotNull ViewGroup parent, int viewType)
{
return new ViewHolder(mInflater.inflate(R.layout.item_viewpager, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position)
{
FileBrowserService fbs = new FileBrowserService();
categoryFiles = filesListsByCategory.get(position);
adapter = new ItemListAdapter(categoryFiles, new ItemList.OnListFragmentInteractionListener()
{
#Override
public void onListFragmentInteraction(String item)
{
categoryFiles = fbs.getFiles(categoryFiles.get(position));
categoryFiles.add(0, "previous directory");
updateUi(adapter, holder);
}
});
holder.myView.setAdapter(adapter);
}
private void updateUi(ItemListAdapter adapter, ViewHolder holder)
{
adapter.notifyDataSetChanged();
holder.myView.setAdapter(adapter);
}
#Override
public int getItemCount()
{
return filesListsByCategory.size();
}
class ViewHolder extends RecyclerView.ViewHolder
{
RecyclerView myView;
RelativeLayout relativeLayout;
ViewHolder(View itemView)
{
super(itemView);
myView = itemView.findViewById(R.id.my_list);
myView.setLayoutManager(new LinearLayoutManager(ctx));
relativeLayout = itemView.findViewById(R.id.container);
}
}
}
It is the adapter of inner recyclerview. It represents just a list of elements:
public class ItemListAdapter extends RecyclerView.Adapter<ItemListAdapter.ViewHolder>
{
private List<String> files;
private final OnListFragmentInteractionListener mListener;
public ItemListAdapter(List<String> items, OnListFragmentInteractionListener listener)
{
files = items;
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_item, parent, false));
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
holder.file = files.get(position);
holder.mContentView.setText(files.get(position));
holder.mView.setOnClickListener(v ->
{
if (null != mListener)
{
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onListFragmentInteraction(holder.file);
}
});
}
#Override
public int getItemCount()
{
return files.size();
}
class ViewHolder extends RecyclerView.ViewHolder
{
private final View mView;
private final TextView mContentView;
private String file;
private ViewHolder(View view)
{
super(view);
mView = view;
mContentView = view.findViewById(R.id.content);
}
}
}
The last thing is the ItemList fragment.
public class ItemList extends Fragment
{
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
/**
* Mandatory empty constructor for the fragment manager to instantiate the fragment (e.g. upon screen orientation
* changes).
*/
public ItemList()
{
}
// TODO: Customize parameter initialization
#SuppressWarnings("unused")
public static ItemList newInstance(int columnCount)
{
ItemList fragment = new ItemList();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Context context)
{
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener)
{
mListener = (OnListFragmentInteractionListener) context;
} else
{
throw new RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getArguments() != null)
{
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_item_list, container, false);
if (view instanceof RecyclerView)
{
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1)
{
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else
{
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new ItemListAdapter(getArguments().getStringArrayList("list"), mListener));
}
return view;
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this fragment to allow an interaction in this
* fragment to be communicated to the activity and potentially other fragments contained in that activity.
* <p/>
* See the Android Training lesson
* <a href= "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener
{
// TODO: Update argument type and name
void onListFragmentInteraction(String item);
}
}
When I click, the data won't update. What I would like to have is:
This is what you have to do
add this method into your adapter class
public void updateData(List<String> filesList, int flag) {
if (flag == 0) { //append
for (int i = 0; i < filesList.size(); i++) {
files.add(messageList.get(i));
notifyItemInserted(getItemCount());
}
} else { //clear all
files.clear();
notifyDataSetChanged();
}
}
Then whenever you need to update recycle view call like below
mItemListAdapter.updateData(yourNewListOfItems, 0);
if you need to reset recycle-view call like below
mItemListAdapter.updateData(null, 1);
Add notifyDataSetChanged() in your adapter
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
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();
I'm a beginner on Android development and I was trying to make a simple app that has a recycleView inside a fragment using cardViews and when you click the like button inside of any of the items inside the list, the app then should send this item to another fragment called FavoriteFragment (which also contains recycleView) and display it here.
I tried to use an interface to do this, but whenever I click one of the like buttons, my activity does not receive the information (I tried to Log.d a message inside the method and is not being displayed)
here is the code for each of this:
My interface, what I am trying to use to pass the data from countries fragment-> adapter -> viewholder -> activity -> favorite fragment
public interface InterfaceListItemClickListener {
void listItemClickAction(ArrayList properties);
}
my CountriesFragment, which is the fragment that holds the first RecycleView:
public class CountriesFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
ArrayList<RecycleViewItem> listCountries = new ArrayList<>();
String names[] = {"Thailand", "Venezuela", "Sweden"};
int images[] = {R.drawable.thailand, R.drawable.venezuela, R.drawable.sweden};
RecyclerView myRecyclerView;
InterfaceListItemClickListener sender;
public CountriesFragment() {
// Required empty public constructor
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
sender = (InterfaceListItemClickListener) getActivity();
}
public static CountriesFragment newInstance(String param1, String param2) {
CountriesFragment fragment = new CountriesFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
initializeList();
}
public void initializeList(){
listCountries.clear();
for(int i = 0; i < names.length; i++){
RecycleViewItem item = new RecycleViewItem();
item.setCardName(names[i]);
item.setImageResourceID(images[i]);
item.setIsFav(0);
item.setIsTurned(0);
listCountries.add(item);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_countries, container, false);
myRecyclerView = (RecyclerView) view.findViewById(R.id.recycleView);
myRecyclerView.setHasFixedSize(true);
LinearLayoutManager myLayoutManager = new LinearLayoutManager(getActivity());
myLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
ListsForFragments.populateCountriesList();
if (ListsForFragments.countriesList.size() > 0 & myRecyclerView != null) {
myRecyclerView.setAdapter(new MyAdapter(ListsForFragments.countriesList, sender));
}
myRecyclerView.setLayoutManager(myLayoutManager);
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 {
void onFragmentInteraction(Uri uri);
}
}
My Adapter class:
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder>{
private ArrayList<RecycleViewItem> list = new ArrayList<RecycleViewItem>();
InterfaceListItemClickListener sender = null;
public MyAdapter(ArrayList<RecycleViewItem> list, InterfaceListItemClickListener sender) {
this.list = list;
this.sender = sender;
}
public MyAdapter(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_items, parent, false);
MyViewHolder holder = new MyViewHolder(view, sender);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.titleTextView.setText(list.get(position).getCardName());
holder.coverImageView.setImageResource(list.get(position).getImageResourceID());
holder.coverImageView.setTag(list.get(position).getImageResourceID());
}
#Override
public int getItemCount() {
return list.size();
}
}
My viewHolder class:
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView titleTextView;
public ImageView coverImageView;
public ImageView likeImageView;
public ImageView shareImageView;
public ImageView favoriteImageView;
public TextView favoriteTextView;
private ArrayList goesToFavourites = new ArrayList();
public MyViewHolder(View itemView, final InterfaceListItemClickListener sender) {
super(itemView);
titleTextView = (TextView) itemView.findViewById(R.id.titleTextView);
coverImageView = (ImageView) itemView.findViewById(R.id.coverImageView);
likeImageView = (ImageView) itemView.findViewById(R.id.likeImageView);
shareImageView = (ImageView) itemView.findViewById(R.id.shareImageView);
favoriteImageView = (ImageView) itemView.findViewById(R.id.imageView_favorite);
favoriteTextView = (TextView) itemView.findViewById(R.id.textView_name_favorite);
if (likeImageView != null) {
likeImageView.setTag(R.drawable.ic_like);
likeImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int id = (int) likeImageView.getTag();
if (id == R.drawable.ic_like) {
likeImageView.setTag(R.drawable.ic_liked);
likeImageView.setImageResource(R.drawable.ic_liked);
if(sender != null) {
getGoesToFavourites().add(coverImageView);
getGoesToFavourites().add(likeImageView);
sender.listItemClickAction(getGoesToFavourites());
}
} else {
likeImageView.setTag(R.drawable.ic_like);
likeImageView.setImageResource(R.drawable.ic_like);
}
}
});
}
}
public ArrayList getGoesToFavourites() {
return goesToFavourites;
}
public void setGoesToFavourites(ArrayList goesToFavourites) {
this.goesToFavourites = goesToFavourites;
}
}
My favoriteFragment class, the one receiving the information:
public class FavoriteFragment extends Fragment {
private OnFragmentInteractionListener mListener;
RecyclerView myRecyclerView;
ArrayList receiver = new ArrayList();
public FavoriteFragment() {
}
public void receiveData(ArrayList receiver){
this.receiver = receiver;
}
public static FavoriteFragment newInstance() {
FavoriteFragment fragment = new FavoriteFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#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 (receiver != null & myRecyclerView != null) {
myRecyclerView.setAdapter(new MyAdapter(receiver));
}
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);
}
}
finally, my MainActivity, the bridge:
public class MainActivity extends AppCompatActivity implements
HostFragment.OnFragmentInteractionListener,
CountriesFragment.OnFragmentInteractionListener,
CitiesFragment.OnFragmentInteractionListener,
PlacesFragment.OnFragmentInteractionListener,
FavoriteFragment.OnFragmentInteractionListener,
ViewPagerFragment.OnFragmentInteractionListener,
InterfaceListItemClickListener{
FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fm = getSupportFragmentManager();
//if this is the first time we are running the app
if(savedInstanceState == null){
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content, new ViewPagerFragment());
transaction.commit();
}
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void listItemClickAction(ArrayList list) {
FavoriteFragment favorite = (FavoriteFragment)
fm.findFragmentById(R.id.favorite);
favorite.receiveData(list);
Log.d("INTERFACE", "Data received!" + list);
}
}
If any extra information needed let me know and I'll provide.
EDIT: so trying to debug, I found out that the InterfaceListItemClickListener that MyViewHolder is a null, but not sure why...
EDIT 2: so I changed some things, inside My CountriesFragment:
I deleted the OnActivityCreated method and initialized the interface rather inside the onCreate like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeList();
sender = (InterfaceListItemClickListener) getActivity();
}
Now with this change, I was able to know that the findFragmentById inside my MainActivity is returning me a null. now, the way I am displaying this fragment is by using a ViewPager fragment which holds both fragments. this looks like this:
public class ViewPagerFragment extends Fragment {
private OnFragmentInteractionListener mListener;
public static ViewPager viewPager;
public ViewPagerFragment() {
// Required empty public constructor
}
public static ViewPagerFragment newInstance() {
ViewPagerFragment fragment = new ViewPagerFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setTitle(null);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
CustomAdapter adapter = new CustomAdapter(getChildFragmentManager()); //getChildFragmentManager
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
return view;
}
public class CustomAdapter extends FragmentPagerAdapter {
public CustomAdapter(FragmentManager fm){
super(fm);
}
//position tells the program what fragment we are currently on/displaying
public Fragment getItem(int position){
switch (position){ //notice we don't use breaks on each case, due to the return statement on each.
case 0:return CountriesFragment.newInstance();
case 1: return FavoriteFragment.newInstance();
default: return FavoriteFragment.newInstance();
}
}
public int getCount(){
return 2;
}
}
// 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);
}
}
How would I proceed in this case to finish passing the information?
OnCreateView() is called before OnActivityCreate() thats why your sender is null.Moreover,you must avoid setting or creating any objects in the OnCreateView(). Your fragment should be like this
public class CountriesFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
ArrayList<RecycleViewItem> listCountries = new ArrayList<>();
String names[] = {"Thailand", "Venezuela", "Sweden"};
int images[] = {R.drawable.thailand, R.drawable.venezuela, R.drawable.sweden};
RecyclerView myRecyclerView;
InterfaceListItemClickListener sender;
public CountriesFragment() {
// Required empty public constructor
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
sender = (InterfaceListItemClickListener) getActivity();
myRecyclerView.setHasFixedSize(true);
LinearLayoutManager myLayoutManager = new LinearLayoutManager(getActivity());
myLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
ListsForFragments.populateCountriesList();
if (ListsForFragments.countriesList.size() > 0 & myRecyclerView != null) {
myRecyclerView.setAdapter(new MyAdapter(ListsForFragments.countriesList, sender));
}
myRecyclerView.setLayoutManager(myLayoutManager);
}
public static CountriesFragment newInstance(String param1, String param2) {
CountriesFragment fragment = new CountriesFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
initializeList();
}
public void initializeList(){
listCountries.clear();
for(int i = 0; i < names.length; i++){
RecycleViewItem item = new RecycleViewItem();
item.setCardName(names[i]);
item.setImageResourceID(images[i]);
item.setIsFav(0);
item.setIsTurned(0);
listCountries.add(item);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_countries, container, false);
myRecyclerView = (RecyclerView) view.findViewById(R.id.recycleView);
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 {
void onFragmentInteraction(Uri uri);
}
I have seen a lot of similar questions about this issue but I couldn't find any solution to this:
I have three fragments in a TabLayout handled by a ViewPager and I have a ListView in the third Fragment which is not displaying any items after I change the orientation of the screen. I have tried to set a background color to the convertView in the ArrayAdapter to see if it was displayed and indeed it is not being displayed after I change the orientation. But it's weird because in my First Fragment where I use the same ArrayAdapter for another ListView everything's working and I can't understand why it's not on the third Fragment.
One thing is sure: I have checked with logs almost everywhere that the ArrayList.size() is never zero.
Here's the Third Fragment's relevant code:
public class SavedScanFragment extends Fragment{
private ListView lv;
private Database db;
private ArrayList<Scan> scans;
private ScanAdapter adapter;
public static SavedScanFragment newInstance() {
return new SavedScanFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new Database(getContext());
getScans();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.fragment_saved_scan, container, false);
lv = (ListView) result.findViewById(R.id.saved_scan_list);
return result;
}
#Override
public void onResume() {
super.onResume();
db = new Database(getContext());
getScans();
}
public void getScans() {
AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
scans = db.getScans();
if(scans!=null)
return true;
else {
scans = new ArrayList<>();
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result)
populateList();
}
};
task.execute();
}
public void populateList() {
if(getContext()!=null) {
if (lv.getAdapter() == null) {
adapter = new ScanAdapter(getContext(), R.layout.scan_list_item, scans);
lv.setAdapter(adapter);
} else {
((ScanAdapter) lv.getAdapter()).update(scans);
}
}
}
And the ArrayAdapter's code:
public class ScanAdapter extends ArrayAdapter<Scan> implements ListAdapter {
private Context context;
private int layoutResourceID;
private ArrayList<Scan> results;
public ScanAdapter(Context context, int layoutResourceID, ArrayList<Scan> results) {
super(context, layoutResourceID, results);
this.context = context;
this.layoutResourceID = layoutResourceID;
this.results = results;
}
public void update(ArrayList<Scan> scans) {
results.clear();
results.addAll(scans);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView; //view = row
ViewHolder holder = null;
if(view == null) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(layoutResourceID, parent, false);
view.setBackgroundColor(Color.GREEN);
holder = new ViewHolder();
holder.name = (TextView)view.findViewById(R.id.scan_name_and_date_text);
holder.ssid = (TextView)view.findViewById(R.id.scan_SSID_text);
holder.frequency = (TextView)view.findViewById(R.id.scan_frequency_text);
holder.level = (TextView)view.findViewById(R.id.scan_level_text);
view.setTag(holder);
} else
holder = (ViewHolder) view.getTag();
Scan sr = results.get(position);
holder.name.setText(sr.getName()+" ( "+sr.getDate()+" )");
holder.ssid.setText(sr.getSsid() + " ( " + sr.getBssid() + " )");
holder.frequency.setText(sr.getFrequency()+" MHz");
holder.level.setText(Integer.toString(sr.getLevel())+ " dBm");
return view;
}
static class ViewHolder {
TextView name,ssid, frequency, level;
}
}
Thanks in advance!
From this post. You can try to use onActivityCreated instead of onCreate. Try this:
public class SavedScanFragment extends Fragment{
//....to restore the saved state
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Restore the fragment state here
db = new Database(getContext());
getScans();
}
//add this to save instant state
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//save your important variable here to outstate
}
}