Итак, я собираюсь установить спиннер в моем 1-м фрагменте, и мне нужны данные onItemSelected из 1-го фрагмента, а позже я хочу показать им данные в 4-м фрагменте, но моя следующая и предыдущая кнопка находится на операции бронирования. Поэтому я пытаюсь ошибиться в своей активности бронирования. Но я получаю, что logcat говорит, что мой Bundle пуст. Может кто-то мне помочь, пожалуйста!! Я не знаю, как решить это.
Вот моя ошибка logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.VehicleServiceBooking/com.example.VehicleServiceBooking.BookingActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.example.VehicleServiceBooking.BookingActivity.onCreate(BookingActivity.java:192)
Это мой 1 фрагмент
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View itemView = inflater.inflate(R.layout.fragment_booking_step_one,container,false);
unbinder = ButterKnife.bind(this,itemView);
car_model = (Spinner)itemView.findViewById(R.id.car_millage_spinner);
service_types = (Spinner)itemView.findViewById(R.id.service_type_spinner);
car_millage = (Spinner)itemView.findViewById(R.id.car_model_spinner);
//get spinner values
getSpinners();
initView();
loadAllSalon();
return itemView;
}
private void getSpinners() {
ArrayAdapter carmodel = ArrayAdapter.createFromResource(getContext(),
R.array.car_models, android.R.layout.simple_spinner_dropdown_item);
car_model.setAdapter(carmodel);
car_model.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String selectedItemText = car_model.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
ArrayAdapter serviceTypes = ArrayAdapter.createFromResource(getContext(),
R.array.service_types, android.R.layout.simple_spinner_dropdown_item);
service_types.setAdapter(serviceTypes);
service_types.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String selectedItemText = service_types.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
ArrayAdapter mileageCar = ArrayAdapter.createFromResource(getContext(),
R.array.car_millages, android.R.layout.simple_spinner_dropdown_item);
car_millage.setAdapter(mileageCar);
car_millage.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String selectedItemText = car_millage.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
Здесь моя кнопка BookingActivity. java следующая кнопка и предыдущая, и где я объявляю пакет, чтобы получить значение в счетчике в 1stFragment
@OnClick(R.id.btn_next_step)
void nextClick(){
if (Common.step < 3 || Common.step == 0)
{
Common.step++;
if (Common.step == 1)
{
if (Common.currentSalon != null)
loadBarberBySalon(Common.currentSalon.getSalonId());
String ServiceType = String.valueOf(service_types.getSelectedItem().toString());
String carMillage = String.valueOf(car_millage.getSelectedItem().toString());
String carModel = String.valueOf(car_model.getSelectedItem().toString());
if (ServiceType.equals("Choose Service") | carMillage.equals("Choose Car Millage") || carModel.equals("Choose Car Model"))
return;
else
{
Intent gotoBookingStep4 = new Intent(this, BookingStep4Fragment.class);
Bundle extras = new Bundle();
extras.putString("CarMillageData", carMillage);
extras.putString("CarModelData", carModel);
extras.putString("Service_Type",ServiceType);
extras.putString("newServiceTypeFromIntent", ServiceTypeFromIntent);
extras.putString("CarMillageFromCarActivity", CarMillageDataFromIntent);
extras.putString("CarModelFromCarActivity", CarModelDataFromIntent);
gotoBookingStep4.putExtras(extras);
startActivityForResult(gotoBookingStep4,0);
}
}
else if (Common.step == 2)
{
if (Common.currentBarber != null)
loadTimeSlotOfBarber(Common.currentBarber.getBarberId());
}
else if (Common.step == 3)
{
if (Common.currentTimeSlot != -1)
confirmBooking();
}
viewPager.setCurrentItem(Common.step);
}
}
Это моя onCreate на странице BookingActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
ButterKnife.bind(BookingActivity.this);
Bundle extras = getIntent().getExtras();
ServiceTypeFromIntent = extras.getString("Service_Type");
CarMillageDataFromIntent = extras.getString("CarMillageData");
CarModelDataFromIntent = extras.getString("CarModelData");
car_model = (Spinner)findViewById(R.id.car_millage_spinner);
service_types = (Spinner)findViewById(R.id.service_type_spinner);
car_millage = (Spinner)findViewById(R.id.car_model_spinner);
dialog = new SpotsDialog.Builder().setContext(this).setCancelable(false).build();
localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.registerReceiver(buttonNextReceiver,new IntentFilter(Common.KEY_ENABLE_BUTTON_NEXT));
setupStepView();
setColorButton();
viewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(4);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
stepView.go(i,true);
if (i == 0)
btn_previous_step.setEnabled(false);
else
btn_previous_step.setEnabled(true);
btn_next_step.setEnabled(false);
setColorButton();
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
}
Это мой 4-й фрагмент, где я хочу, чтобы пользователь данных выбирал во фрагменте счетчика1
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ifcmApi = RetrofitClient.getInstance().create(IFCMApi.class);
Bundle extras2 = getActivity().getIntent().getExtras();
CarMillageDataFromIntent = extras2.getString("CarMillageFromCarActivity");
CarModelDataFromIntent = extras2.getString("CarModelFromCarActivity");
ServiceTypeFromIntent = extras2.getString("ServiceTypeFromService");
//init object
AssignMyValues();
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
localBroadcastManager = LocalBroadcastManager.getInstance(getContext());
localBroadcastManager.registerReceiver(confirmBookingReceiver,new IntentFilter(Common.KEY_CONFIRM_BOOKING));
dialog = new SpotsDialog.Builder().setContext(getContext()).setCancelable(false)
.build();
}
private void AssignMyValues() {
textViewType.setText("" + ServiceTypeFromIntent + "");
textViewCarMillage.setText("" + CarMillageDataFromIntent + "");
textViewModel.setText("" + CarModelDataFromIntent + "");
//extractx int from String
CarMillageDataFromIntent = CarMillageDataFromIntent.replaceAll("\\D+", "");
//covert car millage to integer
millage_value = Integer.parseInt(CarMillageDataFromIntent);
//setting user price
if (millage_value == 1000 || millage_value < 15000) {
millage_price_result = 100;
//converting int to String
millage_price_value = String.valueOf(millage_price_result);
//set price in String format
textViewPrice.setText(" RM " + millage_price_value + "");
} else if (millage_value == 15000 || millage_value < 30000) {
millage_price_result = 200;
//converting int to String
millage_price_value = String.valueOf(millage_price_result);
//set price in String format
textViewPrice.setText(" RM " + millage_price_value + "");
} else if (millage_value == 30000 || millage_value < 50000) {
millage_price_result = 300;
//converting int to String
millage_price_value = String.valueOf(millage_price_result);
//set price in String format
textViewPrice.setText(" RM " + millage_price_value + "");
} else if (millage_value == 50000 || millage_value < 80000) {
millage_price_result = 400;
//converting int to String
millage_price_value = String.valueOf(millage_price_result);
//set price in String format
textViewPrice.setText(" RM " + millage_price_value + "");
}
}
@Override
public void onDestroy() {
super.onDestroy();
compositeDisposable.clear();
localBroadcastManager.unregisterReceiver(confirmBookingReceiver);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View itemView = inflater.inflate(R.layout.fragment_booking_step_four,container,false);
unbinder = ButterKnife.bind(this,itemView);
textViewCarMillage = (TextView)itemView.findViewById(R.id.service_millage_text);
textViewType = (TextView) itemView.findViewById(R.id.service_types_text);
textViewModel = (TextView) itemView.findViewById(R.id.service_model_text);
textViewPrice = (TextView)itemView.findViewById(R.id.service_estimatedprice_text);
return itemView;
}