Multiple instance of same fragments inside a ViewPager - java

I have got some weird problem after implementing multiple instance(loaded dynamically depending on the data) of same fragment inside a Viewpager.
My fragment class consists of a listview which will be populated according to the data retrieved from the server, but every time i swipe page from one to another, the data inside a listview of the fragment is jumbled.
Here is the code. Any help will be appreciated. Thank You.
This the Fragment class where the Viewpager is present.
public class Menu extends Fragment implements View.OnClickListener {
private SlidingTabLayout mSlidingTab;
SlidingUpPanelLayout mLayout;
private ArrayList<String> menu_names;
private ViewPager pager;
ActionBarActivity act;
public ArrayList<ArrayList<All_Data>> menus;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.main, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
mSlidingTab = (SlidingTabLayout) act.findViewById(R.id.sliding_tab);
mSlidingTab.setDistributeEvenly(true);
mSlidingTab.setCustomTabView(R.layout.custom_text, 0);
pager= (ViewPager) act.findViewById(R.id.pager);
mSlidingTab.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return android.R.color.transparent;
}
});
mSlidingTab.bringToFront();
menuUpdate();
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return Meals.newInstance(position);
}
#Override
public int getCount() {
return menu_names.size();
}
#Override
public CharSequence getPageTitle(int i) {
return menu_names.get(i);
}
}
private void menuUpdate(String result) {
//menu_names= List Retrieved from server
//menus= List Retrieved from server
pager.setAdapter(new MyPagerAdapter(act.getSupportFragmentManager()));
mSlidingTab.setViewPager(pager);
}
Meals.java(Fragment class):
public class Meals extends Fragment {
ActionBarActivity activity;
int position = 0;
static Meals newInstance(int page) {
Meals fragmentFirst = new Meals();
Bundle args = new Bundle();
args.putInt("position", page);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.meals, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
position = getArguments().getInt("position");
ArrayList<All_Data> mMeals;
Fragment menu = activity.getSupportFragmentManager().findFragmentByTag("Menu");
mMeals = ((Menu) menu).menus.valueAt(position);
ListView mList = (ListView) activity.findViewById(R.id.mainMenu1);
LayoutInflater inflater;
inflater = LayoutInflater.from(activity.getApplicationContext());
mList.addHeaderView(inflater.inflate(R.layout.custom_text, mList, false));
mList.addFooterView(inflater.inflate(R.layout.footer, mList, false));
Menu_adapter adapter = new Menu_adapter(((Menu) menu), mMeals, activity);
mList.setAdapter(adapter);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (ActionBarActivity) context;
}
#Override
public void onResume() {
super.onResume();
MyApplication.getInstance().trackScreenView("Startes Screen");
}
}
meals.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f1f2f3"
android:orientation="vertical">
<ListView
android:id="#+id/mainMenu1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#f1f2f3"
android:dividerHeight="20dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:scrollbars="none" />
</RelativeLayout>

Related

Add and show items to the RecyclerView in different fragments

I am creating an app that has 3 Tabs and every tabs has a different jobs. For Example, In Employee tab, there are EditText for taking name and surname of an emolyee and Button for add items to the its RecyclerView. City Tab is same as Employee tab just takes city names. The last tab has only one Button for distribute entries of Employees and Cities and show to user.
My problem is, I cannot find how to add items to the RecyclerView and and show it to the user.
Here is my code. I am sending just Tab1's fragment and layouts. Others are the same.
This is the Fragment1 class:
public class Fragment1 extends Fragment {
private RecyclerView employeeRecyclerView;
private RecyclerViewAdapter employeeRecyclerViewAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.name_employee, container, false);
}
}
This is the RecyclerViewAdapter class:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private List<String> mData;
private LayoutInflater mInflater;
RecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
#NonNull
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.fragment_main, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
String x = mData.get(position);
holder.myTextView.setText(x);
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.section_label);
}
}
}
and Employee.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/employeeField"
android:hint="Name and Surname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<Button
android:id="#+id/cityAdd"
android:text="addEmployee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/employees"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
and fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.main.PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Update I upload other classes. There are Fragment2 and Fragment3 classes but they are same with Fragment1.
PlaceHolderFragment.class
public class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private PageViewModel pageViewModel;
public static PlaceholderFragment newInstance(int index) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
bundle.putInt(ARG_SECTION_NUMBER, index);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageViewModel = ViewModelProviders.of(this).get(PageViewModel.class);
int index = 1;
if (getArguments() != null) {
index = getArguments().getInt(ARG_SECTION_NUMBER);
}
pageViewModel.setIndex(index);
}
#Override
public View onCreateView(
#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_main, container, false);
final TextView textView = root.findViewById(R.id.section_label);
pageViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
SectionsPagerAdapter.class
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3};
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
}
return fragment;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
return 3;
}
}
and PageViewModel.class
public class PageViewModel extends ViewModel {
private MutableLiveData<Integer> mIndex = new MutableLiveData<>();
private LiveData<String> mText = Transformations.map(mIndex, new Function<Integer, String>() {
#Override
public String apply(Integer input) {
return "Hello world from section: " + input;
}
});
public void setIndex(int index) {
mIndex.setValue(index);
}
public LiveData<String> getText() {
return mText;
}
}

Use a view from a fragment in main activity

I'm pretty new in android development and I have some questions about communication between fragments and main activity.
I didn't success to solve my problem in my particular case. What I want to do is to modify the alpha of a view inside a fragment (something like a card) when scrolling from one fragment to the one with this view. I tried different things but I failed (null pointer exception), you can see some experiments in a comment. Here is my code and my architecture:
Fragment with the view:
public class VideoviewFragment extends BaseFragment {
/* public View card;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_videoview, container, false);
card = (View) rootview.findViewById(R.id.card_video);
return rootview;
}
public void setalphacard(float value){
card.setAlpha(value);
}*/
public static VideoviewFragment create() {
return new VideoviewFragment();
}
#Override
public int getLayoutResId() {
return R.layout.fragment_videoview;
}
#Override
public void inOnCreateView(View root, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
}
}
Base fragment:
public abstract class BaseFragment extends Fragment {
private View mRoot;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mRoot = inflater.inflate(getLayoutResId(), container, false);
inOnCreateView(mRoot, container, savedInstanceState);
return mRoot;
}
#LayoutRes
public abstract int getLayoutResId();
public abstract void inOnCreateView(View root, #Nullable ViewGroup container,#Nullable Bundle savedInstanceState);
}
Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Viewpager
final ViewPager viewPager = (ViewPager) findViewById(R.id.am_view_pager);
final MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
// tabview et viewpager
viewPager.setCurrentItem(1);
// Changement couleurs swipe
viewPager.setBackgroundColor(Color.rgb(135,206,250));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(position == 1) {
viewPager.setBackgroundColor((Integer) new ArgbEvaluator().evaluate(positionOffset, Color.rgb(135,206,250),Color.rgb(240,15,45)));
//videoviewFragment.setalphacard(positionOffset);
}
if(position == 0) {
viewPager.setBackgroundColor((Integer) new ArgbEvaluator().evaluate(positionOffset, Color.TRANSPARENT,Color.rgb(135,206,250)));
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
Adapter:
public class MainPagerAdapter extends FragmentPagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return CameraFragment.create();
case 1:
return OptionFragment.create();
case 2:
return VideoviewFragment.create();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
XML VideoviewFragment
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout0"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="#+id/card_video"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="70dp"
android:background="#drawable/card_background_video"/>
</RelativeLayout>
(I know there is no instance of my fragment in this activity...)
I found few similar topics on StackOverflow like this one Use view from fragment xml file, but I'm doing something wrong...
Thanks for your help!

ANDROID: ViewPager with different Fragments in instantiateItem method

I use ViewPager to create fragments that swipe left and now I want insert fragments into each fragment page.
activityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
...
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/myviewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<devlight.io.library.ntb.NavigationTabBar
android:id="#+id/ntb_horizontal"
app:ntb_swiped="true"/>
</android.support.design.widget.CoordinatorLayout>
and this:
tab0_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:textSize="30sp"
android:gravity="center"
android:id="#+id/textView"
android:layout_centerHorizontal="true"
android:textColor="#android:color/holo_green_dark"
android:text="Social\nFragment"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:textSize="15sp"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:text="androidbelieve.com"
android:textColor="#000"
android:layout_below="#+id/textView"
android:textStyle="italic"/>
</RelativeLayout>
I have a ViewPager in mainActivity.java
final ViewPager viewPager = (ViewPager) findViewById(R.id.myviewpager);
viewPager.setAdapter(new PagerAdapter() {
...
...
}
I try open one screen in viewpager via fragment layout.
I try this:
final ViewPager viewPager = (ViewPager) findViewById(R.id.myviewpager);
viewPager.setAdapter(new PagerAdapter() {
...
public Object instantiateItem(final ViewGroup container, final int position) {
if (position == 0)
{
final View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.fragment_tab0, null, false);
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.myviewpager,new tab0Fragment()).commit();
container.addView(view);
return view;
}
else if (position == 1)
...
}
...
}
AND tab0Fragment.java
public class tab0Fragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tab0,null);
}
}
I am noob in android. how can correct this code?
Solution:
The answers was not my answer but that help me a lot.
According #Mr. Rabbit ans #Amit Upadhyay I change top code to this:
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
if (position == 0)
{
final View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.fragment_tab0, null, false);
MyAdapter adapter = new MyAdapter(getSupportFragmentManager());
adapter.addFragment(new tab0Fragment(), getResources().getString(R.string.tab0));
container.addView(view);
return view;
}
else if (position == 1)
{
and also adding MyAdapter class according #Mr. Rabbit's answer.
hope help someone else.
Try to separate out your adapter and below code.
MyAdapter.java
public class MyAdapter extends FragmentPagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Create your Fragments
FragmentOne.java
public class FragmentOne extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
}
FragmentTwo.java
public class FragmentTwo extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
return view;
}
}
Setup your viewpager like this in your activity.
final ViewPager viewPager = (ViewPager) findViewById(R.id.myviewpager);
MyAdapter adapter = new MyAdapter(getSupportFragmentManager());
// Add your fragments in adapter.
FragmentOne fragmentOne = new FragmentOne();
adapter.addFragment(fragmentOne, getResources().getString(R.string.fragment_one_title));
FragmentTwo fragmentTwo = new FragmentTwo();
adapter.addFragment(fragmentTwo, getResources().getString(R.string.fragment_two_title));
viewPager.setAdapter(adapter);
Then finally set your NavigationTabBar with your ViewPager.
final NavigationTabBar navigationTabBar = (NavigationTabBar) findViewById(R.id.ntb_horizontal);
navigationTabBar.setViewPager(viewPager, 2);
To achieve this you can create a custom ViewPagerAdapter. Eg:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
/**
* Created by aupadhyay on 1/5/17.
*/
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
public void addFragments(Fragment fragment, String tabTitle)
{
this.fragments.add(fragment);
this.tabTitles.add(tabTitle);
}
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
}
Now you can set adapter on viewpager like this:
final ViewPager viewPager = (ViewPager) findViewById(R.id.myviewpager);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new Tab0Fragment(), "First");
viewPagerAdapter.addFragments(new Tab1Fragment(), "Second");
viewPagerAdapter.addFragments(new Tab2Fragment(), "Third");
// add more if required.
viewPager.setAdapter(viewPagerAdapter);
Tab0Fragment, Tab1Fragment, Tab1Fragment are the fragments created by you to add in your viewpager.

How to change views in ViewPager Fragment

I have a ViewPager with fragments in my activity, each page has a textview, I want to change the text of the textview from the onCreate method in the activity that contains the viewpager. How should I go about doing that?
below is the code that would return a null object exception:
Fragment:
public class MyFragment extends Fragment {
private TextView textView;
public static MyFragment getInstance(){
return new MyFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
textView = (TextView) rootView.findViewById(R.id.textView);
return rootView;
}
public void setText(String text){
textView.setText(text);
}
}
Adapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return MyFragment.getInstance();
}
#Override
public int getCount() {
return 3;
}
}
Activity onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
MyFragment fragment = (MyFragment) adapter.getItem(0);
fragment.setText("Altered"); // and this returns null pointer exception
}
Thank you!
Most FragmentPagerAdapters will have an addFragment method and will keep track various fragments that are added to it via an internal object:
public class MyPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
As it stands, your implementation of getItem returns a new instance of MyFragment every time it is called. As such, MyFragment fragment = (MyFragment) adapter.getItem(0); is a new instance that will never be loaded into the ViewPager, will never be inflated, and hence has a null textView reference.
The other issue is that within the onCreate of your activity, the fragments have not yet been inflated, so the textView will be null unless you delay the call:
final MyFragment fragment = (MyFragment) mPagerAdapter.getItem(0);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
fragment.setText("Altered");
}
}, 100);
But really, why not just set it to the correct value when it is initialized?
Try This
Fragment:
public class MyFragment extends Fragment {
private TextView textView;
private String Text;
public MyFragment (String Text){
this.Text=Text;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
textView = (TextView) rootView.findViewById(R.id.textView);
textView.setText(Text);
return rootView;
}
}
Adapter :
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new MyFragment("Altered");
}
#Override
public int getCount() {
return 3;
}
}
Activity onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}

Passing object to sliding tabs fragment on create

I am trying to pass an object that is retrieved and created during my main activities on create method to one of the fragments of my sliding tabs layout.
Since this object is created over a network connection my plan was to receive the data during the creation of the Main Activity then pass the resulting object to my fragments. However this seems easier said than done. The resulting object will then get passed to a recycler view in the Forecast fragment.
I have read various methods including implementing the parcelable interface on my model object, storing it as a bundle and trying to send it over to the fragment. However it always came up null. I believe this was due to me creating a new fragment in memory and not passing the bundle to the fragment that was displayed. I also don't have any ID's for the fragments so locating them by ID isn't possible, at least to my knowledge.
If anyone could point me in the right direction Id be greatly appreciative.
Main Activity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MAIN ACTIVITY";
#Bind(R.id.toolBar) Toolbar mToolbar;
#Bind(R.id.viewPager) ViewPager mViewPager;
#Bind(R.id.tabLayout) SlidingTabLayout mTabLayout;
private ViewPagerAdapter mAdapter;
private String mForecastsTabName = "Forecasts";
private String mAlertsTabName = "Alerts";
private String mTabTitles[] = {mForecastsTabName, mAlertsTabName};
private int mNumberOfTabs = 2;
private Forecast[] mForecasts;
private JsonParser mJsonParser = new JsonParser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
setupSlidingTabs();
}
private void setupSlidingTabs() {
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
mAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mTabTitles, mNumberOfTabs);
// Assigning the ViewPages View and setting the adapter
mViewPager.setAdapter(mAdapter);
// Assigning the Sliding Tab Layout View
mTabLayout.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
mTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.ColorAccent);
}
});
mTabLayout.setViewPager(mViewPager);
}
Forecast Fragment.java
public class ForecastFragment extends Fragment {
private static final String FORECAST_KEY = "FORECAST_KEY";
private static final String TAG = "FRAGMENT";
private Forecast[] mForecasts;
#Bind(R.id.recyclerView) RecyclerView mRecyclerView;
#Bind(R.id.emptyView) TextView mEmptyView;
#Bind(R.id.locationButton) Button mLocationButton;
public static ForecastFragment newInstance(Forecast[] forecasts) {
ForecastFragment fragment = new ForecastFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArray(FORECAST_KEY, forecasts);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize dataset, this data would usually come from a local content provider or
// remote server.
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.forecast_tab_fragment, container, false);
ButterKnife.bind(this, view);
displayEmptyViewIfNoData();
ForecastAdapter adapter = new ForecastAdapter(getActivity(), mForecasts);
mRecyclerView.setAdapter(adapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(layoutManager);
return view;
}
private void displayEmptyViewIfNoData() {
if (mForecasts == null || mForecasts.length < 1) {
mRecyclerView.setVisibility(View.GONE);
mEmptyView.setVisibility(View.VISIBLE);
mLocationButton.setVisibility(View.VISIBLE);
}
else {
mRecyclerView.setVisibility(View.VISIBLE);
mEmptyView.setVisibility(View.GONE);
mLocationButton.setVisibility(View.GONE);
}
}
#OnClick(R.id.locationButton)
public void selectLocations(View view) {
Intent intent = new Intent(getActivity(), LocationSelectionActivity.class);
intent.putExtra(ActivityConstants.CALLING_ACTIVITY, ActivityConstants.FORECAST_ACTIVITY);
startActivity(intent);
}
}
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
// This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
String mTitles[];
// Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
int mNumberOfTabs;
SparseArray<Fragment> registeredFragments = new SparseArray<>();
public ViewPagerAdapter(FragmentManager fm, String titles[], int numberOfTabs) {
super(fm);
mTitles = titles;
mNumberOfTabs = numberOfTabs;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if (position == 0) {
ForecastFragment forecastFragment = new ForecastFragment();
return forecastFragment;
}
else if (position == 1) {
AlertFragment alertFragment = new AlertFragment();
return alertFragment;
}
return null;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return mTitles[position];
}
#Override
public int getCount() {
return mNumberOfTabs;
}
}
Forecast_tab_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/ColorPrimaryLight">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/activity_vertical_margin"/>
<TextView
android:id="#+id/emptyView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/empty_forecast_message"
android:textColor="#color/ColorTextPrimary"
android:gravity="center"
android:visibility="gone"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="115dp"/>
<Button
android:id="#+id/locationButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/button_shape"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:textColor="#color/ColorTextPrimary"
android:text="#string/add_forecast_button"
android:visibility="gone"
android:layout_alignParentBottom="false"
android:layout_centerHorizontal="true"
android:layout_below="#+id/emptyView"
android:layout_marginTop="24dp"/>
</RelativeLayout>
When you do this code below, you can hand the data to your fragment.
In your Activity, call below, when the data is ready:
mAdapter.getFragment(index).setData(dataObject);
or
mAdapter.getFragment(mViewPager.getCurrentItem()).setData(dataObject);
Your FragmentPagerAdater should be like this:
class CustomPagerAdapter extends FragmentPagerAdapter {
SparseArray<App4StoreBaseSubFragment> registeredFragments = new SparseArray<App4StoreBaseSubFragment>();
public CustomPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
App4StoreBaseSubFragment fragment = (App4StoreBaseSubFragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public ForecastFragment getFragment(int position){
return registeredFragments.get(position);
}
}
Your Fragment should be like this:
public class ForecastFragment extends Fragment {
public void setData(Forecast forecast){
//write code here to change UI
}
}

Categories

Resources