Access to getString() in a fragment that implements a viewpager - android

I am using a nested fragment using SherlockFragment, all works fine. But i am not being able to make viewpager title to string so that i can support multilanguage using string.xml.
Here is my code
public class schedule_pl extends SherlockFragment {
private static String titles[] = new String[] { "Portugal", "Lisbon" , "Azores" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_pager, container, false);
// Locate the ViewPager in viewpager_main.xml
ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
// Set the ViewPagerAdapter into ViewPager
mViewPager.setAdapter(new MyAdapter (getChildFragmentManager()));
return view;
}
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class
.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position)
{
case 0:
return new place();
case 1:
return new place2();
case 2:
return new place3();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
public static class place extends Fragment {
public place() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container,
false);
return rootView;
}
}
public static class place3 extends Fragment {
public place3() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment2, container,
false);
return rootView;
}
}
public static class place2 extends Fragment {
public place2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment3, container,
false);
return rootView;
}
}
}
on getPageTitle i can't that working with strings and already tried several methods.
Access to getString() in android.support.v4.app.FragmentPagerAdapter?
This is a question similar on the site but neither answer got me on the right path.
I tried using this:
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getcontext.getString(R.string.title_section_schedule1).toUpperCase(l);
case 1:
return getcontext.getString(R.string.title_section_schedule2).toUpperCase(l);
case 2:
return getcontext.getString(R.string.title_section_schedule3).toUpperCase(l);
}
return null;
}
But do not work. Anyone knows the solution to this?

You can pass the Activity to your adapter constructor.
mViewPager.setAdapter(new MyAdapter (getChildFragmentManager(), getActivity()));
then in MyAdapter:
//declare a private variable for the activity
private Activity myActivity;
public MyAdapter(FragmentManager fm, Activity myActivity) {
super(fm);
this.myActivity = myActivity;
}
then in your getPageTitle
...
return myActivity.getString(R.String.title_section_scheduale1).toUpperCase(l);
...
Try it out hope it works for you.

Related

How to add function in fragment

EDIT:
I'm new in android and i try to use fragments in my app. I try to use a fragment function in my activity but i got a null pointer exception..
Fragment:
public class VideoviewFragment extends Fragment {
private View card;
public static VideoviewFragment create() {
return new VideoviewFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_videoview, container, false);
card = (View) view.findViewById(R.id.card_video);
return view;
}
public void setalphacard(float value){
card.setAlpha(value);
}
}
In main activity i want to do that for example (i simplified my code):
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Viewpager
final SmartFragmentStatePagerAdapter adapterViewPager;
final ViewPager viewPager = (ViewPager) findViewById(R.id.am_view_pager);
adapterViewPager = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapterViewPager);
final VideoviewFragment videoviewFragment = (VideoviewFragment) adapterViewPager.getRegisteredFragment(2);
videoviewFragment.setalphacard(0.3f);
}
}
Main pager adapter:
public class MainPagerAdapter extends SmartFragmentStatePagerAdapter {
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;
}
}
You just have to declare the View globally like this:
public class VideoviewFragment extends Fragment {
private View card;
public static VideoviewFragment create() {
return new VideoviewFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_videoview, container, false);
card = (View) view.findViewById(R.id.card_video);
return view;
}
public void setalphacard(float value){
card.setAlpha(value);
}
}
Declare your View Object globally in your fragment.

TextView from ViewPager is throwing Null Pointer Exception

I have a fragment with a ViewPager inside it. In the ViewPager I have 4 content screens so swipe around in. The content has a few TextView components and I'm trying to access them from the first fragment, however when I go to use setText or similar I get a null pointer exception. Ive checked and the id for the TextView is valid, and I've done a clean build.
Here is a snippet of my relevant code:
private TextView textViewOne;
private PagerAdapter mPagerAdapter;
private ViewPager pager;
View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_viewpager, container, false);
InitializePaging();
textViewOne = (TextView) rootView.findViewById(R.id.create_name);
//would return null if I did this:
textViewOne.setText("test");
return rootView;
}
private void InitializePaging() {
mPagerAdapter = new ViewPagerAdapter(getContext(), getChildFragmentManager(),
Arrays.asList(PageOne.class, PageTwo.class, PageThree.class, PageFour.class));
pager = (ViewPager) rootView.findViewById(R.id.content_pager);
pager.setAdapter(mPagerAdapter);
}
The PageOne class:
public class PageOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(container == null) {
return null;
}
return (LinearLayout) inflater.inflate(R.layout.fragment_page_one, container, false);
}
}
This is the fragment_layout_viewpager xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/content_pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
You are inflating fragment_layout_viewpager, so the create_name should exist in that layout, otherwise it will throw a null pointer.
Create an interface with 1 abstract method. Let the Fragment implement the interface and call the callback method from Activity.In the below example, I try to pass value on click of button from MainActivity to ThirdFragment.
public interface FragmentCommunicator {
public void passDataToFragment(String someValue);
}
public class MainActivity extends FragmentActivity {
FragmentCommunicator fragmentCommunicator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn= (Button)findViewById(R.id.button) ;
btnsetOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
randomvalue= getRansomString();
if(fragmentCommunicator!=null)
fragmentCommunicator.passDataToFragment(randomvalue);
}
});
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
default: return FirstFragment.newInstance("FirstFragment,Instance 1");
}
}
#Override
public int getCount() {
return 2;
}
}
public static class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText(getArguments().getString("msg"));
return v;
}
public static FirstFragment newInstance(String text) {
Log.e("FirstFragment","newInstance called");
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
public class ThirdFragment extends Fragment implements FragmentCommunicator {
TextView tv;
String value="";
public FragmentCommunicator fragmentCommunicator;
#Override
public void passDataToFragment(String someValue) {
this.value = someValue;
tv.setText(value);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
((MainActivity)activity).fragmentCommunicator = this;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement FragmentCommunicator");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
value=getArguments().getString("msg");
tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText(value);
return v;
}
public static ThirdFragment newInstance(String text) {
ThirdFragment f = new ThirdFragment();
Bundle b = new Bundle();
b.putString("msg",text);
f.setArguments(b);
return f;
}
}

Log Error in Nested Fragments on View Pager : No view found for id

I have a fragment that Contains view pager.there are three fragments in that Main fragment they are Fragment A,Fragment B,Fragment C. Upto this code runs properly.
Then i added a new Fragment and called via Fragment A then i got the error in the Log
No view found for id 0x7f0d0083 (com.app.sanyog:id/frame) for fragment SearchPlaces{289bf4e #0 id=0x7f0d0083}
Main Fragment:
/**
* Created by Admin on 04-06-2015.
*/
public class ContentFragment_Flight_Bkg extends Fragment {
private View view;
public ViewPager pager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_fragment_flight,container,false);
TabsPagerAdapter adapter = new TabsPagerAdapter(getFragmentManager());
pager = (ViewPager)view.findViewById(R.id.pager);
pager.setAdapter(adapter);
return view;
}
}
Pager Adapter
public class TabsPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
// Tab Titles
private String tabtitles[] = new String[] { "One Way", "Round Trip", "Multicity" };
Context context;
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
OneWayTab fragmenttab1 = new OneWayTab();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
RoundTripTab fragmenttab2 = new RoundTripTab();
return fragmenttab2;
// Open FragmentTab3.java
case 2:
MultiCityTab fragmenttab3 = new MultiCityTab();
return fragmenttab3;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
Fragment A
public class OneWayTab extends Fragment {
private LinearLayout oneway_source,oneway_destiantion;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab3.xml
View view = inflater.inflate(R.layout.content_one_way_tab, container, false);
oneway_source = (LinearLayout)view.findViewById(R.id.oneway_source_layout);
oneway_destiantion = (LinearLayout)view.findViewById(R.id.oneway_destination_layout);
oneway_source.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SearchPlaces fragment_Flight= new SearchPlaces();
android.support.v4.app.FragmentTransaction fragmentTransaction_Flight = getChildFragmentManager().beginTransaction();
fragmentTransaction_Flight.replace(R.id.frame,fragment_Flight,"FLight_booking");
fragmentTransaction_Flight.commit();
}
});
oneway_destiantion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Utils.showToast(getActivity(),"Destiantion");
}
});
return view;
}
}
New Fragment (Called from Fragment A)
public class SearchPlaces extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.content_search_places, container, false);
return view;
}
}

Updating data in viewpager

How i can update data in my case
public class SpaFragment extends Fragment {
public SpaFragment(){}
private SpaList mSpa;
private TabHost tabs;
private View rootView;
private ViewPager pager;
private PagerAdapter pagerAdapter;
public void setSpa(SpaList s)
{
mSpa=s;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.spa_tab_fragment, container, false);
FragmentManager f = ((FragmentActivity) getActivity()).getSupportFragmentManager();
pagerAdapter = new MyPagerAdapter( f );
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(pagerAdapter);
pagerAdapter.notifyDataSetChanged();
Log.d(""+mSpa.getSpaName(),"");
return rootView;
}
private class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
Resources res = getResources();
String[] title = res.getStringArray(R.array.title_spa_viewpager_array);
return title[position];
}
#Override
public android.support.v4.app.Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance(mSpa.getSpaName());
case 1: return SecondFragment.newInstance(mSpa.getSpaAddr());
case 2: return SecondFragment.newInstance(mSpa.getCityEngName());
default: return FirstFragment.newInstance(mSpa.getSpaPhone());
}
}
#Override
public int getCount() {
return 3;
}
}
}
and fragment code
public class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.viewpager_tab_text, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText(getArguments().getString("msg"));
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}

ViewPager inside Fragment causes NullPointerException

I am trying to use ViewPager inside a Fragment and get
03-01 15:23:05.375 3937-3937/com.example.android.navigationdrawerexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.android.navigationdrawerexample.SpaFragment.onCreateView(SpaFragment.java:50)
at android.app.Fragment.performCreateView(Fragment.java:1695)
Code:
public class SpaFragment extends Fragment {
public SpaFragment(){}
private SpaList mSpa;
private TabHost tabs;
private FragmentActivity mFragmentActivity;
private View rootView;
public void setSpa(SpaList s)
{
mSpa=s;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_spa, container, false);
ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(new MyPagerAdapter(mFragmentActivity.getSupportFragmentManager()));
return rootView;
}
#Override
public void onAttach(Activity activity) {
mFragmentActivity = (FragmentActivity) activity;
Log.d("ACTIVITY on attach"+mFragmentActivity,"\n");
super.onAttach(activity);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return "Title " + position;
}
#Override
public android.support.v4.app.Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
default: return FirstFragment.newInstance("ThirdFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
}
You are running into a NullPointerException because you are invoking a method on an object that is NULL at that time.
This could be because your
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// ...
}
method is called before your
#Override
public void onAttach(Activity activity) { }
method, and therefore, your variable mFragmentActivity is NULL. In that case, your code
String.valueOf(mFragmentActivity);
will throw a NullPointerException.

Categories

Resources