Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class CurrentUser {
- private static final CurrentUser ourInstance = new CurrentUser();
- private CurrentUserInterface mInterface;
- private CurrentUser() {
- }
- public static CurrentUser getInstance() {
- return ourInstance;
- }
- public void setUserName(String userName) {
- if (mInterface != null) {
- mInterface.setUserName(userName);
- }
- }
- public void setInterface(CurrentUserInterface mInterface) {
- this.mInterface = mInterface;
- }
- public interface CurrentUserInterface {
- void setUserName(String username);
- }
- }
- public class UserViewModel extends AndroidViewModel implements CurrentUser.CurrentUserInterface {
- private MutableLiveData<String> userName;
- public UserViewModel(@NonNull Application application) {
- super(application);
- CurrentUser.getInstance().setInterface(this); // <-- Is this a good practice ??
- }
- public LiveData<String> getUserName() {
- if (userName == null) {
- userName = new MutableLiveData<>();
- loadUser("username","password");
- }
- return userName;
- }
- @Override
- public void setUserName(String username) {
- if (this.userName == null) {
- return;
- }
- this.userName.postValue(username);
- }
- private void loadUser(String username, String password) {
- Intent service = new Intent(context, HttpService.class);
- service.putExtra(HTTP_SERVICE_LOGIN, true);
- service.putExtra(HTTP_SERVICE_LOGIN_USERNAME, username);
- service.putExtra(HTTP_SERVICE_LOGIN_PASSWORD, password);
- context.startService(service);
- }
- }
- public class HttpService extends IntentService {
- // Login constants
- public static final String HTTP_SERVICE_LOGIN = "HTTP_SERVICE_LOGIN";
- public static final String HTTP_SERVICE_LOGIN_USERNAME = "HTTP_SERVICE_LOGIN_USERNAME";
- public static final String HTTP_SERVICE_LOGIN_PASSWORD = "HTTP_SERVICE_LOGIN_PASSWORD";
- @Override
- protected void onHandleIntent(@Nullable Intent intent) {
- if (intent != null) {
- if (intent.getBooleanExtra(HTTP_SERVICE_LOGIN, false)) {
- String username = intent.getStringExtra(HTTP_SERVICE_LOGIN_USERNAME);
- String password = intent.getStringExtra(HTTP_SERVICE_LOGIN_PASSWORD);
- loginAction(username, password);
- }
- }
- }
- private void loginAction(String username, String password) {
- // Async call to http server - this part is working fine
- // Then
- CurrentUser.getInstance().setUserName("User connected");
- }
- }
- public class MainActivity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- /// initialization code
- final TextView tv = navigationView.getHeaderView(0).findViewById(R.id.textViewName);
- UserViewModel model = ViewModelProviders.of(this).get(UserViewModel.class);
- model.getUserName().observe(this, new Observer<String>() {
- @Override
- public void onChanged(@Nullable String s) {
- tv.setText(s);
- }
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement