Saving State In Fragment With ViewPager Android Studio - java

Need a little help on how to approach saving state in my single activity application. I looked at a few resources but couldn't quite find one that fits the build. Essentially I have single activity with a Fragment container view that I'm using to swap out fragments as needed. My issue is that as my activity is destroyed when a lifecycle event occurs, the fragment with my view pager is restored but the individual fragments on the tabs are not loaded. I cannot figure out how to save the state properly. Below is my code:
Activity:
public class StartActivity extends AppCompatActivity {
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mAuth = FirebaseAuth.getInstance();
if (savedInstanceState == null) {
LoginFragment fragment = new LoginFragment();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frameLayout, fragment)
.commit();
}
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null){
MainActivity mainActivityFrag = new MainActivity();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frameLayout, mainActivityFrag)
.commit();
}
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState, #NonNull PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
}
Fragment With View Pager:
public class MainActivity extends Fragment {
private FirebaseAuth mAuth;
private SectionsPagerAdapter sectionsPagerAdapter;
private ViewPager viewPager;
private TabLayout tabs;
private Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = mAuth = FirebaseAuth.getInstance();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
sectionsPagerAdapter = new SectionsPagerAdapter(getContext(),((AppCompatActivity)getActivity()).getSupportFragmentManager());
viewPager = view.findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
tabs = view.findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.showContextMenu();
toolbar = view.findViewById(R.id.topAppBar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
setHasOptionsMenu(true);
tabs.getTabAt(0).setIcon(R.drawable.home_selector);
tabs.getTabAt(1).setIcon(R.drawable.destination);
tabs.getTabAt(2).setIcon(R.drawable.mail_outline_blk);
tabs.getTabAt(3).setIcon(R.drawable.notification_bell);
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.main_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.logout:
mAuth.signOut();
//navigate to home fragment
LoginFragment fragment = new LoginFragment();
((AppCompatActivity)getActivity()).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frameLayout, fragment)
.commit();
return true;
default:
return false;
}
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
}
}
Adapter Code:
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, R.string.tab_text_4};
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
mContext = context;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position){
case 0:
PostFragment postFragment = new PostFragment();
return postFragment;
case 1:
TestFragment userFeedFragmentt = new TestFragment();
return userFeedFragmentt;
default:
TestFragment userFeedFragmenttt = new TestFragment();
return userFeedFragmenttt;
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
// Show 2 total pages.
return 4;
}
}

Related

How to close Unity without closing the entire app when changing fragments in Android Studio?

I have an app that the user can go through different fragments using BottomNavigationView and one of those fragments is a Unity3D application. So when i open the Unity fragment it works but when i open another fragment and open the Unity fragment back it crashes how do i fix this here is my code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
BottomNavigationView mBottomNavigationView;
NavController mNavController;
NavDestination mDestination;
AppBarConfiguration appBarConfiguration;
String tab;
private boolean doubleBackToExitPressedOnce ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean b = this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_main);
ActionBar mActionBar = getSupportActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater li = LayoutInflater.from(this);
View customView = li.inflate(R.layout.top_menu_custom, null);
mActionBar.setCustomView(customView);
mActionBar.setDisplayShowCustomEnabled(true);
mBottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_view);
ImageButton profileButton = (ImageButton) customView.findViewById(R.id.profile_button);
ImageButton notificationButton = (ImageButton) customView.findViewById(R.id.noti_button);
profileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment profileFragment = new ProfileFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,profileFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
notificationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NotificationFragment notificationFragment = new NotificationFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,notificationFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
mBottomNavigationView.setItemIconTintList(null);
mBottomNavigationView.setItemTextColor(ColorStateList.valueOf(getColor(R.color.black)));
mNavController = Navigation.findNavController(this, R.id.nav_host_fragment);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard,R.id.navigation_map, R.id.navigation_card,R.id.navigation_deals)
.build();
NavigationUI.setupActionBarWithNavController(this, mNavController, appBarConfiguration);
NavigationUI.setupWithNavController(mBottomNavigationView, mNavController);
mNavController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
Toast.makeText(getApplicationContext(),"hi",Toast.LENGTH_SHORT).show();
mDestination = mNavController.getCurrentDestination();
tab = mDestination.toString();
}
});
}
#Override
public void onBackPressed() {
//Toast.makeText(getApplicationContext(), mDestination.toString(),Toast.LENGTH_SHORT).show();
if (doubleBackToExitPressedOnce) {
getSupportFragmentManager().popBackStackImmediate();
mNavController.navigate(mDestination.getId());
mBottomNavigationView.setVisibility(View.VISIBLE);
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
UnityMapFragment
public class MapFragment extends Fragment{
protected UnityPlayer mUnityPlayer;
FrameLayout frameLayoutForUnity;
public MapFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mUnityPlayer = new UnityPlayer(getActivity());
View view = inflater.inflate(R.layout.fragment_map, container, false);
this.frameLayoutForUnity = (FrameLayout) view.findViewById(R.id.frameLayoutForUnity);
this.frameLayoutForUnity.addView(mUnityPlayer.getView(),
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
mUnityPlayer.requestFocus();
mUnityPlayer.windowFocusChanged(true);
return view;
}
#Override
public void onPause() {
super.onPause();
mUnityPlayer.pause();
}
#Override
public void onResume() {
super.onResume();
mUnityPlayer.resume();
}
// Quit Unity
#Override
public void onDestroy ()
{
mUnityPlayer.quit();
super.onDestroy();
}
So I managed to make a solution for this problem don't know if its good to make it this way or not but what i did was I instantiate the UnityPlayer in my MainActivity and in my fragment i call upon the UnityPlayer that was instatiated in my Main Activity.
MainActivity.java
public class MainActivity extends AppCompatActivity {
public BottomNavigationView mBottomNavigationView;
public NavController mNavController;
public NavDestination mDestination;
AppBarConfiguration appBarConfiguration;
String tab;
int onBackTimes = 0;
public UnityPlayer mUnityPlayer; <----Call unity player
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUnityPlayer = new UnityPlayer(this); <----UNITY PLAYER HERE
boolean b = this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_main);
ActionBar mActionBar = getSupportActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater li = LayoutInflater.from(this);
View customView = li.inflate(R.layout.top_menu_custom, null);
mActionBar.setCustomView(customView);
mActionBar.setDisplayShowCustomEnabled(true);
mBottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_view);
ImageButton profileButton = (ImageButton) customView.findViewById(R.id.profile_button);
ImageButton notificationButton = (ImageButton) customView.findViewById(R.id.noti_button);
profileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment profileFragment = new ProfileFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,profileFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
notificationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NotificationFragment notificationFragment = new NotificationFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,notificationFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
mBottomNavigationView.setItemIconTintList(null);
mBottomNavigationView.setItemTextColor(ColorStateList.valueOf(getColor(R.color.black)));
mNavController = Navigation.findNavController(this, R.id.nav_host_fragment);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard,R.id.navigation_map, R.id.navigation_card,R.id.navigation_deals)
.build();
NavigationUI.setupActionBarWithNavController(this, mNavController, appBarConfiguration);
NavigationUI.setupWithNavController(mBottomNavigationView, mNavController);
mNavController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
mDestination = mNavController.getCurrentDestination();
tab = mDestination.toString();
}
});
}
#Override
public void onBackPressed() {
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
onBackTimes +=1;
if(onBackTimes>1){
LoginActivity.close.finish();
finish();
}
else{
getSupportFragmentManager().popBackStackImmediate();
mBottomNavigationView.setVisibility(View.VISIBLE);
super.onBackPressed();
mNavController.navigate(mDestination.getId());
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
onBackTimes=0;
}
}, 2000);
}
#Override
protected void onStop() {
super.onStop();
}
//UNITY STUFF OVER HERE
#Override
protected void onPause() {
super.onPause();
mUnityPlayer.pause();
}
#Override protected void onResume()
{
super.onResume();
mUnityPlayer.resume();
}
#Override
protected void onDestroy(){
super.onDestroy();
}
}
UnityMapFragment
public class MapFragment extends Fragment{
private MainActivity mUnityMainActivity;
private UnityPlayer mUnityPlayer;
public MapFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//this code calls the UNITYPLAYER from MainActivity and return it here
mUnityMainActivity = (MainActivity) getActivity();
View unityPlayViewer = mUnityMainActivity.mUnityPlayer.getView();
mUnityMainActivity.mUnityPlayer.requestFocus();
mUnityMainActivity.mUnityPlayer.windowFocusChanged(true);
return unityPlayViewer;
}
/** FOR UNITY **/
#Override
public void onPause() {
super.onPause();
mUnityMainActivity.mUnityPlayer.pause();
}
// Resume Unity
#Override public void onResume()
{
super.onResume();
mUnityMainActivity.mUnityPlayer.resume();
}
I don't know why i have to include the OnPause, OnResume etc on both file but if one of them doesn't have it it'll crash.
The problem is, a new UnityPlayer is being created every-time we switch to the unity fragment and this crashes the app. So we need to create the UnityPlayer only for the first time or only when the player has been stopped. This works on my side.
In the UnityFragment class, my global variables :
protected UnityPlayer mUnityPlayer;
private View view;
private FrameLayout frameLayoutForUnity;
In onCreate a new UnityPlayer is created, which is called only for the first time :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUnityPlayer = new UnityPlayer(getActivity()); // create Unity Player
}
In onCreateView we refresh the view for UnityPlayer :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(mUnityPlayer.getParent() != null){
((ViewGroup)mUnityPlayer.getParent()).removeAllViews();
}
view = inflater.inflate(R.layout.fragment_unity, container, false);
this.frameLayoutForUnity = (FrameLayout) view.findViewById(R.id.unityFragmentLayout);
this.frameLayoutForUnity.addView(mUnityPlayer.getView(),
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
mUnityPlayer.requestFocus();
mUnityPlayer.windowFocusChanged(true);
return view;
}
Rest remains same. There could be better solutions than this. Cheers :)

How to show activity (which cannot be converted to fragment) using BottomNavigationBar?

I have problem with showing my activity. I don't know how to implement methods from NoteActivity to HomeFragment. HomeFragment is carried out by BottomNavigationBar without executing a NoteActivity.
NoteActivity-
public class NoteActivity extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference notebookRef = db.collection("Notebook");
private NoteAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_home);
setUpRecyclerView();
}
public void setUpRecyclerView() {
Query query = notebookRef.orderBy("title", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Note> options = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query, Note.class)
.build();
adapter = new NoteAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Simple HomeFragment which should have content of NoteActivity-
public class HomeFragment extends Fragment {
#Nullable
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
BottomNavigationBar which is executing HomeFragment and 2 more activities -
public class BottomNavigationBar extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
bottomNav.setSelectedItemId(R.id.nav_home);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_game:
selectedFragment = new GameFragment();
break;
case R.id.nav_user:
selectedFragment = new UserFragment();
break;
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container,
selectedFragment)
.commit();
return true;
}
};
}
Please help, thanks.

How to implement RecyclerView to Fragment of BottomNavigationBar? [duplicate]

I have problem with showing my activity. I don't know how to implement methods from NoteActivity to HomeFragment. HomeFragment is carried out by BottomNavigationBar without executing a NoteActivity.
NoteActivity-
public class NoteActivity extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference notebookRef = db.collection("Notebook");
private NoteAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_home);
setUpRecyclerView();
}
public void setUpRecyclerView() {
Query query = notebookRef.orderBy("title", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Note> options = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query, Note.class)
.build();
adapter = new NoteAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Simple HomeFragment which should have content of NoteActivity-
public class HomeFragment extends Fragment {
#Nullable
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
BottomNavigationBar which is executing HomeFragment and 2 more activities -
public class BottomNavigationBar extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
bottomNav.setSelectedItemId(R.id.nav_home);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_game:
selectedFragment = new GameFragment();
break;
case R.id.nav_user:
selectedFragment = new UserFragment();
break;
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container,
selectedFragment)
.commit();
return true;
}
};
}
Please help, thanks.

Interaction between fragments in Tabbed activity

I am trying a simple interaction between two fragments in Tabbed activity.
I have a two layouts with TextView, EditText and Button. I am trying to achieve move text from EditText in FragmentOne to the EdidText (or TextView) in Fragment two when the Button from FragmentOne is pressed. But it doesnt works.
During debuging there isnt any problem. App doesnt stop working.
Is something problem in ViewPager or SectionsPagerAdapter?
I have this two fragments.
Fragments One:
public class FragmentOne extends Fragment {
TextView textView;
EditText editText;
Button button;
private OnFragmentOneInteractionListener mListener;
public FragmentOne()
{
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_one, container, false);
editText = (EditText) view.findViewById(R.id.fragOne_txb);
textView = (TextView) view.findViewById(R.id.fragTwo_header);
button = (Button) view.findViewById(R.id.fragOne_btn_to2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String text = editText.getText().toString();
mListener.onFragmentOneInteraction(text);
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentOneInteractionListener) {
mListener = (OnFragmentOneInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentOneInteractionListener");
}
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnFragmentOneInteractionListener
{
void onFragmentOneInteraction(String string);
}
}
And fragments two:
public class FragmentTwo extends Fragment{
private OnFragmentTwoInteractionListener mListener;
public EditText editText;
public FragmentTwo()
{
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_two, container, false);
editText = (EditText) view.findViewById(R.id.fragTwo_txb);
return view;
}
public void onUpdateEditText(String string)
{
this.editText.setText(string);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentTwoInteractionListener) {
mListener = (OnFragmentTwoInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentTwoInteractionListener");
}
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnFragmentTwoInteractionListener
{
void onFragmentTwoInteraction(Uri uri);
}
}
And this is my main activity:
public class MainActivity extends AppCompatActivity
implements FragmentOne.OnFragmentOneInteractionListener,
FragmentTwo.OnFragmentTwoInteractionListener
{
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public void onFragmentOneInteraction(String string)
{
FragmentTwo fr2 = (FragmentTwo) getSupportFragmentManager().findFragmentById(R.id.fr2);
fr2.onUpdateEditText(string);
}
#Override
public void onFragmentTwoInteraction(Uri uri)
{
}
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position)
{
case 0:
FragmentOne fragmentOne = new FragmentOne();
return fragmentOne;
case 1:
FragmentTwo fragmentTwo = new FragmentTwo();
return fragmentTwo;
default:
return null;
}
}
#Override
public int getCount()
{
// Show 2 total pages.
return 2;
}
}
}
I just tried your code and this is the update i did to make it work. Please mark it correct if its what you are looking for
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public void onFragmentOneInteraction(String string)
{
fragmentTwo.onUpdateEditText(string);
/*FragmentTwo fr2 = (FragmentTwo) getSupportFragmentManager().findFragmentById(R.id.fr2);
fr2.onUpdateEditText(string);*/
}
#Override
public void onFragmentTwoInteraction(Uri uri)
{
}
FragmentTwo fragmentTwo = new FragmentTwo();
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position)
{
case 0:
FragmentOne fragmentOne = new FragmentOne();
return fragmentOne;
case 1:
return fragmentTwo;
default:
return null;
}
}
#Override
public int getCount()
{
// Show 2 total pages.
return 2;
}
}
I suggest to use getActivity() instead
if (getActivity() instanceof OnFragmentOneInteractionListener) {
mListener = (OnFragmentOneInteractionListener) getActivity();
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentOneInteractionListener");
}

How can i load WebView URL in fragment from another AppCompatActivity class

I am creating project for "Drawer with Swipe Tab". There i used a webview in fragment and i want to load Webview URL from Another AppCompatActivity. How can i do it?
Fragment Class:
public class SocialFragment extends Fragment {
ProgressBar pb_per;
public WebView mWebView;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.social_layout, container, false);
pb_per = (ProgressBar) view.findViewById(R.id.progressBar_book1);
mWebView = (WebView) view.findViewById(R.id.web_book1); //This is the id you gave for webview
//--------------------------- to over ride keyboard error ------(1)
mWebView.setWebViewClient(new myWebClient());
mWebView.getSettings().setJavaScriptEnabled(true);
//--------------------------------------------------
mWebView.getSettings().setSupportZoom(true); //Zoom Control on web (You don't need this
//if ROM supports Multi-Touch
mWebView.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM
mWebView.setBackgroundColor(Color.parseColor("#FFFFFF"));
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(false);
// Load URL
mWebView.loadUrl("http://www.twitter.com");
mWebView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return view;
}
//===================================================================
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
pb_per.setVisibility(View.VISIBLE);
// multi_per.setVisibility(ProgressBar.GONE);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
pb_per.setVisibility(View.GONE);
// multi_per.setVisibility(ProgressBar.VISIBLE);
}
}
}
TabFragment.Java Class
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
// Return fragment with respect to Position .
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new PrimaryFragment();
case 1 : return new SocialFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
// This method returns the title of the tab according to the position.
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Facebook";
case 1 :
return "Twitter";
}
return null;
}
}
}
AppCompatActivity class:
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup the DrawerLayout and NavigationView
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
// Lets inflate the very first fragment
// Here , we are inflating the TabFragment as the first Fragment
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
// Setup click events on the Navigation View Items.
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_sent) {
//###############################From Here I Call WEBVIEW URL #######################
SocialFragment.mWebView.loadUrl("http://www.busindia.com/busindia_TNSTC.jsp");
}
if (menuItem.getItemId() == R.id.nav_item_inbox) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
}
return false;
}
});
// Setup Drawer Toggle of the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle
= new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
}
I had Tried #cprakashagr Given Solutation but getting error See below Image
See Error ScreenShot
Use localBroadCastManager
WebViewHavingActivity
#Override
protected void onPause() {
// Unregister since the activity is paused.
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mWebViewLoader);
super.onPause();
}
#Override
protected void onResume() {
// Register to receive messages.
// We are registering an observer (mWebViewLoader) to receive Intents
// with actions named "WebView".
LocalBroadcastManager.getInstance(this).registerReceiver(
mWebViewLoader, new IntentFilter("WebView"));
super.onResume();
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "WebView" is broadcasted.
private BroadcastReceiver mWebViewLoader = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mWebView.post(new Runnable() {
#Override
public void run() {
mWebView.loadUrl("http://google.com");
}
});
}
};
CallingActivity
LocalBroadcastManager.getInstance(JobDetailScreen.this).sendBroadcast(new Intent("WebView"));
This Work for me Thanks For trying me to Help
SocialFragment.mWebView.post(new Runnable() {
public void run() {
SocialFragment.mWebView.loadUrl("http://www.busindia.com/busindia_TNSTC.jsp");
}
});

Categories