Android - Swipe refresh on active fragment - java

I have a fragment inside the MainActivity
on the menu, there is a refresh button and swipe refresh option which calls myUpdateOperation() method
This fragment may be different according to user's selection.
How can I make sure the right fragment currently active gets refreshed when the refresh action is invoked?
content_main.xml
<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/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.app.MainActivity"
tools:showIn="#layout/app_bar_main">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/main_fragment"
android:name="com.example.app.main_fragment.MainFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="7"
tools:layout="#layout/fragment_main" />
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
mSwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i(TAG, "onRefresh called from SwipeRefreshLayout");
// This method performs the actual data-refresh operation.
// The method calls setRefreshing(false) when it's finished.
myUpdateOperation();
mSwipeRefreshLayout.setRefreshing(false);
}
}
);
}
void myUpdateOperation(){
// TODO: 20-Mar-17
Toast.makeText(this, "Refresh", Toast.LENGTH_SHORT).show();
}
Fragment1.java
public class Fragment1 extends Fragment {
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_1, container, false);
}
public void fragment1refresh(){
// TODO: this to be call when refresh on MainActivity and also fragment_1 is visible
}
}
Fragment2.java
public class Fragment2 extends Fragment {
public Fragment2() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_2, container, false);
}
public void fragment2refresh(){
// TODO: this to be call when refresh on MainActivity and also fragment_2 is visible
}
}

For this make your Fragment1 and Fragment2 class extends CustomFragment
The code for CustomFragment can be something like this
public abstarct class CustomFragment extends Fragment {
public CustomFragment() {
// Required empty public constructor
}
public abstract void refresh();
}
Change Fragment1 implementation to:
public class Fragment1 extends CustomFragment {
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_1, container, false);
}
#Override
public void refresh(){
// TODO: this to be call when refresh on MainActivity and also fragment_1 is visible
}
}
Similarly change the implementation of Fragment2 class.
Now in your MainActivity class get a reference to current visible fragment. This can be done as:
CustomFragment currentFragment = (CustomFragment)mFragmentManager.findFragmentById(R.id.main_fragment);
Now inside change myUpdateOperation() implementation to :
private void myUpdateOperation(){
// TODO: 20-Mar-17
currentFragment.refresh();
}

Get the current fragment from the fragment manager, then check which fragment type matches with it:
Fragment currentFragment = mFragmentManager.findFragmentById(R.id.main_fragment);
if (currentFragment instanceof Fragment1) {
((Fragemnt1) currentFragment).fragment1refresh()
} if (currentFragment instanceof Fragment2) {
((Fragemnt2) currentFragment).fragment2refresh()
}

Related

ViewPager2 doesn't show Fragments

I am trying to implement ViewPager2 in my application and this is not the first time I am doing it but now it is not working.
I've been trying to find a solution for a couple of hours and trying different options but still - the fragments don't show up.
ViewPager2 is displaying correctly - I checked this by changing its background color.
I'm using the OneUI 2.4.0 library - but I've tested this library before and everything worked, and now it won't.
ViewPager2 Adapter
public class MainViewPagerAdapter extends FragmentStateAdapter {
private ArrayList<Fragment> arrayList = new ArrayList<>();
public MainViewPagerAdapter(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new MainFragment();
case 1:
return new NewsFragment();
case 2:
return new ProfileFragment();
}
return null;
}
#Override
public int getItemCount() {
return 3;
}
}
MainFragment.java (other fragments code looks the same)
public class MainFragment extends Fragment {
View mRootView;
#Nullable
#Override
public View onCreateView(
#NonNull LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_main, container, true);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("MainFragment", "Initialized"); // I don't see that in logcat
}
}
fragment_main.xml (Other fragments have similar layout)
<?xml version="1.0" encoding="utf-8"?>
<de.dlyt.yanndroid.oneui.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.textview.MaterialTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/main_page"
android:textColor="#color/sesl_primary_text"
android:textSize="24sp"
android:textStyle="bold" />
</de.dlyt.yanndroid.oneui.widget.NestedScrollView>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ToolbarLayout mToolbarLayout;
private ViewPager2 mViewPager;
private TabLayout mTabLayout;
private MainViewPagerAdapter viewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
setup();
}
private void initialize() {
mToolbarLayout = (ToolbarLayout) findViewById(R.id.mToolbarLayout);
mViewPager = (ViewPager2) findViewById(R.id.mMainPager);
mTabLayout = (TabLayout) findViewById(R.id.mMainTabLayout);
}
private void setup() {
viewPagerAdapter = new MainViewPagerAdapter(getSupportFragmentManager(), getLifecycle());
mViewPager.setAdapter(viewPagerAdapter);
}
And the problem is just that i don't see my fragments in ViewPager2.
try to
return mRootView
instead of
return super.onCreateView(inflater, container, savedInstanceState);
The place where you went wrong was when you did not add the layout to the root. The problem is this:
return super.onCreateView(inflater, container, savedInstanceState);
but, you r not using your view right? You are using the default view which is just empty. So, to solve it, you need to pass it your view instead of that. So, return your view like this:
return mRootView;

Android studio null object reference error while changing component visibility

I'm making an app that displays the same menus for different users, each menu being a fragment, but depending on the user certain things are visible and others aren't.
However, when I try to set a component's visibility as GONE I get a null pointer exception error, I'm still testing so I'm only using a textView on the fragment xml.
I've already tried initializing both the TextView and the FragmentMenuEncomenda, the class of the fragment I'm using, objects, both inside the if clause before the onCreate() method, and after the setContentView(), like the tabLayout and viewPager.
The if clause was only to make sure the user type was correct and the code in question is as follows:
public class PaginaInicialCliente extends AppCompatActivity {
private SharedPreferences sharedpreferences;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pagina_inicial_cliente);
tabLayout = findViewById(R.id.tabLayoutCliente);
viewPager = findViewById(R.id.viewPagerCliente);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
//fragments a adicionar
adapter.addFragment(new FragmentMenuEncomendas(), "Encomendas");
adapter.addFragment(new FragmentMenuOpcoes(), "Opções");
//inicializar o tab layout
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
sharedpreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
if (sharedpreferences.getInt("tipo",0)==3) {
Log.d("USER_DEBUG","Cliente");
FragmentMenuEncomendas fragmentMenuEncomendas = new FragmentMenuEncomendas();
//THE ERROR IS HERE
fragmentMenuEncomendas.getActivity().findViewById(R.id.textViewEncomendas).setVisibility(View.GONE);
}
}
}
The FragmentMenuEncomenda class:
public class FragmentMenuEncomendas extends Fragment {
View v;
public FragmentMenuEncomendas(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.encomendas_fragment, container, false);
return v;
}
}
The xml file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textViewEncomendas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
All the answers I've searched didn't work, I don't know if it's because I'm trying to change the visibility inside the on create method.
Because view is not created when you call the function.
public class FragmentMenuEmpresas extends Fragment {
View v;
View textView;
boolean isTextViewShow = false;
boolean isViewCreated = false;
public FragmentMenuEmpresas() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.empresas_fragment, container, false);
textView = v.findViewById(R.id.textViewEncomendas);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (isTextViewShow) {
textView.setVisibility(View.VISIBLE);
} else {
textView.setVisibility(View.GONE);
}
isViewCreated = true;
}
void setIsTextViewShow() {
if (isViewCreated) {
textView.setVisibility(View.VISIBLE);
} else {
isTextViewShow = true;
}
}
void setIsTextViewGone() {
if (isViewCreated) {
textView.setVisibility(View.GONE);
} else {
isTextViewShow = false;
}
}
}
then you can call the setIsTextViewShow or setIsTextViewGone anytime you want
FragmentMenuEncomendas fragmentMenuEncomendas = new FragmentMenuEncomendas();
fragmentMenuEncomendas.setIsTextViewShow();//show
fragmentMenuEncomendas.setIsTextViewGone();//gone

How to run the normal functionalities of buttons when using ViewPager

Today was the first day I used ViewPager to swipe across screens in my activity. However, after adding the ViewPager, none of my buttons in any activities seem to work. I can only swipe between my activities. I don't understand as to why this happens so any help would be greatly appreciated. Thank you!
Here is the PageAdapter class code:
PageAdapter.java
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FragmentOne();
break;
case 1:
return new FragmentTwo();
break;
case 2:
return new FragmentThree();
break;
default:
break;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
Here is the Fragments code:
FragmentOne.java
public class FragmentOne extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_log,container,false);
}
}
FragmentTwo.java
public class FragmentTwo extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_remote_lock,container,false);
}
}
FragmentThree.java
public class FragmentThree extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_my_keys,container,false);
}
}
FragmentActivity.java
public class FragmentActivity extends android.support.v4.app.FragmentActivity {
ViewPager viewPager;
#Override
protected void onResume() {
super.onResume();
viewPager.setCurrentItem(1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
viewPager = (ViewPager) findViewById(R.id.damsara);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}
}
FragmentActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/damsara"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.v4.view.ViewPager>
The xml files i added to the fragment classes contain buttons with animations. however none of them work.

Multiple instance of same fragments inside a ViewPager

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>

How to navigate between fragments?

I am new to Android Fragments. I have 2 different fragments and want to navigate from one fragment to another using buttons. For example, in fragmentA when i press a button, i go to fragmentB and vise verse.
Here are my simple codes:
FragmentA.java
public class FragmentA extends Fragment {
public FragmentA(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
return rootView;
}
}
fragmenta.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="670dp"
android:gravity="top"
android:orientation="vertical" >
<TextView
android:id="#+id/txtLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:text="Fragment 1"
android:textStyle="bold"
android:textSize="22dp" />
</LinearLayout>
FragmentB.java
public class FragmentB extends Fragment {
public FragmentB(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_b, container, false);
return rootView;
}
}
fragmentb.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="670dp"
android:gravity="top"
android:orientation="vertical" >
<TextView
android:id="#+id/txtLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:text="Fragment 2"
android:textStyle="bold"
android:textSize="22dp" />
</LinearLayout>
I need codes (both java and xml) for buttons. Help from scratch would be appreciated. Thanks in advance!!
Check This Tutorial and Below Code for refrence
Fragment1.java
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
public void onClick(View view) {
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment1, fragment2);
fragmentTransaction.commit();
}
}
Fragment2.java
public class Fragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}
}
Code in Activity
public class MyActivity extends FragmentActivity implements OnListenerChangeFragment {
FragmentA mFragmentA;
FragmentB mFragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public void onShowFragmenA() {
//replace mFragmentB by mFragmentA
}
#Override
public void onShowFragmenB() {
//replace mFragmentA by mFragmentA
}
}
//Code in Fragments
public class FragmentA extends Fragment {
private OnListenerChangeFragment mCallback;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
Button mButton = new Button(getActivity());
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onShowFragmenB();
}
});
return mButton;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnListenerChangeFragment) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()+ " must implement OnListenerChangeFragment");
}
}
}
public class FragmentB extends Fragment {
private OnListenerChangeFragment mCallback;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Button mButton = new Button(getActivity());
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onShowFragmenA();
}
});
return mButton;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnListenerChangeFragment) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()+ " must implement OnListenerChangeFragment");
}
}
}

Categories

Resources