-->

Unable to pass data from Activity to fragment. get

2019-08-20 17:18发布

问题:

Please help me, I use a navigation drawer and fragment.When the user presses the login button I retrieve user data and send it to the variable in the fragment. but when fragment is called the variable value in the fragment is null. How can the value not be null. Below is the code :

public class RecyclerViewBookingFragment extends Fragment implements DatePickerDialog.OnDateSetListener {
    private static final String TAG = RecyclerViewBookingFragment.class.getSimpleName();
    private View dialogView;


    private LayoutInflater inflater;
    private AlertDialog.Builder dialog;
    private ProgressDialog pDialog;
    private Context context;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerViewBookingAdapter adapter;
    private List<Booking> bookingList = new ArrayList<>();
    private static final Helper helper = new Helper();
    private EditText editTextRelasi, editTextKapal, editTextAlamatKapal, editTextTanggal, editTexttglPengajuan, editTextKuota, EditTextUserIDPass, editTextUnamePass, editTextPasslama, editTextPassnew;
    private String userid, namaRelasi, tanggalPembuatan, namaKapal, tanggalAntri, kuotaBongkar, createdBy, createdDevice, statusBongkar;
    private long detailIDuser, groupidx;
    public String useridx, usernamex, groupNamex, namaKapalx, alamatKapalx, passwordx;

    public RecyclerViewBookingFragment() {
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }



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

        View view = inflater.inflate(R.layout.booking_recycler_view_fragment, null);

          if (getArguments() != null) {
            userid = getArguments().getString(KeyContent.KEY_USERID);// ============>>>>>>> this tes get from login activity (NULL VALUE)
        }

        return view;
    }

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

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        pDialog = new ProgressDialog(context);
        recyclerView = view.findViewById(R.id.recycler_view_booking);
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_booking);
        FloatingActionButton fab = view.findViewById(R.id.fab);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pDialog.setMessage("Loading Form ...");
                pDialog.show();
                entryDialog(0, "", "", "", "", 0);
                pDialog.dismiss();
                Toast.makeText(context,  userid, Toast.LENGTH_SHORT).show(); // ============>>>>>>> this tes get from login activity (NULL VALUE)
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getAllBooking(KeyContent.KEY_GET_ALL);
                swipeRefreshLayout.setRefreshing(false);
            }
        });
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(context.getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {

            @Override
            public void onClick(View view, int position) {

                // if (usernamex.toLowerCase().trim().equals(bookingList.get(position).getNamaRelasi().toLowerCase().trim())) {

                entryDialog(bookingList.get(position).getDetailID(),
                        bookingList.get(position).getNamaRelasi(),
                        bookingList.get(position).getNamaKapal(),
                        bookingList.get(position).getTanggalPembuatan(),
                        bookingList.get(position).getTanggalAntri(),
                        bookingList.get(position).getKuotaBongkar());

              /*  } else {

                    helper.iMessagaseBuilder(context, "  !", false);

                }*/

            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));
        getAllBooking(KeyContent.KEY_GET_ALL);
    }`



From login Activity ` loginbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                String userid = textViewuserid.getText().toString();
                String passd = textViewPass.getText().toString();

                if (userid.isEmpty()) {

                    textViewuserid.setError("User ID Tidak Boleh Kosong");
                    textViewuserid.requestFocus();
                    return;
                }

                if (passd.isEmpty()) {

                    textViewPass.setError("Password Harus Diisi");
                    textViewPass.requestFocus();
                    return;
                }

                _GetUserLogin(userid, passd, getDev.getDeviceName(), versionName);

                Bundle bundle = new Bundle();
                bundle.putString(KeyContent.KEY_USERID,"WAI");
                RecyclerViewBookingFragment fragment = new RecyclerViewBookingFragment();
                fragment.setArguments(bundle);
                getSupportFragmentManager().beginTransaction().add(android.R.id.content, fragment).commit();

            }
        });`

in MainNavigationDrawer ` private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new RecyclerViewBookingFragment(), "List Antrian"); //=====================================>> calling Fragment
        adapter.addFrag(new GridViewFragment(), "GridView");
        viewPager.setAdapter(adapter);

    }

回答1:

Fragments communicate using interfaces, FragmentA can communicate with FragmentB by creating a inner interface which defines methods that the calling Activity must implement. FragmentB in turn does same but its method can be to get the data from the Activity after FragmentA passes them to it. Below is an example :

public class FragmentA extends Fragment{

    private Listener mListener;

    public interface Listener{
        void setUser(String user);
        void setPassword(String password);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        listener = (Listener) context;
    }

    public void someMethod(String user, String password){
        mListener.setUser(user);
        mListener.setPassword(password);
    }


}

Same thing applies to FragmentB which will pick the passed data from the Activity.

public class FragmentB extends Fragment{

    private Listener mListener;
    private String user;
    private String password;


    public interface Listener{
        String getUser();
        String getPassword();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mListener = (Listener) context;
    }

    public void someMethod(){
        user = mListener.getUser();
        password = mListener.getUser();
        // use the data in some way
    }

}

The Activity must also implement these interfaces to finalize the communication pipeline.

public class MainActivity extends Activity implements FragmentA.Listener, FragmentB.Listener{

    private String user;
    private String password;

    public String getUser() {
       return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
       return password;
    }

    public void setPassword(String password) {
       this.password = password;
   }

   // the rest of the code that creates the fragments


}

I hope this helps you.