android-fragments 为什么我无法从我的活动中获取数据到我的片段?

nzk0hqpo  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(147)

我有一个向SecondActivity发送登录信息(如名称、日期、电子邮件)的MainActivity。我尝试从该SecondActivity向SecondActivity的选项卡中名为ProfileFragment的片段添加该信息。我一直收到一个错误消息:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.String android.os.Bundle.getString(java.lang.String)”。
下面是我的MainActivity中的方法,它处理一个日期选择器对话框按钮,还有一个提交按钮,它将数据放入一个包中,并将其发送到SecondActivity。这里没有问题。

@Override
    public void onClick(View v) {
        //When the date button is clicked, display a calendar dialog
        if (v.getId() == R.id.dateButton) {
            final Calendar cal = Calendar.getInstance();
            mYear = cal.get(Calendar.YEAR);
            mMonth = cal.get(Calendar.MONTH);
            mDay = cal.get(Calendar.DAY_OF_MONTH);
            DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                    dateText.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

                }
            }, mYear, mMonth, mDay);
            datePickerDialog.show();
        }
        //When submit button is clicked. Validate form data and go to next activity
        if (v.getId() == R.id.submitButton) {
            //Create intent for ProfileActivity
            Intent SecondActivity = new Intent(MainActivity.this, SecondActivity.class);
            //Create a new bundle
            Bundle bundle = new Bundle();

            //Convert all input data to strings
            String stringName = name.getText().toString();
            String stringEmail = email.getText().toString();
            String stringUserName = userName.getText().toString();
            String stringDate = dateText.getText().toString();
            String stringDescription = description.getText().toString();
            String stringOccupation = occupation.getText().toString();

            try {   //If age/name/email/username is invalid or under 18 then return
                if ( !validateEmail() || !checkAge(convertDate(stringDate)) || !validateName() || !validateUserName() || !validateDescription() || !validateOccupation()) {
                    validateEmail();
                    validateName();
                    validateUserName();
                    validateDescription();
                    validateOccupation();
                    checkAge(convertDate(stringDate));
                    return;
                    //If age/name/username/email is valid then bundle data to send to ProfileActivity
                } else {
                    //get users age
                    int age = getAge(convertDate(stringDate));
                    //add data to bundle
                    bundle.putString("name", stringName);
                    bundle.putString("email", stringEmail);
                    bundle.putString("date", stringDate);
                    bundle.putString("userName", stringUserName);
                    bundle.putString("description",stringDescription);
                    bundle.putString("occupation",stringOccupation);
                    bundle.putInt("age", age);
                    //Start activity
                    SecondActivity.putExtras(bundle);
                    startActivity(SecondActivity);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
    }

这是我第二个活动

public class SecondActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager2 viewPager2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        tabLayout = findViewById(R.id.tablayout);
        viewPager2 = findViewById(R.id.viewpager2);

        viewPager2.setAdapter(createAdapter());

        //create profilefragment
        ProfileFragment profileFragment = new ProfileFragment();

        //get bundle

            Bundle bundle = getIntent().getExtras();
            if(bundle != null) {
            String stringDate = bundle.getString("date");
            String stringName = bundle.getString("name");
            String stringEmail = bundle.getString("email");
            String stringUserName = bundle.getString("userName");
            String stringDescription = bundle.getString("description");
            String stringOccupation = bundle.getString("occupation");
            int userAge = bundle.getInt("age");

            //set arguments
            profileFragment.setArguments(bundle);
        }
    }

    private VpAdapter createAdapter(){
        VpAdapter adapter = new VpAdapter(this);
        return adapter;
    }
}

class VpAdapter extends FragmentStateAdapter {
    public VpAdapter(FragmentActivity fa){
        super(fa);
    }
    private static int NUM_ITEMS = 1;
    @Override
    public Fragment createFragment(int position){
        Fragment fragment = null;

        switch(position){
            case 0:
                fragment = new ProfileFragment();
                break;
        }
        return fragment;
    }
    @Override
    public int getItemCount() {
        return NUM_ITEMS;
    }
}

这是我的档案片段

public class ProfileFragment extends Fragment {
    TextView welcome;
    TextView name;
    TextView age;
    TextView description;
    TextView occupation;

public ProfileFragment() {
        // Required empty public constructor
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_profile, container, false);

        //Receive data from secondActivity through getArguments

        String mStringDate = getArguments().getString("date");
        String mStringName = getArguments().getString("name");
        String mStringEmail = getArguments().getString("email");
        String mStringUserName = getArguments().getString("userName");
        String mStringDescription = getArguments().getString("description");
        String mStringOccupation = getArguments().getString("occupation");
        int mUserAge = getArguments().getInt("age");

        welcome = v.findViewById(R.id.welcome);
        name = v.findViewById(R.id.user_name);
        age = v.findViewById(R.id.age);
        description = v.findViewById(R.id.description);
        occupation = v.findViewById(R.id.occupation);

        //set username in welcome message.
        welcome.setText("Welcome " + mStringUserName);

        //set username, age, description, and job into the profile fields
        name.append(mStringUserName);
        age.append(String.valueOf(mUserAge));
        description.append(mStringDescription);
        occupation.append(mStringOccupation);

        // Inflate the layout for this fragment
        return v;
    }

我的错误指向这一行“字符串mStringDate = getArguments().getString(“日期”);“我得到了一个空对象引用。有人能帮助我吗?”

twh00eeo

twh00eeo1#

仅将一个活动与ViewModel一起使用

相关问题