Tuesday, 7 May 2019

modelView Simple use | How model view hold the data when we rotating the screen

MainActivity.java:-
public class MainActivity extends AppCompatActivity {
    private TextView randomText;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        randomText = findViewById(R.id.randomText);
        //MainActivityViewModel generator = new MainActivityViewModel();
MainActivityViewModel dataGenerator = ViewModelProviders.of(this).get(MainActivityViewModel.class);
        String reandomNumber = dataGenerator.getRandomNumber();
        randomText.setText(reandomNumber);
    }
}

MainActivityViewModel:-

public class MainActivityViewModel extends ViewModel {
    private String randomNumber;

    public String getRandomNumber() {
        if (randomNumber == null) {
            createRandonNumber();
        }
        return randomNumber;
    }

    public void createRandonNumber() {
        Random random = new Random();
        randomNumber = "Number ::=" + (random.nextInt(10 - 1) + 1);
    }
}

Dependencies:-
def lifecycle_version = "1.1.1"
implementation "android.arch.lifecycle:extensions:$lifecycle_version"


#################################################################################

Using live data in above example :-

MainActivity:-
button = findViewById(R.id.button);
final MainActivityViewModel dataGenerator = ViewModelProviders.of(this).get(MainActivityViewModel.class);
LiveData<String> reandomNumber = dataGenerator.getRandomNumber();
reandomNumber.observe(this, new Observer<String>() {
    @Override    public void onChanged(@Nullable String s) {
        Log.d("supriya",":: onChanged ::");
        randomText.setText(s);
    }
});
button.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
        Log.d("supriya",":: onClick ::");
        dataGenerator.createRandonNumber();
    }
});


MainActivityViewModel:-

public class MainActivityViewModel extends ViewModel {
    private MutableLiveData<String> randomNumber;

    public MutableLiveData<String> getRandomNumber() {
        if (randomNumber == null) {
            Log.d("supriya",":: getRandomNumber== null ::");
            randomNumber = new MutableLiveData<>();
            createRandonNumber();
        }
        return randomNumber;
    }

    public void createRandonNumber() {
        Log.d("supriya",":: createRandonNumber ::");
        Random random = new Random();
        randomNumber.setValue("Number ::=" + (random.nextInt(10 - 1) + 1));
    }
}

No comments:

Post a Comment