Send data from activity to fragment using Tab Layo

2020-05-06 11:43发布

I created a Tab Layout with Swipeable Views using this tutorial. I'm trying to pass a string from Activity to Fragment. I read about fragment communication and couple other topics on stackoverflow but still i get null pointer exception. Here's my code:

MainActivity.java

public class MainActivity extends FragmentActivity {
    private static final int REQUEST_CODE_EMAIL = 1;
    String password, email;

    ViewPager viewPager;
    TabsPagerAdapter tabsPagerAdapter;
    ActionBar actionBar;

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

        tabsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
        viewPager = (ViewPager) findViewById(R.id.pager);
        viewPager.setOnPageChangeListener(
                new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        actionBar = getActionBar();
                        actionBar.setSelectedNavigationItem(position);
                    }
                });
        viewPager.setAdapter(tabsPagerAdapter);
        actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        ActionBar.TabListener tabListener = new ActionBar.TabListener() {
            @Override
            public void onTabReselected(android.app.ActionBar.Tab tab,
                                        FragmentTransaction ft) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
                viewPager.setCurrentItem(tab.getPosition());

            }

            @Override
            public void onTabUnselected(android.app.ActionBar.Tab tab,
                                        FragmentTransaction ft) {
                // TODO Auto-generated method stub
            }
        };
        actionBar.addTab(actionBar.newTab().setText("Głowna").setTag("main").setTabListener(tabListener));
        actionBar.addTab(actionBar.newTab().setText("Rachunki").setTag("bills").setTabListener(tabListener));

        Bundle bundle=new Bundle();
        bundle.putString("email", "emasiofnasdbjk");
        EnterExitFragment enterExitFragment = new EnterExitFragment();
        android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.pager, enterExitFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

activity_main.xml

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</android.support.v4.view.ViewPager>

TabsPagerAdapter.java

public class TabsPagerAdapter extends FragmentStatePagerAdapter {

    public TabsPagerAdapter(FragmentManager fragmentManager){
        super(fragmentManager);
    }
    @Override
    public Fragment getItem(int i) {

        switch (i){
            case 0:
                return new EnterExitFragment();
            case 1:
                return new BillsFragment();
        }
        return null;
    }

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

EnterExitFragment.java

public class EnterExitFragment extends Fragment{
    TextView tvFloor1, tvFloor2, tvEmail;
    Button btnSend;
    Integer floorId, segmentId, spaceId, ticketId;
    String floorName, segmentName, spaceName;
    String email;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.activity_enter_exit, container, false);

        tvEmail = ((TextView)rootView.findViewById(R.id.textEmail));
        tvFloor1 = ((TextView)rootView.findViewById(R.id.textFloor1));
        tvFloor2 = ((TextView)rootView.findViewById(R.id.textFloor2));
        new FloorFreeSpaces(EnterExitFragment.this).execute();

        btnSend = ((Button)rootView.findViewById(R.id.btnSend));
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Floor(EnterExitFragment.this).execute();
                email = getArguments().getString("email"); //line 55
                tvEmail.setText(email);
            }
        });
        return rootView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

activity_enter_exit.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/textFloor1"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/textFloor2"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:layout_width="354dp"
        android:layout_height="93dp"
        android:text="Email:"
        android:id="@+id/textEmail"
        android:layout_gravity="center_horizontal|bottom" />

    <Button
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:text="SEND"
        android:id="@+id/btnSend"
        android:layout_gravity="center_horizontal|bottom" />

    </LinearLayout>

error log

java.lang.NullPointerException
            at com.carpark.EnterExitFragment$1.onClick(EnterExitFragment.java:55)
            at android.view.View.performClick(View.java:4240)
            at android.view.View$PerformClick.run(View.java:17722)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5303)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
            at dalvik.system.NativeStart.main(Native Method)

Has anyone solution for my problem? :)

2条回答
SAY GOODBYE
2楼-- · 2020-05-06 11:53

EDIT: My suggestion is to make the following constructor which takes Bundle object as an argument:

public EnterExitFragment(Bundle bundle) {
    super();
    setArguments(bundle);
}

and call that constructor with bundle object as the argument instead of the default one in your program. That way you're sure to add the bundle before you attach it to your Activity.

Additionally, if that doesn't work, add a Bundle attribute to your EEF class, initialize it within your constructor and refer to it rather than getArguments() method:

public class EnterExitFragment extends Fragment{
    TextView tvFloor1, tvFloor2, tvEmail;
    Button btnSend;
    Integer floorId, segmentId, spaceId, ticketId;
    String floorName, segmentName, spaceName;
    String email;
    Bundle args;

    public EnterExitFragment(Bundle bundle) {
        super();
        args = bundle;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.activity_enter_exit, container, false);

        tvEmail = ((TextView)rootView.findViewById(R.id.textEmail));
        tvFloor1 = ((TextView)rootView.findViewById(R.id.textFloor1));
        tvFloor2 = ((TextView)rootView.findViewById(R.id.textFloor2));
        new FloorFreeSpaces(EnterExitFragment.this).execute();

        btnSend = ((Button)rootView.findViewById(R.id.btnSend));
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Floor(EnterExitFragment.this).execute();
                email = args.getString("email"); //line 55
                tvEmail.setText(email);
            }
        });
        return rootView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
查看更多
聊天终结者
3楼-- · 2020-05-06 11:56

I do not see that you set your argument to fragment. If you did, but you forgotten to write please inform me...

Bundle bundle=new Bundle();
bundle.putString("email", "emasiofnasdbjk");
EnterExitFragment enterExitFragment = new EnterExitFragment();
enterExitFragment.setArguments(bundle); // This line is needed...
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.pager, enterExitFragment);
transaction.addToBackStack(null);
transaction.commit();
查看更多
登录 后发表回答