0

I am new to Java/android/stackoverflow, so please forgive any stupid mistakes.

here are is the tutorial I was working off of, and here are some posts from stackoverflow that I was using as reference.

tutorial

post1

post2

My code has a good bit of other stuff in it, but right now I am having trouble setting text on a fragment.

Fragment A (fragment_class) has an TextView embedded that I would like to change programatically

public  class fragment_class extends Fragment {

public static final String ARG_SECTION_NUMBER = "section_number";
private static TextView tv;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment, container, false);
    tv = (TextView)v.findViewById(R.id.temperature);
    return v;
}

public void setText(String str){
    tv.setText(str);
}

}

fragment B (BT) has the OnClickListener that will create the change

public class BT extends Fragment{


    public static final String ARG_SECTION_NUMBER = "section_number";

    public fragCommander commander;

    public interface fragCommander{
        void sText(String str);
    }


@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        commander = (fragCommander)context;
    }catch (ClassCastException e){
        throw new ClassCastException(context.toString());
    }
}

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_1, container, false);
        final Button fbt = (Button)v.findViewById(R.id.fbtbutton);
        fbt.setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View v) {
                        commander.sText("chicken");
                    }
                }
        );
        return v;
    }

}

MainActivity implements an interface

public class MainActivity extends FragmentActivity implements         ActionBar.TabListener, BT.fragCommander {
Context context;
SectionsPagerAdapter mSectionsPagerAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    setContentView(R.layout.sample_main);
    context = getApplicationContext();
    final ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    }

    mSectionsPagerAdapter = new     SectionsPagerAdapter(getSupportFragmentManager());


    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);


    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            assert actionBar != null;
            actionBar.setSelectedNavigationItem(position);
        }
    });


    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {

        assert actionBar != null;
        actionBar.addTab(
                actionBar.newTab()
                        .setText(mSectionsPagerAdapter.getPageTitle(i))
                        .setTabListener(this));
    }



}


@Override
public void sText(String str) {

    fragment_class fc = (fragment_class) getSupportFragmentManager().findFragmentById(R.id.frag_layout);
    fc.setText(str);
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, tell the ViewPager to switch to the corresponding page.
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                BT btFrag = new BT();
                Bundle args = new Bundle();
                args.putInt(btFrag.ARG_SECTION_NUMBER, position + 1);
                btFrag.setArguments(args);
                return btFrag;

            case 1:
                Fragment fragment2 = new DummySectionFragment2();
                Bundle args2 = new Bundle();
                args2.putInt(DummySectionFragment2.ARG_SECTION_NUMBER, position + 2);
                fragment2.setArguments(args2);
                return fragment2;



            case 2:

                Fragment object = new fragment_class();
                Bundle args3 = new Bundle();
                args3.putInt(fragment_class.ARG_SECTION_NUMBER, position + 3);
                object.setArguments(args3);
                return object;

            case 3:
                Fragment fragment4 = new DummySectionFragment4();
                Bundle args4 = new Bundle();
                args4.putInt(DummySectionFragment4.ARG_SECTION_NUMBER, position + 4);
                fragment4.setArguments(args4);
                return fragment4;


            default:
                return null;
        }

    }


    @Override
    public int getCount() {
        return 4;
    }


    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            case 3:
                return getString(R.string.title_section4).toUpperCase(l);
        }
        return null;
    }

}

error message

10-27 22:56:39.712  19163-19163/com.example.android.horizontalpaging     E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.android.horizontalpaging, PID: 19163
java.lang.NullPointerException: Attempt to invoke virtual method 'void  com.example.android.horizontalpaging.fragment_class.setText(java.lang.String)'  on a null object reference
        at com.example.android.horizontalpaging.MainActivity.sText(MainActivity.java:97)
        at com.example.android.horizontalpaging.BT$1.onClick(BT.java:43)
        at android.view.View.performClick(View.java:4785)
        at android.view.View$PerformClick.run(View.java:19869)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:155)
        at android.app.ActivityThread.main(ActivityThread.java:5696)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

adding XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:id="@+id/frag_layout">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:id="@+id/temperature"
    android:layout_gravity="center" />
</LinearLayout>

Ok, I figured out the problem, I was trying to set text on a different fragment than the one being shown. The Pager was destroying the fragment I was referencing. So under the OnCreate method I added this line mViewPager.setOffscreenPageLimit(4);.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    setContentView(R.layout.sample_main);
    context = getApplicationContext();
    final ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    }


    // Create the adapter that will return a fragment for each of the three primary sections
    // of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());


    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    // added line
    mViewPager.setOffscreenPageLimit(4);

After that I created a method in the fragment that set text, and I could set the text from any fragment after that.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.fragment, container, false);
    tv = (TextView)v.findViewById(R.id.temperature);
    return v;
}


public void settext(String str){
    if (tv != null) {
        tv.setText(str);
    }
}
Community
  • 1
  • 1
sup
  • 1
  • 2
  • It means your `TextView` in `fragment_class` is still `NULL` when you are setting it. Also you are finding fragment by id not by layout `findFragmentById(R.id.frag_layout)` it needs a FragmentID – Murtaza Khursheed Hussain Oct 28 '15 at 04:14
  • it might not be the best name, but the ID is frag_layout (i think). Your first statement, I know that's what the error means, I just can't figure out how to fix it. It should get a reference to temperature as soon as the fragment is created, then later after that I click a button and it runs setText on that object tv. Correct me if i'm wrong. – sup Oct 29 '15 at 01:13
  • Ok, after doing some more research, I was wrong you were right. frag_layout is a layout not a fragmentID. I found some solutions [https://gist.github.com/jacek-marchwicki/d6320ba9a910c514424d] [http://stackoverflow.com/questions/18609261/getting-the-current-fragment-instance-in-the-viewpager?lq=1] to get the fragment ID on a pager, but none seem like a very straight forward solution. I think I am going to try redo the code and get rid of fragments. – sup Oct 29 '15 at 03:07
  • Fragments inserted through the `` tag can be found using `findFragmentById` and those which are added programaticaly can't. – Murtaza Khursheed Hussain Oct 29 '15 at 04:02

0 Answers0