无法将数据从“活动”传递到片段。得到NULL

时间:2018-10-18 17:23:27

标签: android android-fragments android-recyclerview android-alertdialog datepickerdialog

请帮助我,我使用导航抽屉和片段。当用户按下登录按钮时,我会检索用户数据并将其发送到片段中的变量。但是调用片段时,片段中的变量值为null。值如何不能为null。下面是代码:

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 个答案:

答案 0 :(得分:0)

片段使用接口进行通信, FragmentA 可以通过创建定义方法的内部接口来与 FragmentB 进行通信。调用 活动 必须实现。 FragmentB 的功能相同,但其方法可以是在 FragmentA 将数据传递给活动后从活动中获取数据。下面是一个示例:

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);
    }


}

FragmentB 同样适用,它将从活动中选择传递的数据。

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
    }

}

该活动还必须实现这些接口以最终确定通信管道。

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


}

希望对您有帮助。