How to get String Resource within ViewPager Adapter?
If you are trying to access string resources from outside of an activity, then you need to pass the context in to that class (which you stated you have already done), and then call
String str = context.getResources().getString(R.string.some_string);
Also check your strings.xml
file to make sure that you are using the string id correctly.
If you're using android studio you should be able to simply start typing R.string.
and it will then show suggestions from the strings.xml file. If you do not see your resource here, then that may indicate a problem with the way you are storing your resources, as opposed to how you are trying to access them.
you should call getString from an activity's context, change your code to
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
Context context;
public ViewPagerAdapter(FragmentManager fm, Context nContext) {
super(fm);
context = nContext;
}
@Override
public int getCount() {
return PAGE_COUNT;
}
@Override
public Fragment getItem(int position) {
return PageFragment.create(position + 1);
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return context.getString(R.string.title1);
case 1:
return context.getString(R.string.title1);
case 2:
return context.getString(R.string.title1);
}
return null;
}
}
Well, according to your error message you do not have a String with the ID you are requesting.
Could it be that you are supporting multi languages and only have this kind of String-ID for a specific language?
Anyways, this line of code:
String yourstring = getResources().getString(R.string.yourstring);
is how to get a String from Resources. getResources()
can be called whenever you are in a class extending Context
, such as Activity
.