Skip to content

Instantly share code, notes, and snippets.

@MohammadSamandari
Last active April 6, 2020 22:50
Show Gist options
  • Save MohammadSamandari/e3e1d26fa4bf90a5e1147d63d241811c to your computer and use it in GitHub Desktop.
Save MohammadSamandari/e3e1d26fa4bf90a5e1147d63d241811c to your computer and use it in GitHub Desktop.
Android- ViewModel and Live Data
package mohammad.samandari.testviewmodel;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Lord";
private MyViewModel myViewModel;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
final TextView textView = findViewById(R.id.textView);
// Get the ViewModel.
myViewModel = new ViewModelProvider(this).get(MyViewModel.class);
// Create the observer which updates the UI.
final Observer<Integer> aObserver = new Observer<Integer>() {
@Override
public void onChanged (@Nullable final Integer a) {
// Update the UI, in this case, a TextView.
textView.setText(String.valueOf(a));
}
};
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
myViewModel.getA().observe(this, aObserver);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View v) {
myViewModel.getA().setValue(myViewModel.getA().getValue() + 1);
}
});
}
}
package mohammad.samandari.testviewmodel;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class MyViewModel extends ViewModel {
private MutableLiveData<Integer> a;
public MutableLiveData<Integer> getA () {
if (a == null) {
a = new MutableLiveData<Integer>();
a.setValue(0);
}
return a;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment