How to open a specific website in a fragment from a button in another fragment - android-fragments

I'm using TabLayout and ViewPager in MainActivity and I want to open a specific website in a fragment(BrowserFragment) that contains a webview by clicking a button in another fragment(FragmentHome). In HomeFragment I've 2 buttons, goToFacebook which lead to Facebook and goToAmazon which lead to Amazon.
This is my code:
MainActivity extends AppCompatActivity
TabLayout tabLayout;
ViewPager viewPager;
TabItem homeTabItem;
TabItem browserTabItem;
TabItem profilTabItem;
PagerAdapter pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout=findViewById(R.id.tabLayout);
homeTabItem=findViewById(R.id.homeTabItem);
browserTabItem=findViewById(R.id.browserTabItem);
profilTabItem=findViewById(R.id.profilTabItem);
viewPager=findViewById(R.id.viewPager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
PagerAdapter extends FragmentPagerAdapter
private int numOfTabs;
public PagerAdapter(#NonNull FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs=numOfTabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch(position){
case 0 :
return new HomeFragment();
case 1 :
return new BrowserFragment();
case 2 :
return new ProfilFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
BrowserFragment extends Fragment
WebView webView;
ProgressBar progressBar;
public BrowserFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_browser, container, false);
progressBar = v.findViewById(R.id.progressBar);
progressBar.setMax(100);
webView=v.findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
webView.setWebChromeClient(new MyWebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.google.com/");
return v;
}
private class MyWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String request)
{
view.loadUrl(request);
return true;
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
}
private class MyWebChromeClient extends WebChromeClient
{
public void onProgressChanged(WebView view, int progress)
{
progressBar.setProgress(progress);
}
}
HomeFragment extends Fragment
Button goToAmazon, goToFacebook;
String urlAmazon ="https://www.amazon.com";
String urlFacebook="https://www.facebook.com";
String urlDestination;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
goToAmazon=v.findViewById(R.id.goToAmazon);
goToFacebook=v.findViewById(R.id.goToFacebook);
goToAmazon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
urlDestination=urlAmazon;
}
});
goToFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
urlDestination=urlFacebook;
}
});
return v;
}
Which code should I put in onClick() method to load the specific address in the webview and display the fragment containing webview?

Related

Send data from Main Activity to Fragment not through intent or bundle but through interface in android?

My question is simple how to send data from Main activity to fragment through interface but not through intent or bundle in android.
Please guide me thanks.
Here is my code from fragment to Activity data send through interface but I want against it Activity to fragment which I don't know how to do.
public interface OnRestaurantSelectedListener {
public void onRestaurantSelected(String s);
}
MainActivity extends AppCompatActivity implements OnRestaurantSelectedListener{
String mPosition;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onRestaurantSelected(String s) {
mPosition =s;
}
}
In fragment:
public class ListFragment extends Fragment {
...
private OnRestaurantSelectedListener mOnRestaurantSelectedListener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mOnRestaurantSelectedListener = (OnRestaurantSelectedListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + e.getMessage());
}
}
mOnRestaurantSelectedListener.onRestaurantSelected("AliResturant");
}
Create interface FragmentCommunicator as,
public interface FragmentCommunicator{
public void passDataToFragment(String someValue);
}
In your main Activity we can use interface and pass data to fragment. Like below,
public class MainActivity extends FragmentActivity{
//interface through which communication is made to fragment
public FragmentCommunicator fragmentCommunicator;
private Button fragmentButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.title_viewpager);
fragmentButton = (Button)findViewById(R.id.fragmentButton);
setUIListeners();
}
private void setUIListeners(){
fragmentButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(fragmentCommunicator != null)
fragmentCommunicator.passDataToFragment("Hi from FragmentActivity");
}
});
}
}
Access passed data in fragment like below,
public class CustomFragment extends Fragments implements FragmentCommunicator{
public Context context;
private Button activityButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.activity_frag, container, false);
activityButton =(Button)fragmentView.findViewById(R.id.activityButton);
textView =(TextView)fragmentView.findViewById(R.id.textView);
setRetainInstance(true);
return fragmentView;
}
//FragmentCommunicator interface implementation
#Override
public void passDataToFragment(String someValue){
String activityAssignedValue = someValue;
textView.setText(activityAssignedValue);
}
}

NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setMenuVisibility(boolean)' on a null object reference

I am trying to implement viewpager with Tablayout. In this everything is fine working properly, but the one problem is when i come back from another screen view pager lost their position with Tablayout and when i scroll its crash the app.I find many solutions but all of these cannot work for this. Here is my code Adapter Class:-
public class Portfolio_Adapter extends FragmentStatePagerAdapter {
int tabCount;
public Portfolio_Adapter(FragmentManager fm,int tabCount) {
super(fm);
this.tabCount=tabCount;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Websites_Fragment websites_fragment=new Websites_Fragment();
return websites_fragment;
case 1:
Mobileapplication_fragment mobileapplication_fragment=new Mobileapplication_fragment();
return mobileapplication_fragment;
case 2:
Graphics_Fragment graphics_fragment=new Graphics_Fragment();
return graphics_fragment;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
Fragment class:-
public class Portfolio_fragment extends Fragment {
TabLayout tabLayout;
ViewPager viewPager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.portfolio_fragment, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Portfolio");
tabLayout = (TabLayout) view.findViewById(R.id.portfolio_tabLayout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addTab(tabLayout.newTab().setText("Websites"));
tabLayout.addTab(tabLayout.newTab().setText("Mobile Application"));
tabLayout.addTab(tabLayout.newTab().setText("Graphics"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) view.findViewById(R.id.portfolio_pager);
Portfolio_Adapter adapter = new Portfolio_Adapter(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
ViewGroup slidingTabStrip = (ViewGroup) tabLayout.getChildAt(0);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
View tab = slidingTabStrip.getChildAt(i);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tab.getLayoutParams();
layoutParams.weight = 1;
tab.setLayoutParams(layoutParams);
}
return view;
}
}
Your code is right you only have to change the placement of code put your
tabLayout.setupWithViewPager(viewPager);
,
tabLayout.addTab(tabLayout.newTab().setText("Websites"));
tabLayout.addTab(tabLayout.newTab().setText("Mobile Application"));
tabLayout.addTab(tabLayout.newTab().setText("Graphics"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
after setadapter in viewPager
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3);

Android Code for Refresh Button that destroys and recreates Text MediaPlayer (Hangs)!

viewPager4 Fragment Activities
If I click on the Texts that play short sounds, one after another then after sometimes the mediaplayer hangs and doesn't play any sound. But if I'm able to destroy activity and recreate the same activity with refresh button in Action Bar, I'd be able to click sounds again.
So what to write in the code for R.id.item2?
Or there is any other way that continuous clicking on short sounds by these texts is possible without any hang kind of problem?
Following is the reference code:
public class module1 extends FragmentActivity {
static Context con;
static int length = 0;
ViewPager mViewPager;
SectionsPagerAdapter mSectionsPagerAdapter;
static MediaPlayer mediaplayer, mediaplayert, m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
con = this;
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mains, menu);
// Just .main into .mains [created new for different behavior of Action Bar]
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.item1) {
Intent in = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.google.com"));
startActivity(in);
}
if (item.getItemId() == R.id.item2) {
//what should i write here? to destroy and recreate the same fragment activity again.
//Problem: After clicking fast on one after another text links, mediaplayert hangs and doesnt play
//Solution: exit app destroy and reopen, then mediaplayer works fine...
//SO, what to write here? kindly help!
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment ff = new DummySectionFragment1();
switch (arg0) {
case 0:
ff = new DummySectionFragment1();
break;
}
Bundle args = new Bundle();
args.putInt(DummySectionFragment1.ARG_SECTION_NUMBER, arg0 + 1);
ff.setArguments(args);
return ff;
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int arg0) {
Locale l = Locale.getDefault();
switch (arg0) {
case 0:
return getString(R.string.title_section27).toUpperCase(l);
}
return null;
}
}
public static class DummySectionFragment1 extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.m01set01, container, false);
// Genius Shot by Stupid vIC//
TextView Text = (TextView) rootView.findViewById(R.id.textView2);
Text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound1);
mediaplayert.start();
}
});
TextView Text1 = (TextView) rootView.findViewById(R.id.textView4);
Text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound2);
mediaplayert.start();
}
});
TextView Text2 = (TextView) rootView.findViewById(R.id.textView6);
Text2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound3);
mediaplayert.start();
}
});
return rootView;
}
}
#Override
protected void onDestroy() {
if (mediaplayert != null) {
mediaplayert.stop();
mediaplayert= null;
}
super.onDestroy();
}
}

Getting a Fragment inside a ViewPager in Android using getRegisteredFragment returns null

I've been searching a lot and I can't make it work.
I have a problem trying to get fragments inside a viewpager with a tabstrip.
I've implemented a SparseArray as I read here and several methods that I found here but I can't make it work.
The thing is that everytime I call adapter.getRegisteredFragment(position).. I always receive null unless I made it inside the onPageSelected event of the tabsStrip, there it works.. but I don't want to get the fragments there.
Those are my classes:
My fragment:
public class WeekFragment extends Fragment implements View.OnClickListener
{
private static final String ARG_POSITION = "position";
private int position;
private LinearLayout[] btns;
public static WeekFragment newInstance(int position) {
WeekFragment f = new WeekFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
fillFragment();
}
private void fillFragment()
{
// Irrelevant stuff..
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance)
{
return inflater.inflate(R.layout.week_fragment, container, false);
}
#Override
public void onClick(View v)
{
// Irrelevant stuff
}
public LinearLayout[] getBtns()
{
return btns;
}
public void setBtns(LinearLayout[] btns)
{
this.btns = btns;
}
}
My adapter:
public class WeekAdapter extends FragmentPagerAdapter
{
Calendar cal;
Context context;
SparseArray<Fragment> registeredFragments;
private String[] TITLES = new String[6];
public WeekAdapter(FragmentManager fm, Context context)
{
super(fm);
registeredFragments = new SparseArray<>();
this.context = context;
fillTitles();
}
private void fillTitles()
{
// Fill titles
}
#Override
public CharSequence getPageTitle(int position)
{
return TITLES[position];
}
#Override
public int getCount()
{
return TITLES.length;
}
#Override
public Fragment getItem(int position)
{
return WeekFragment.newInstance(position);
}
#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);
}
}
and my activity:
public class MyActivity extends FragmentActivity
{
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private WeekAdapter adapter;
private List<DayResumeItem> listDayResumesItems;
private User u;
private View mProgressView;
private View mRotaView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rota2);
mProgressView = findViewById(R.id.view_progress);
mRotaView = findViewById(R.id.view_rota);
this.u = this.getIntent().getExtras().getParcelable(getString(R.string.parcel_user));
// Initialize the ViewPager and set an adapter
pager = (ViewPager) findViewById(R.id.pager);
adapter = new WeekAdapter(getSupportFragmentManager(), getApplicationContext());
pager.setAdapter(adapter);
// Bind the tabs to the ViewPager
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);
tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
WeekFragment f = (WeekFragment)adapter.getRegisteredFragment(week);
// Do stuff.. Here, f is not null. Here I can work, but I don't want to.
}
#Override
public void onPageSelected(int position)
{
}
#Override
public void onPageScrollStateChanged(int state)
{
}
});
WeekFragment f = (WeekFragment)adapter.getRegisteredFragment(week);
// Do stuff.. Here, f is null and I can't work.
}
#Override
protected void onResume()
{
super.onResume();
getList();
}
}
It is everytime I call adapter.getRegisteredFragment(position) on my activity where it crash because it always return null..
I swear that I've been searching a lot but I'm unable to make it work.
Thank you very much everybody!
I think my problem was that I was calling this adapter.getRegisteredFragment(position) in the onCreate of my activity, and in the onCreate, the viewpager is still not fully loaded and the registeredFragments aren't still instantiated, so the list is still empty..
If you move this callings to another place when the viewpager is fully loaded, it will work.
The items in registeredFragments are initialized in instantiateItem() method, which should be called during the process of drawing views. And this drawing process happens after onCreate()/onResume().
I am not sure what stuff you want to do by getting Fragment in onCreate(), but generally it is not a good idea since the Fragment is not initialized at that moment. You should access the fragment in onPageSelected() as you said.

troubled passing data from asynctask to fragment

I seek to receive data from AsyncTask inside a fragment. I'm aware to achieve this with activity but having difficulties in fragment.
GetResult class
public interface GetResult {
void getData(ArrayList<String> result);
}
myFrag class
public class myFrag extends Fragment implements GetResult{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.myFrag_layout, container, false);
Button myBtn = (Button) view.findViewById(R.id.Button1);
myBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
myAsync obj = new myAsync();
obj.setListener(getActivity());
}
});
}
}
myAsync class
public class myAsync extends AsyncTask<Void, Void, String>{
GetResult interfaceObj = null;
public void setListener( GetResult interfaceObj ) {
this.interfaceObj = interfaceObj;
}
}
I'm having problem with obj.setListener(getActivity). It say The method setListener(GetResult) in the type myAsync is not applicable for the arguments (FragmentActivity). Thanks in advance to everyone.
I didn't figured out wt the problem is but there is another way to do it. I'll just share it here.
1st the interface class GetResult.class is same
2nd Changes in the fragment class myFrag.class
public class myFrag extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.myFrag_layout, container, false);
Button myBtn = (Button) view.findViewById(R.id.Button1);
myBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
getLoc obj = new getLoc(getActivity(), new GetResultInterface() {
#Override
public void processFinish(ArrayList<String> result) {
// U can get the result here
}
obj.execute(url);
});
}
}
3rd In AsyncTask myAsync.class
public class myAsync extends AsyncTask<Void, Void, String>{
Context context;
GetResult interfaceObj = null;
public myAsync(Context context, GetResultInterface interfaceObj) {
this.context = context;
this.interfaceObj = interfaceObj;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
interfaceObj.processFinish(result);
}
}

Resources