Search code examples
javaandroidandroid-livedatamutablelivedata

Using Livedata and having a problem with displaying MutableLiveData<Float> result


I am just testing ViewModel and LiveData of Android Architechture Components. I have this basic Activity with one EditText to receive a number from the user and when clicking the Convert button then the Textview should give the result multipled by 0.87. For example when I put 100 in EditText and click Convert button it should give the result of 87. But when I click the Convert button the Textview gives the value of "android.arch.lifecycle.MutableLiveData@eb84a7b". And when I rotate the screen then the result becomes 87. Could you please have a look at my code and tell me where I should revise the code so that the result gives the number when I click Convert button?

ViewModelLiveDataActivity.java:

public class ViewModelLiveDataActivity extends AppCompatActivity {

private ViewModel2 mViewModel;

private EditText mEditText;
private TextView mTextView;
private Button mButton;

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

    mViewModel = ViewModelProviders.of(this).get(ViewModel2.class);

    mEditText = (EditText) findViewById(R.id.livedata_editText);
    mTextView = (TextView) findViewById(R.id.livedata_textView);
    mButton = (Button) findViewById(R.id.livedata_button);

    final Observer<Float> resultObserver = new Observer<Float>() {
        @Override
        public void onChanged(@Nullable final Float result) {
            mTextView.setText(result.toString());

        }
    };

    mViewModel.getResult().observe(this, resultObserver);

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Doing the calculations using ViewModel class
            String dollarText = mEditText.getText().toString();
            mViewModel.setAmount(dollarText);
            mTextView.setText(mViewModel.getResult().toString());
        }
    });



}
}

ViewModel2.java:

public class ViewModel2 extends ViewModel {

private static final float EURO_DOLLAR_EXCHANGE_RATE = 0.87f;
private String dollarString = ""; //the value of UI EditText
private MutableLiveData<Float> result = new MutableLiveData<>();

public void setAmount(String value) {
    this.dollarString = value;
    result.setValue(Float.valueOf(dollarString) * EURO_DOLLAR_EXCHANGE_RATE);
}

public MutableLiveData<Float> getResult() {
    return result;
}
}

Solution

  • Use getValue() instead of toString()

    mTextView.setText(mViewModel.getResult().getValue());