MutableLiveData with ArrayList and ArrayAdapter

29 Views Asked by At

i am trying change my: ArrayList<Worker> Workers = new ArrayList<Worker>(); to: private MutableLiveData<ArrayList<Worker>> Workers = new MutableLiveData<>(); i built ViewModel class that conect the MainActivity and Worker class: MyViewModel class: my question is what i need to change in MyViewModel functions for the functions will get the MutableLiveData without nullPointers.

public class MyViewModel extends ViewModel {
    ArrayList<Worker> Workers = new ArrayList<Worker>();
    //Double sum=0.0;
    private MutableLiveData<Double> sum = new MutableLiveData<>();
    //private MutableLiveData<ArrayList<Worker>> Workers = new MutableLiveData<>();

    public LiveData<Double> getSum() {
        return sum;
    }

    public void reduceSum(Double s) {
        Double currentVal = sum.getValue() !=null ? sum.getValue():0;
        sum.setValue(currentVal-s);
    }

    public ArrayList<Worker> getWorkers() {
        return Workers;
    }

    public void removeTheLast() {
        int index = Workers.size() -1;
        Workers.remove(index);
    }
    public void addToList(String name,String time,String type) {
        Workers.add(new Worker(0, name,time,type,Worker.ExChange(time), (int) 0,"X","X"));

    }

    public void removeFromList(int listItem) {
        Workers.remove(listItem);

    }
    public void sumHours(Double num) {        // calc the total hours in shift of all workers
        int index = Workers.size() -1;
        if(Workers.get(index).getWorkerType().equals("מלצר") || Workers.get(index).getWorkerType().equals("ברמן")) {
            Double currentVal = sum.getValue() !=null ? sum.getValue():0;
            sum.setValue(currentVal+num);
            //sum += num;
        }
    }

}

changing the 'sum' was easy and worked but working with Arrays make me some problems.. the MainActivity: in MainActivity the problm is when i need to change the func getWorkers() in MyViewModel and i using the func in MainActivity.

public class MainActivity extends AppCompatActivity {

    TimePickerDialog picker;
 
    ArrayList<String> teamList = new ArrayList<String>();

    private static MyCustomAdapter adapter; //========

    ActivityMainBinding binding;
    MyViewModel viewModel;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        viewModel = new ViewModelProvider(this).get(MyViewModel.class);

        binding.WorkerTimeInput.setInputType(InputType.TYPE_NULL);

        binding.buttonAdd.setOnClickListener(new View.OnClickListener() {           // after push the button save its saves the inputs that entered by the user

            @Override
            public void onClick(View v) {

                String getInput=binding.WorkerNameInput.getText().toString();
                String getInputOne=binding.WorkerTimeInput.getText().toString();

                if(getInput == null || getInput.trim().equals("") || getInputOne == null || getInputOne.trim().equals("") ||
                        spinnerTeam.getSelectedItem().toString().equals("בחר סוג עובד")) {   // if the field is empty
                    Toast.makeText(getBaseContext(), "Check if you enter Name/Job", Toast.LENGTH_LONG).show();
                }
                else {
                    binding.WorkerNameInput.setText(" ");
                    binding.WorkerTimeInput.setText(" ");

                    if(Worker.ExChange(getInputOne) == 0) {
                        Toast.makeText(getBaseContext(), "The time shift isnt corect", Toast.LENGTH_LONG).show();
                        viewModel.removeTheLast();
                    }
                    else {
                        viewModel.addToList(getInput,getInputOne,spinnerTeam.getSelectedItem().toString());
                        viewModel.sumHours(Worker.ExChange(getInputOne));
                       
                    }
                    binding.sumHours.setText( "סהכ שעות במשמרת: " );                                  
                    binding.WorkerNameInput.setText(null);
                    binding.WorkerTimeInput.setText(null);
                }

            }
        });
        binding.nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sum = binding.totlHoursUpdating.getText().toString();
                Intent i = new Intent(getApplicationContext(),SeconddActivity.class);
                i.putExtra("message", sum);
                //i.putParcelableArrayListExtra("Array", (ArrayList<? extends Parcelable>) Workers);
                i.putExtra("Array",viewModel.getWorkers());
                startActivity(i);
            }
        });
        viewModel.getSum().observe(this, new Observer<Double>() {
            @Override
            public void onChanged(Double aDouble) {
                //binding.sumHours.setText(viewModel.getSum().toString());
                binding.totlHoursUpdating.setText("hh"+aDouble);
            }
        });
        viewModel.getWorkers().observe(this, new Observer<ArrayList<Worker>>() {
            @Override
            public void onChanged(ArrayList<Worker> workers) {
                adapter = new MyCustomAdapter(workers, getApplicationContext()); //==========
                binding.listViewNew.setAdapter(adapter);
                adapter.notifyDataSetChanged();

            }
        });

    }
}

i am try to replce the ArrayList With MutableLiveData

0

There are 0 best solutions below