重新创建活动时,每次都会调用LiveData观察者

时间:2019-12-03 05:31:40

标签: android mvvm android-livedata observers

我正在观察从外部api获取的livedata。正在验证实时数据并完成活动,如下面的代码所示。但是当我再次创建此活动时,将再次调用Observer,该活动将自行完成。

viewModel.getRescheduleResponse().observe(this, new Observer<Response >() {
        @Override
        public void onChanged(Response response) {
            if(response!=null){
                if(response.getOutput().get(0).getStatus().equalsIgnoreCase("success")){
                    Toast.makeText(ProcessDetails.this, "Service rescheduled successfully", Toast.LENGTH_SHORT).show();
                    finish();
                }else{
                    Toast.makeText(ProcessDetails.this, response.getOutput().get(0).getMessage(), Toast.LENGTH_SHORT).show();
                }
            }else{
                Toast.makeText(ProcessDetails.this, "Please check your network", Toast.LENGTH_SHORT).show();
            }


        }
    });

这是活动代码。观察者在重新启动此活动时触发的地方

public class ProcessDetails extends BaseActivity {


TextView tracktech, reschedule;
LinearLayout action;
ProcessDetailViewModel viewModel;
ActivityProcessDetailsBinding binding;
ProgressDialog pdialog;
 Dialog dialog;

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

    binding = DataBindingUtil.setContentView(this, R.layout.activity_process_details);
    //viewModel = new ProcessDetailViewModel();
    viewModel = ViewModelProviders.of(this).get(ProcessDetailViewModel.class);

    if (savedInstanceState == null) {
        viewModel.init();
    }
    pdialog = new ProgressDialog(this);
    pdialog.setMessage("Please wait...");
    binding.setViewModel(viewModel);
    binding.setClickHandlers(new ClickHandlers());


    tracktech = findViewById(R.id.tracktxt);
    reschedule = findViewById(R.id.rescheduletxt);
    action = findViewById(R.id.actionlay);


    if (getIntent().getStringExtra("FROM") != null) {
        tracktech.setVisibility(View.GONE);
        action.setVisibility(View.GONE);

    }


    setupObdservers();


    tracktech.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent i = new Intent(getApplicationContext(), TrackingActivity.class);
            startActivity(i);
        }
    });





}


public void setupObdservers() {


    viewModel.getProcessdetailsResponse().observe(this, new Observer<ProcessDetailResponse>() {
        @Override
        public void onChanged(ProcessDetailResponse processDetailResponse) {
            Log.i("darbar", "okay");

            ProcessDetailModel model = new ProcessDetailModel();

            model.setBrand(processDetailResponse.getOutput().get(0).getBookinglist().get(0).getBrand());
            model.setDate(processDetailResponse.getOutput().get(0).getBookinglist().get(0).getDate());
            model.setTime(processDetailResponse.getOutput().get(0).getBookinglist().get(0).getTime());
            model.setAddress(processDetailResponse.getOutput().get(0).getBookinglist().get(0).getAddress());
            model.setService(processDetailResponse.getOutput().get(0).getBookinglist().get(0).getServiceType());
            model.setTechName(processDetailResponse.getOutput().get(0).getBookinglist().get(0).getTechnicianDetails().get(0).getName());
            model.setTechPhone(processDetailResponse.getOutput().get(0).getBookinglist().get(0).getTechnicianDetails().get(0).getPhoneNo());

            viewModel.setModel(model);
            binding.setViewModel(viewModel);


        }
    });





    viewModel.getRescheduleResponse().observe(this, new Observer<LoginResponse>() {
        @Override
        public void onChanged(LoginResponse loginResponse) {
            if(loginResponse!=null){
                if(loginResponse.getOutput().get(0).getStatus().equalsIgnoreCase("success")){
                    Log.i("darbar","gone");
                    Toast.makeText(ProcessDetails.this, "Service rescheduled successfully", Toast.LENGTH_SHORT).show();

                    finish();
                }else{
                    Toast.makeText(ProcessDetails.this, loginResponse.getOutput().get(0).getMessage(), Toast.LENGTH_SHORT).show();
                }
            }else{
                Toast.makeText(ProcessDetails.this, "Please check your network", Toast.LENGTH_SHORT).show();
            }


        }
    });


}


public class ClickHandlers {


    public void onRescheduleClick(View v) {


        showCustomDialog();


    }


}

private void showCustomDialog() {

     dialog = new Dialog(ProcessDetails.this);
    dialog.setContentView(R.layout.dialog_reschedule);

    Button okbtn = dialog.findViewById(R.id.buttonOk);
    final TextView datetxt = dialog.findViewById(R.id.datetxt);
    final TextView timetxt = dialog.findViewById(R.id.timetxt);


    datetxt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


            final Calendar calendar = Calendar.getInstance();
            int yy = calendar.get(Calendar.YEAR);
            int mm = calendar.get(Calendar.MONTH);
            int dd = calendar.get(Calendar.DAY_OF_MONTH);
            DatePickerDialog datePicker = new DatePickerDialog(ProcessDetails.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    String date = String.valueOf(dayOfMonth) + "/" + String.valueOf(monthOfYear+1)
                            + "/" + String.valueOf(year);

                    datetxt.setText(date);
                }
            }, yy, mm, dd);
            datePicker.show();

        }
    });


    timetxt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


            Calendar mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);
            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(ProcessDetails.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int hourOfDay, int selectedMinute) {
                    boolean isPM = (hourOfDay >= 12);
                    timetxt.setText(String.format("%02d:%02d %s", (hourOfDay == 12 || hourOfDay == 0) ? 12 : hourOfDay % 12, selectedMinute, isPM ? "PM" : "AM"));

                }
            }, hour, minute, false);//Yes 24 hour time
            mTimePicker.setTitle("Select Time");
            mTimePicker.show();


        }
    });


    okbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            if(datetxt.toString().length()<2){

                Toast.makeText(ProcessDetails.this, "Plese fill reschedule date", Toast.LENGTH_SHORT).show();
            }else if(timetxt.toString().length()<2){

                Toast.makeText(ProcessDetails.this, "Plese fill reschedule time", Toast.LENGTH_SHORT).show();
           } else {
                viewModel.rescheduleService(datetxt.getText().toString(),timetxt.getText().toString());
            }

            // Close dialog
            dialog.dismiss();
        }
    });
    dialog.show();
}

}

有解决方案吗?

0 个答案:

没有答案