简体   繁体   中英

Java open Fragment from MainActivity

I have a Main Activity which hosts a tabsAdapter and ViewPager for my different Fragments. I am trying to open the second Fragment (Special Fragment) from my main activity. Below is the code, which fails to start the Special Fragment, and secondly, fails to be able to reference methods from within Special Fragment. Please help!

Main Activity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Day Events"));
    tabLayout.addTab(tabLayout.newTab().setText("Special Events"));
    tabLayout.addTab(tabLayout.newTab().setText("Notifications"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
    final TabsAdapter tabsAdapter = new TabsAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(tabsAdapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    
    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) {

        }
    });

    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        if (bundle.getString("fragment") != null) {

            SpecialFragment specialFragment = (SpecialFragment) tabsAdapter.getItem(1);
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.view_pager, specialFragment).commit();

            specialFragment.setLocation("TEST");

Special Fragment snippet:

public void setLocation(String location)
{
    txtLocation = v.findViewById(R.id.txtLocationSpecialEvent);
    txtLocation.setText(location);
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/fragment_container"
tools:context=".MainActivity">

<androidx.appcompat.widget.Toolbar
    android:id="@+id/tool_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tool_bar"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<androidx.viewpager.widget.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_below="@id/tab_layout"/>

OK, I have managed to switch to the Special Fragment using

viewPager.setCurrentItem(1);

            SpecialFragment specialFragment = (SpecialFragment) tabsAdapter.getItem(1);
            specialFragment.setLocation(bundle.getString("location"));

However, setLocation method in Special Fragment seems to cause a problem:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.scrollingtext/com.example.scrollingtext.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
    at com.example.scrollingtext.SpecialFragment.setLocation(SpecialFragment.java:359)
    at com.example.scrollingtext.MainActivity.onCreate(MainActivity.java:73)

Note that v = View is initiated in the OnCreateView in

v = inflater.inflate(R.layout.special_layout, viewGroup, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM