Search code examples
androidandroid-viewpagerandroid-resources

How to get String Resource within ViewPager Adapter?


I trying to set the title for my viewpager, I can't seem to get it to work. I tried Resources.getSystem().getString(R.string.title1); and also tried to pass a context. Could anyone help me?

public class ViewPagerAdapter extends FragmentPagerAdapter {
    final int PAGE_COUNT = 3;
    Context context;

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @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 Resources.getSystem().getString(R.string.title1);

        case 1:
            return Resources.getSystem().getString(R.string.title1);

        case 2:
            return Resources.getSystem().getString(R.string.title1);
        }

        return null;
    }
}

Logcat:

09-02 17:40:33.160: E/AndroidRuntime(3116): FATAL EXCEPTION: main
09-02 17:40:33.160: E/AndroidRuntime(3116): android.content.res.Resources$NotFoundException: String resource ID #0x7f050003
09-02 17:40:33.160: E/AndroidRuntime(3116):     at android.content.res.Resources.getText(Resources.java:230)
09-02 17:40:33.160: E/AndroidRuntime(3116):     at android.content.res.Resources.getString(Resources.java:314)

Solution

  • 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.