Firebase RecylcerView Adapter Not Getting Accurate View Position - java

I am using the Firebase UI and am experiencing a unique issue. When I load the RecyclerView, there are no issues. I click an item on the RecyclerView and get the .push() value of the item that was clicked. It then takes data from that Firebase .push() value, which is stored in the Firebase database, and sends it to another activity. See images below:
The second image is the activity that receives data via an intent. When I click back to the RecyclerView, I click "8" again and I am loading a different number (right now it appears to be 1).
Ultimately, I am concerned that I do not have the RecyclerView set up correctly. Here is my code:
Create Poll object (POJO) and write to Firebase:
mSubmitPollCreation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO: Need to check if poll requirements are added, i.e. Question, Answer, ......
//check if image has been loaded first
if (resultImageURL == null) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.no_image_selected), Toast.LENGTH_LONG).show();
return;
}
//capture answers
if (mNumberOfPollAnswersCreatedByUser > 5) {
Toast.makeText(getApplicationContext(), getResources().getText(R.string.poll_answers_greater_than_five), Toast.LENGTH_LONG).show();
mNumberOfPollAnswersCreatedByUser = 5;
}
for (int i = 0; i < mNumberOfPollAnswersCreatedByUser; i++) {
EditText editText = (EditText) mEditTextAnswerLayout.findViewWithTag(getResources().getString(R.string.created_answer_editText_id) + String.valueOf(i + 1));
String editTextInputForAnswer = String.valueOf(editText.getText());
mPollAnswers.add(0, editTextInputForAnswer); Toast.makeText(getApplicationContext(),editTextInputForAnswer,Toast.LENGTH_SHORT).show();
}
Poll poll = new Poll(mCreatePollQuestion.getText().toString(), resultImageURL, mPollAnswers);
Map<String, Object> pollMap = poll.toMap();
final String key = mBaseRef.child("Polls").push().getKey();
Map<String, Object> childUpdates = new HashMap<String, Object>();
childUpdates.put("/Polls/" + key, pollMap);
mBaseRef.updateChildren(childUpdates);
Collections.reverse(mPollAnswers);
for (int i = 0; i < mPollAnswers.size(); i++) {
mBaseRef.child("Polls").child(key).child("answers").child(String.valueOf(i + 1)).updateChildren(poll.answerConvert(mPollAnswers, i));
}
Intent toHomeActivity = new Intent(CreateActivity.this, HomeActivity.class);
toHomeActivity.putExtra("viewpager_position", 2);
startActivity(toHomeActivity);
}
});
Where I read from Firebase and populate a RecyclerView:
public class LiveFragment 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";
private RecyclerView mRecyclerview;
private DatabaseReference mBaseRef;
private DatabaseReference mPollsRef;
private LinearLayoutManager mLayoutManager;
private FloatingActionButton mFloatingActionAdd;
private FirebaseRecyclerAdapter<Poll, PollHolder> mFireAdapter;
private RecyclerView.ItemAnimator mItemAnimator;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public LiveFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment LiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static LiveFragment newInstance(String param1, String param2) {
LiveFragment fragment = new LiveFragment();
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);
mBaseRef = FirebaseDatabase.getInstance().getReference();
mPollsRef = mBaseRef.child("Polls");
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_new, container, false);
Log.v("TAG", "ON CREATE CALLED FROM NEW");
mRecyclerview = (RecyclerView) v.findViewById(R.id.list);
mRecyclerview.setItemAnimator(new SlideInLeftAnimator());
mLayoutManager = new LinearLayoutManager(getContext());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
mFloatingActionAdd = (FloatingActionButton) getActivity().findViewById(R.id.myFAB);
mFloatingActionAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent I = new Intent(getActivity().getApplicationContext(), CreateActivity.class);
startActivity(I);
}
});
mRecyclerview.setLayoutManager(mLayoutManager);
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
scrollToPosition();
}
#Override
public void onStart() {
super.onStart();
mFireAdapter = new FirebaseRecyclerAdapter<Poll, PollHolder>(Poll.class, R.layout.latest_item, PollHolder.class, mBaseRef.child("Polls")) {
#Override
protected void populateViewHolder(PollHolder viewHolder, final Poll model, final int position) {
viewHolder.mPollQuestion.setText(model.getQuestion());
Picasso.with(getActivity().getApplicationContext())
.load(model.getImage_URL())
.fit()
.into(viewHolder.mPollImage);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("TAG", model.toString());
Log.v("TAG","ONCLICKED");
Intent toPoll = new Intent(getActivity(), PollHostActivity.class);
toPoll.putExtra("POLL_ID", mFireAdapter.getRef(position).getKey());
startActivity(toPoll);
}
});
Log.v("TAG", mFireAdapter.getRef(position).getKey());
Log.v("TAG", String.valueOf(position));
Log.v("TAG", model.getQuestion());
Log.v("TAG", model.getImage_URL());
}
};
mRecyclerview.setAdapter(mFireAdapter);
scrollToPosition();
}
#Override
public void onStop() {
super.onStop();
if (mFireAdapter != null) {
mFireAdapter.cleanup();
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public static class PollHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView mPollQuestion;
ImageView mPollImage;
View mView;
public PollHolder(View itemView) {
super(itemView);
mPollQuestion = (TextView) itemView.findViewById(R.id.latest_item_question);
mPollImage = (ImageView) itemView.findViewById(R.id.pollThumbNailImage);
this.mView = itemView;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Log.v("TAG", "CLICKED");
}
}
private void scrollToPosition(){
mFireAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int pollCount = mFireAdapter.getItemCount();
int lastVisiblePosition = mLayoutManager.findLastCompletelyVisibleItemPosition();
// If the recycler view is initially being loaded or the user is at the bottom of the list, scroll
// to the bottom of the list to show the newly added message.
if (lastVisiblePosition == -1 ||
(positionStart >= (pollCount - 1) && lastVisiblePosition == (positionStart - 1))) {
mRecyclerview.scrollToPosition(positionStart);
}
}
});
}
}
My thoughts:
am I calling mFireAdapter.cleanup() in the right location?
The issue with clicking "8" and seeing "1" does not appear on the first load of the RecyclerView, it only happens when I go from the activity (second image) and the navigate back to the RecyclerView.
I call .setStackFromEnd(true) and .setReverseLayout(true) to reverse the data as it is stored in the FirebaseDatabase, which could be contributing to the issue.
I set up the .setOnClickListener() in the .populateViewHolder() method, and use the following to pass the .push() key in an intent to the next activity:
toPoll.putExtra("POLL_ID", mFireAdapter.getRef(position).getKey());
This method could be getting the incorrect key.
Finally, Firebase Database:
Any help would be appreciated!

You should not use position outside of populateViewHolder as it value may differ. Instead, make your viewHolder final and use viewHolder.getAdapterPosition() to replace it.

Related

How to pass data from RecyclerView to activity

I'm really struggling with this, what I need is when the user clicks on the recipe image, which comes from the ArrayList listRecipe put into the RecyclerView, the value from myTextView1 should be passed to the CreateMealPlan activity so it can be saved along with the date to an SQLite database.
Hope I've made this clear, thanks in advance for any help.
Activity
public class CreateMealPlan extends MainActivity {
DatePicker datepicker;
Button submit;
List<com.stu54259.plan2cook.Model.Category> listRecipe = new ArrayList<>();
SQLiteDatabase db;
Cursor c;
RecyclerView recipeList;
RecipeListAdapter adapterRecipe;
String recipe_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_meal_plan);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(CreateMealPlan.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(CreateMealPlan.this,RecipeSearch.class);
startActivity(b);
break;
/*case R.id.shoppingList:
Intent c = new Intent(CreateMealPlan.this, ShoppingList.class);
startActivity(c);
break;*/
case R.id.mealPlan:
Intent d = new Intent(CreateMealPlan.this, MenuPlan.class);
startActivity(d);
break;
/*case R.id.reminder:
Intent e = new Intent(CreateMealPlan.this, Reminder.class);
startActivity(e);
break*/
}
return false;
}
});
datepicker = findViewById(R.id.calendarView);
ListRecipes();
adapterRecipe = new RecipeListAdapter(this, listRecipe);
recipeList = findViewById(R.id.recipes);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
recipeList.setLayoutManager(mLayoutManager);
recipeList.setItemAnimator(new DefaultItemAnimator());
recipeList.setAdapter(adapterRecipe);
recipeList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Recipe name is", recipe_name);
}
});
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d_name = new Date(day, month, year);
String dayOfTheWeek = sdf.format(d_name);
submit = (Button) findViewById(R.id.create);
// perform click event on submit button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void ListRecipes() {
listRecipe.clear();
db = (new DatabaseManager(this).getWritableDatabase());
String selectQuery = " SELECT recipe_name, image, image2, category" + " FROM " + DatabaseManager.TABLE_RECIPE + " GROUP BY recipe_name";
c = db.rawQuery(selectQuery, null);
Log.d("Query", selectQuery);
if (c.moveToFirst()) {
do {
com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
category.setRecipe_name(c.getString(c.getColumnIndex("recipe_name")));
category.setImage(c.getInt(c.getColumnIndex("image")));
category.setImage2(c.getString(c.getColumnIndex("image2")));
category.setCategory_name(c.getString(c.getColumnIndex("category")));
listRecipe.add(category);
} while (c.moveToNext());
c.close();
}
}
}
RecyclerAdapter
public class RecipeListAdapter extends RecyclerView.Adapter<com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder> {
private List<Category> listRecipe;
private LayoutInflater mInflater;
private com.stu54259.plan2cook.Adapters.RecipeListAdapter.ItemClickListener mClickListener;
// data is passed into the constructor
public RecipeListAdapter(Context context, List<Category> data) {
this.mInflater = LayoutInflater.from(context);
this.listRecipe = data;
}
// inflates the row layout from xml when needed
#Override
public com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.cardview_recipe, parent, false);
return new com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder holder, int position) {
holder.myTextView1.setText(listRecipe.get(position).getRecipe_name());
holder.myTextView2.setText(listRecipe.get(position).getCategory_name());
String image2 = listRecipe.get(position).getImage2();
Bitmap myBitmap = BitmapFactory.decodeFile(image2);
if (myBitmap != null)
holder.imgImage.setImageBitmap(myBitmap);
else
holder.imgImage.setImageResource(listRecipe.get(position).getImage());
}
// total number of rows
#Override
public int getItemCount() {
return listRecipe.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView1;
TextView myTextView2;
ImageView imgImage;
ViewHolder(View itemView) {
super(itemView);
myTextView1 = itemView.findViewById(R.id.txtName);
myTextView2 = itemView.findViewById(R.id.txtCategory);
imgImage = itemView.findViewById(R.id.imgImage);
myTextView1.setOnClickListener(this);
myTextView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String recipe_name = myTextView1.getText().toString();
}
});
}
/**
* Called when a view has been clicked.
*
* #param v The view that was clicked.
*/
#Override
public void onClick(View v) {
}
}
// allows clicks events to be caught
void setClickListener(com.stu54259.plan2cook.Adapters.RecipeListAdapter.ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
You should:
Define an interface that will be used to handle click events (similar to your ItemClickListener);
Implement this interface as an anonymous class or by extending your Activity;
Pass that instance of the new interface to your adapter;
Set click listener, handle click events and pass data back into your Activity.
Step 1: define an interface
Sample interface:
interface OnRecipeClickListener {
void onRecipeClicked(int position, String someString);
}
Step 2: implement the interface
This part is located inside of your Activity class:
new OnRecipeClickListener() {
public void onRecipeClicked(int position, String someString) {
Log.d(CreateMealPlan.class.getSimpleName(), "Here is the data: " + someString);
}
}
Step 3: passing this interface to the adapter
public class RecipeListAdapter extends RecyclerView.Adapter<com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder> {
...
private OnRecipeClickListener clickListener;
// data is passed into the constructor
public RecipeListAdapter(Context context, List<Category> data, OnRecipeClickListener clickListener) {
...
this.clickListener = clickListener;
}
...
}
Step 4: setting click listeners to view holders
public class RecipeListAdapter extends RecyclerView.Adapter<com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder> {
...
#Override
public void onBindViewHolder(#NonNull com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder holder, int position) {
...
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.onRecipeClicked(position,
holder.textView1.getText().toString());
}
});
}
...
}
Code from Step 2 can be used like that:
OnRecipeClickListener listener = new OnRecipeClickListener() {
public void onRecipeClicked(int position, String someString) {
Log.d(CreateMealPlan.class.getSimpleName(), "Here is the data: " + someString);
}
};
adapterRecipe = new RecipeListAdapter(this, listRecipe, listener);

How to transfer string from TextView to main activity with onClick listener

I want to create an onclick listener that reads the String from one TextView and then I somehow pass that string onto the main activity in order to open a third activity
So my main activity looks like this
public class AdvancedResults extends AppCompatActivity {
private RecyclerView mRecyclerView;
private AdvancedAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
private ArrayList<String> saved_recipes_with_ingredients = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced_results);
advancedList.add(new AdvancedItem(R.drawable.ic_android, "test1", "test2");
advancedList.add(new AdvancedItem(R.drawable.ic_android, "test3", "test4");
mRecyclerView = findViewById(R.id.recyclerView1);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new AdvancedAdapter(advancedList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new AdvancedAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
// I want to open a new activity and append the string from the TextView here (maybe with get/set)
}
});
}
And my recycler adapter looks like this
public class AdvancedAdapter extends RecyclerView.Adapter<AdvancedAdapter.AdvancedViewHolder> {
private ArrayList<AdvancedItem> mAdvancedList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class AdvancedViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextView1;
public TextView mTextView2;
public AdvancedViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageViewADV);
mTextView1 = itemView.findViewById(R.id.textViewADV1);
mTextView2 = itemView.findViewById(R.id.textViewADV2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
//how do I get the string from the TextView and pass it onto the main class?
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
public AdvancedAdapter(ArrayList<AdvancedItem> advancedList) {
mAdvancedList = advancedList;
}
#Override
public AdvancedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.advanced_item, parent, false);
AdvancedViewHolder evh = new AdvancedViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(AdvancedViewHolder holder, int position) {
AdvancedItem currentItem = mAdvancedList.get(position);
holder.mImageView.setImageResource(currentItem.getImageResource());
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
}
#Override
public int getItemCount() {
return mAdvancedList.size();
}
i'm just not sure how im supposed to do that and what method to use.
So if you want the text from the text view you do:
String text = textViewId.getText();
But in your case you want to add the text for each one of the views on the list
So on the adapter how make a on click listener:
if (listener != null) {
int position = getAdapterPosition();
String text = mTextView1.getText();
Intent i = new Intent(getApplicationContext(), YourActitivity.class);
i.putExtra("nameYouWant", text)
startActivity(i);
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
Now on your activity :
String text = intent.getStringExtra("nameYouWant");
You can use interface to pass the second String param. So just add one String param like this -
public interface OnItemClickListener {
void onItemClick(int position, String text);
}
And in adapter pass the string on click of the item along with the position
listener.onItemClick(position, mTextView1.getText().toString());
And in the activity, you will receive the String text, from there you can pass it to ThirdActivity via bundle.
mAdapter.setOnItemClickListener(new AdvancedAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position, String textData) {
Intent i = new Intent(this, ThirdActivity.class);
i.putExtra("TEXT_KEY", textData);
}
});
Hope it will help!!

java - How to match the details of a Dialog from RecyclerViewAdapter to another Fragment upon clicking the button

I'm new to android coding, I've tried all the possible solution here and on YouTube but still struggling. I just want how to match the data from a dialog of a fragment to another fragment upon pressing the button. we're working on a simple project. :)
Here is what we want to do.Kindly watch this link:
https://imgur.com/tGdWcfq
We want to change the name that will match the dialog upon clicking the "set parameters' button
here's what we found online the difference is we have a dialog button
https://www.youtube.com/watch?v=ZXoGG2XTjzU
https://www.youtube.com/watch?v=69C1ljfDvl0
Here are the codes
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
Context mContext;
List<specieList> mData;
Dialog myDialog;
public RecyclerViewAdapter(Context mContext, List<specieList> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
Button b;
v = LayoutInflater.from(mContext).inflate(R.layout.row,parent,false);
final MyViewHolder vHolder = new MyViewHolder(v);
myDialog = new Dialog(mContext);
myDialog.setContentView(R.layout.fishpop);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
b = myDialog.findViewById(R.id.toasted);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView toastfish = (TextView) myDialog.findViewById(R.id.dialog_fish_id);
Toast.makeText(mContext,"Parameters are now set for " + toastfish.getText().toString(), Toast.LENGTH_SHORT).show();
// here upon clicking this button click we want to match the details in this dialog to another tab. Kindly watch the link above :)
}
});
vHolder.fish_choices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView dialog_fish = (TextView) myDialog.findViewById(R.id.dialog_fish_id);
TextView dialog_sciname = (TextView) myDialog.findViewById(R.id.dialog_sciname_id);
ImageView dialog_image = (ImageView) myDialog.findViewById(R.id.dialog_image_id);
dialog_fish.setText(mData.get(vHolder.getAdapterPosition()).getFish());
dialog_sciname.setText(mData.get(vHolder.getAdapterPosition()).getSciname());
dialog_image.setImageResource(mData.get(vHolder.getAdapterPosition()).getImage());
myDialog.show();
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_fish.setText(mData.get(position).getFish());
holder.tv_sciname.setText(mData.get(position).getSciname());
holder.img.setImageResource(mData.get(position).getImage());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private LinearLayout fish_choices;
private TextView tv_fish;
private TextView tv_sciname;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
fish_choices = (LinearLayout) itemView.findViewById(R.id.choices);
tv_fish = (TextView) itemView.findViewById(R.id.textView1);
tv_sciname = (TextView) itemView.findViewById(R.id.textView2);
img = (ImageView) itemView.findViewById(R.id.image);
}
}
}
Code for overview tab(This tab we want to match the content)
public class overview extends Fragment {
View v2;
// 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;
public overview() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment overview.
*/
// TODO: Rename and change types and number of parameters
public static overview newInstance(String param1, String param2) {
overview fragment = new overview();
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);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v2 = inflater.inflate(R.layout.fragment_overview, container, false);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");
String currentDate = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
String currentTime = time.format(calendar.getTime());
TextView textViewDate =(TextView) v2.findViewById(R.id.date_id);
textViewDate.setText(currentDate);
TextView textViewTime =(TextView) v2.findViewById(R.id.time_id);
textViewTime.setText(currentTime);
return v2;
}
// 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);
}
}
Code for Specie tab (this tab we want to refer)
public class specie extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<specieList> lstspecie;
// 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;
public specie() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment specie.
*/
// TODO: Rename and change types and number of parameters
public static specie newInstance(String param1, String param2) {
specie fragment = new specie();
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);
lstspecie = new ArrayList<>();
lstspecie.add(new specieList("Nile Tilapia", "Oreochromis niloticus", R.drawable.tilapia));
lstspecie.add(new specieList("Ayungin (Silver Perch)", "Bidyanus bidyanus", R.drawable.ayungin));
lstspecie.add(new specieList("Sugpo (Tiger Prawn)", "Penaeus monodon", R.drawable.hipon));
lstspecie.add(new specieList("Hito (Catfish)", "Siluriformes", R.drawable.hito));
lstspecie.add(new specieList("Giant Gourami", "Osphronemus goramy", R.drawable.giant));
lstspecie.add(new specieList("Bangus (Milkfish)", "Chanos chanos", R.drawable.bangus));
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_specie, container, false);
myrecyclerview = (RecyclerView)v.findViewById(R.id.specie_recycleview);
RecyclerViewAdapter recyclerAdapter = new RecyclerViewAdapter(getContext(), lstspecie);
myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
myrecyclerview.setAdapter(recyclerAdapter);
return v;
}
// 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;
}
/**
* 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 OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Thank you!
Using object oriented Approach
You can write a function in your activity and you can call a fragment's method from it, as you have your Fragment's reference in your Activity when you initialized it like
In Your Activity
class yourActivity ... {
// your other methods
public void callFragmentMethod(String params) {
// here call your fragment's method
fragment.method(params);
}
}
In your Fragment now
class yourFragment ... {
// your other methods
public void method(String params) {
// here call your fragment's method
here do whatever you want to do it with params
}
}
Now you can call your Activity's method either from another fragment or from Adapter, whatever you want
From Fragment you can call like
((yourActivity)getActivity()).callFragmentMethod(params);
From Adapter
((yourActivity)context).callFragmentMethod(params);
Call below method on your button click..
public void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frameContainer, fragment);
fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.commit();
}
pass frameContainer in constructor of your Adapter like..
new RecyclerViewAdapter(context, list, R.id.frameContainer);

Cannot Save RecyclerView Position in Fragment

I have read several threads on approaches to save the position of a RecyclerView. I have implemented the below, however it does not appear to be saving the position on either screen rotation or back navigation, it simply loads back to the top of the RecyclerView:
public class FeedFragment 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";
private static final String POLL_QUESTION = "POLL_QUESTION";
private static final String POLL_IMAGE_URL = "POLL_IMAGE_URL";
private static final String FILTER_ACTION = "UPDATE_WIDGET";
private static final String POLL_ID = "POLL_ID";
private static final String RECYCLERVIEW_STATE = "Recyclerview_State";
private Parcelable mRecyclerViewState;
private static Bundle mRecyclerViewBundle;
private MyReceiver myReceiver;
#BindView(R.id.list)
RecyclerView mRecyclerview;
private SharedPreferences mPrefs;
private SharedPreferences.Editor editor;
private DatabaseReference mBaseRef;
private DatabaseReference mPollsRef;
private LinearLayoutManager mLayoutManager;
private FirebaseRecyclerAdapter<Poll, PollHolder> mFireAdapter;
private OnFragmentInteractionListener mListener;
public FeedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FeedFragment.
*/
// TODO: Rename and change types and number of parameters
public static FeedFragment newInstance(String param1, String param2) {
FeedFragment fragment = new FeedFragment();
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) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_poll_feed, container, false);
ButterKnife.bind(this, v);
mPrefs = getActivity().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
editor = mPrefs.edit();
if (savedInstanceState != null) {
mRecyclerViewState = savedInstanceState.getParcelable(RECYCLERVIEW_STATE);
}
mRecyclerview.getItemAnimator().setChangeDuration(0);
mLayoutManager = new LinearLayoutManager(getContext());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
mRecyclerview.setSaveEnabled(true);
mRecyclerview.setLayoutManager(mLayoutManager);
setReceiver();
return v;
}
// 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;
}
// #Override
// public void onSaveInstanceState(#NonNull Bundle outState) {
// super.onSaveInstanceState(outState);
// mRecyclerViewState = mLayoutManager.onSaveInstanceState();
// outState.putParcelable(RECYCLERVIEW_STATE, mRecyclerViewState);
// }
//
//
// #Override
// public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
// super.onViewStateRestored(savedInstanceState);
// if (savedInstanceState != null){
// mRecyclerViewState = savedInstanceState.getParcelable(RECYCLERVIEW_STATE);
// }
// }
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
mRecyclerViewState = mLayoutManager.onSaveInstanceState();
outState.putParcelable(RECYCLERVIEW_STATE, mRecyclerViewState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null){
mRecyclerViewState = savedInstanceState.getParcelable(RECYCLERVIEW_STATE);
}
}
#Override
public void onResume() {
super.onResume();
if (mRecyclerViewState != null){
mLayoutManager.onRestoreInstanceState(mRecyclerViewState);
}
}
#Override
public void onStart() {
super.onStart();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Polls");
FirebaseRecyclerOptions<Poll> options = new FirebaseRecyclerOptions.Builder<Poll>()
.setQuery(query, Poll.class)
.build();
mFireAdapter = new FirebaseRecyclerAdapter<Poll, PollHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final PollHolder holder, int position, #NonNull Poll model) {
holder.mPollQuestion.setText(model.getQuestion());
String voteCount = String.valueOf(model.getVote_count());
//Update shared prefs with latest question
editor.putString(POLL_QUESTION, model.getQuestion());
editor.putString(POLL_IMAGE_URL, model.getImage_URL());
editor.apply();
//TODO: Investigate formatting of vote count for thousands
holder.mVoteCount.setText(voteCount);
Picasso.get()
.load(model.getImage_URL())
.fit()
.into(holder.mPollImage);
//TODO: Cannot understand how to utilize IntentService to update widget
//TODO: Followed this tutorial: https://www.journaldev.com/20735/android-intentservice-broadcastreceiver
Intent intent = new Intent(getContext(), MyService.class);
intent.putExtra(POLL_QUESTION, model.getQuestion());
intent.putExtra(POLL_IMAGE_URL, model.getImage_URL());
getActivity().startService(intent);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String pollID = mFireAdapter.getRef(holder.getAdapterPosition()).getKey();
if (getActivity().findViewById(R.id.two_pane_constraint_layout) != null & getActivity().getApplication().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
FragmentManager fm = getActivity().getSupportFragmentManager();
PollFragment pollFragment = PollFragment.newInstance(pollID);
fm.beginTransaction()
.replace(R.id.poll_fragment, pollFragment)
.commit();
} else {
Intent i = new Intent(getActivity().getApplicationContext(), PollHostActivity.class);
i.putExtra(POLL_ID, pollID);
startActivity(i);
}
}
});
}
#Override
public PollHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.latest_item, parent, false);
return new PollHolder(v);
}
};
mRecyclerview.setAdapter(mFireAdapter);
scrollToPosition();
mFireAdapter.startListening();
}
public static class PollHolder extends RecyclerView.ViewHolder {
TextView mPollQuestion;
TextView mVoteCount;
ImageView mPollImage;
View mView;
String mTag;
public PollHolder(View itemView) {
super(itemView);
mPollQuestion = itemView.findViewById(R.id.latest_item_question);
mPollImage = itemView.findViewById(R.id.pollThumbNailImage);
mVoteCount = itemView.findViewById(R.id.latest_item_poll_count);
this.mView = itemView;
}
public void setTag(String tag) {
this.mTag = tag;
}
public View getViewByTag(String tag) {
return mView;
}
}
private void setReceiver() {
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(FILTER_ACTION);
// LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
}
private void scrollToPosition() {
mFireAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int pollCount = mFireAdapter.getItemCount();
int lastVisiblePosition = mLayoutManager.findLastCompletelyVisibleItemPosition();
// If the recycler view is initially being loaded or the user is at the bottom of the list, scroll
// to the bottom of the list to show the newly added message.
if (lastVisiblePosition == -1 ||
(positionStart >= (pollCount - 1) && lastVisiblePosition == (positionStart - 1))) {
mRecyclerview.scrollToPosition(positionStart);
}
}
});
}
private class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String poll_Question = intent.getStringExtra("broadcastMessage");
//TODO: Update Widget - used answer from https://stackoverflow.com/questions/3455123/programmatically-update-widget-from-activity-service-receiver
int[] ids = AppWidgetManager.getInstance(getContext()).getAppWidgetIds(new ComponentName(getContext(), PollWidgetProvider.class));
PollWidgetProvider pollWidgetProvider = new PollWidgetProvider();
pollWidgetProvider.onUpdate(getContext(), AppWidgetManager.getInstance(getContext()), ids);
}
}
/**
* 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 OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
EDIT:
I am trying to save within a Fragment, that is attached to a host Activity. I have some RecyclerView functionality coded to on.Start(), which may be overriding the methods below.
I also feel I need to make a call to onPause() somewhere since the RecyclerView is located inside a Fragment.
Full code available:https://github.com/troy21688/LiveVotingUdacity

RecyclerView in Fragment - No Adapter Attached, Skipping Layout

I have an odd situation, I have an Activity hosting a TabLayout/Viewpager that populates data based on changes to a Firebase Database. Unfortunately, the RecyclerView is not being populated, and I am receiving the error below in my logcat. I believe the fragment is being loaded even when it is not on screen, which is causing an error in the population of the RecyclerView. It is also weird as the RecyclerView does populate when I rotate the screen:
12-13 21:31:40.013 12490-12490/com.troychuinard.fanpolls E/RecyclerView: No adapter attached; skipping layout
Here is the ViewPager Adapter I have in my host Activity:
public class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new TrendingFragment();
case 1:
return new FollowingFragment();
case 2:
return new LiveFragment();
default:
return new TrendingFragment();
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getResources().getString(R.string.trending_text);
case 1:
return getResources().getString(R.string.following_text);
case 2:
return getResources().getString(R.string.new_text);
default:
return getResources().getString(R.string.trending_text);
}
}
}
Here is the complete fragment where I initialize the RecyclerView inside onCreateView() function in my LiveFragment, which is tab 3 in the TabLayout:
public class LiveFragment 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";
private RecyclerView mRecyclerview;
private DatabaseReference mBaseRef;
private DatabaseReference mPollsRef;
private LinearLayoutManager mLayoutManager;
private FirebaseRecyclerAdapter <Poll, PollHolder> mFireAdapter;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public LiveFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment LiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static LiveFragment newInstance(String param1, String param2) {
LiveFragment fragment = new LiveFragment();
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);
mBaseRef = FirebaseDatabase.getInstance().getReference();
mPollsRef = mBaseRef.child("Polls");
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_new, container, false);
Log.v("TAG", "ON CREATE CALLED FROM NEW");
mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerview = (RecyclerView)v.findViewById(R.id.new_RecyclerView);
if (mRecyclerview != null){
mRecyclerview.setHasFixedSize(true);
}
if (mRecyclerview == null){
Log.v("TAG", "RECYCLERVIEW NULL");
} else if (mLayoutManager == null){
Log.v("TAG", "LAYOUTMANAGER NULL");
} else if (mFireAdapter == null) {
Log.v("TAG", "mFIREADAPTER NULL");
}
return v;
}
// 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 onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
if (mFireAdapter != null){
mFireAdapter.cleanup();
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mRecyclerview.setLayoutManager(mLayoutManager);
mFireAdapter = new FirebaseRecyclerAdapter<Poll, PollHolder>(Poll.class, R.layout.latest_item, PollHolder.class, mPollsRef) {
#Override
protected void populateViewHolder(PollHolder viewHolder, Poll model, int position) {
viewHolder.mPollQuestion.setText(model.getQuestion());
Picasso.with(getActivity().getApplicationContext())
.load(model.getImage_URL())
.fit()
.into(viewHolder.mPollImage);
Log.v("QUESTION", model.getQuestion());
Log.v("IMAGE", model.getImage_URL());
}
};
mRecyclerview.setAdapter(mFireAdapter);
mPollsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot x : dataSnapshot.getChildren()){
mFireAdapter.notifyItemInserted(0);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#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 static class PollHolder extends RecyclerView.ViewHolder {
TextView mPollQuestion;
ImageView mPollImage;
public PollHolder(View itemView) {
super(itemView);
mPollQuestion = (TextView) itemView.findViewById(R.id.latest_item_question);
mPollImage = (ImageView) itemView.findViewById(R.id.pollThumbNailImage);
}
}
/**
* 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 OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Move your Adapter from onCreateView to onActivityCreated method after you have read data from firebase.
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//read Poll data from firebase mPollsRef for example
//.... database reference to firebase
//Query mPollsRef = databaseReference.child("pools").limitToFirst(200);
mRecyclerview.setLayoutManager(mLayoutManager);
mFireAdapter = new FirebaseRecyclerAdapter<Poll, PollHolder>(Poll.class, R.layout.latest_item, PollHolder.class, mPollsRef) {
#Override
protected void populateViewHolder(PollHolder viewHolder, Poll model, int position) {
viewHolder.mPollQuestion.setText(model.getQuestion());
Picasso.with(getActivity().getApplicationContext())
.load(model.getImage_URL())
.fit()
.into(viewHolder.mPollImage);
Log.v("QUESTION", model.getQuestion());
Log.v("IMAGE", model.getImage_URL());
}
};
mRecyclerview.setAdapter(mFireAdapter);
}
My code for initialize Pager at HostActivity.java
private FragmentPagerAdapter mPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_absence);
// Create the adapter that will return a fragment for each section
mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
private final Fragment[] mFragments = new Fragment[] {
new MyAbsenceFragment(),
new MyAttendanceFragment(),
new AbsTypesFragment(),
new LiveFragment(),
};
private final String[] mFragmentNames = new String[] {
"Absences",
"Attendances",
"AbsTypes",
"Live"
};
#Override
public Fragment getItem(int position) {
return mFragments[position];
}
#Override
public int getCount() {
return mFragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentNames[position];
}
};
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mPagerAdapter);

Categories