I am creating a polling app in realtime using Firebase.
Every day, I am adding new polls to a Firebase category that I have under the directory Polls > Dates > Respective Date > Poll 1, Poll 2, Poll 3. I want to update the ViewPager to display the polls only for that current day.
Each poll will have an image, question, answer choices, a total vote count, and several other components.
Basically, I want my ViewPager to display each poll for that particular day. I will manually update the data in Firebase, and I am hoping that my Firebase listeners in client/Java code can update the data dynamically. My polls are each a unique instance of a HomePollsFragment, and I am having difficulty changing the individual fragments that display in the ViewPager for a particular day.
I am trying to handle the changes in the getItemPosition() override method of the FragmentStatePagerAdapter, and I am trying to override the "View Comments" TextView in the included screenshot (I will update everything else later, just doing the "View Comments" now for simplicity). I would like the "View Comments" to state "Test Comments for Poll 1" for the first poll, and "Test Comments for Poll 2" for the second poll.
Below is my MainActivity, where I create the ViewPager, and my HomePollsFragment:
MainActivity
public class MainActivity extends AppCompatActivity implements HomePollsFragment.OnFragmentInteractionListener {
private Toolbar toolbar;
private FragmentManager fm;
private static final String FIREBASE_URL = "https://fan-polls.firebaseio.com/";
private Firebase mBaseRef;
private Firebase mUserRef;
private Firebase mPollsRef;
private static final String POLL_FRAG_TAG = "POLL_FRAG";
private static final String PREFS_FRAG_TAG = "PREFS_FRAG";
private static final String REQUEST_POLL_FRAG_RAG = "REQUEST_POLL_FRAG";
private ViewPager mPager;
private FragmentStatePagerAdapter mPagerAdapter;
private int mPollCountforCurrentDay;
private DateFormat mDateFormat;
private Date mDate;
private String mCurrentDateString;
private String mPollQuestion;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
createNavDrawer();
//write to Firebase
mBaseRef = new Firebase(FIREBASE_URL);
mUserRef = mBaseRef.child("Users");
mPollsRef = mBaseRef.child("Polls");
//set up viewpager for current day
mPager = (ViewPager) findViewById(R.id.home_polls_viewpager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
//terminate the Loading Activity as it has no value after sending user to the appropriate screen
LoadingActivity.LoadingActivity.finish();
//get current date to apply to Viewpager
mDateFormat = new SimpleDateFormat("dd-MM-yyyy");
mDate = new Date();
mCurrentDateString = mDateFormat.format(mDate);
}
@Override
protected void onStart() {
super.onStart();
mPollsRef.addValueEventListener(new ValueEventListener() {
//testing methodology of adding children
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mPollCountforCurrentDay = (int) dataSnapshot.child(mCurrentDateString).getChildrenCount();
mPagerAdapter.notifyDataSetChanged();
Log.i("TAG", "There are " + String.valueOf(mPollCountforCurrentDay) + " children in today's poll count.");
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
//close fireBase eventlistener
@Override
protected void onStop() {
super.onStop();
}
@Override
public void onFragmentInteraction(Uri uri) {
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return new HomePollsFragment();
}
@Override
public int getCount() {
return mPollCountforCurrentDay;
}
@Override
public int getItemPosition(Object object) {
final Object mObject = object;
mPollsRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (int i = 1; i <= mPollCountforCurrentDay; i++) {
HomePollsFragment frag = (HomePollsFragment) mObject;
frag.mNumberOfPollChildren.setText((String) dataSnapshot.child(mCurrentDateString).child(String.valueOf(i)).child("Poll_Question").getValue());
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return super.getItemPosition(object);
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
super.onBackPressed();
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
}
HomePollsFragment, trying to create a new instance of this with a different question, answer, and other info for each day (the ViewPager should dynamically update each day for the polls on that given day):
public class HomePollsFragment 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;
public TextView mNumberOfPollChildren;
private Firebase mBaseRef;
private Firebase mPollsRef;
private static final String FIREBASE_URL = "https://fan-polls.firebaseio.com/";
//all date items; dynamic
private int mPollCountforCurrentDay;
private DateFormat mDateFormat;
private Date mDate;
private String mCurrentDateString;
private OnFragmentInteractionListener mListener;
public HomePollsFragment() {
// 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 HomePollsFragment.
*/
// TODO: Rename and change types and number of parameters
public static HomePollsFragment newInstance(String param1, String param2) {
HomePollsFragment fragment = new HomePollsFragment();
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 = new Firebase(FIREBASE_URL);
mPollsRef = mBaseRef.child("Polls");
//get current date to apply to Viewpager
mDateFormat = new SimpleDateFormat("dd-MM-yyyy");
mDate = new Date();
mCurrentDateString = mDateFormat.format(mDate);
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
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_poll, container, false);
mNumberOfPollChildren = (TextView) rootView.findViewById(R.id.comments_textview);
return rootView;
}
@Override
public void onStart() {
super.onStart();
mPollsRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mPollCountforCurrentDay = (int) dataSnapshot.child(mCurrentDateString).getChildrenCount();
Log.i("TAG", "There are " + String.valueOf(mPollCountforCurrentDay) + " children in today's pollllll count.");
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
//close event listener onStop
@Override
public void onStop() {
super.onStop();
}
// 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);
}
}
Example of Poll Design with View Comments TextView: