Java Code Examples for android.arch.lifecycle.ViewModelProviders

The following are top voted examples for showing how to use android.arch.lifecycle.ViewModelProviders. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GSoC-Info-Android   File: MainPageFragment.java   View source code 6 votes vote down vote up
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_about, container, false);
    RecyclerView recyclerView = view.findViewById(R.id.rv_timeline);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    MainPageViewModel mainPageViewModel = ViewModelProviders.of(getActivity()).get(MainPageViewModel.class);
    timelineAdapter = new TimelineAdapter();
    recyclerView.setAdapter(timelineAdapter);
    mainPageViewModel.getMainPageCopy().observe(this, new Observer<MainPage.Copy>() {
        @Override
        public void onChanged(@Nullable MainPage.Copy copy) {
            timelineAdapter.setData(copy);
        }
    });
    return view;
}
 
Example 2
Project: file.io-app   File: MainActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    /* Animate the views */
    MaterialIn.animate(rootView);

    /* Get the view model */
    uploadItemViewModel = ViewModelProviders.of(this).get(UploadItemViewModel.class);

    /* Handle incoming intent content */
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();
    // FIXME: Google photos URI
    if (type != null) {
        Log.d(TAG, "Receive Type: " + type);
        Uri fileUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
        Log.d(TAG, "\nURI: " + fileUri);
        if (Intent.ACTION_SEND.equals(action) && fileUri != null) {
            handleExplicitFileShare(intent);
        }
    }
    linkTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Copy the content of the link text to Clipboard
            ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText("link", linkTextView.getText());
            if (clipboardManager != null) {
                clipboardManager.setPrimaryClip(clipData);
                Toast.makeText(MainActivity.this, getString(R.string.link_copy), Toast.LENGTH_SHORT).show();
            }
        }
    });
}
 
Example 3
Project: android-arch-mvvm   File: LoginActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_activity_layout);

    // step0 获取相关的viewModel
    mLoginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);

    // step1 获取view
    mLoginBtn = (Button) findViewById(R.id.loginBtn);

    // step2 设置监听
    mLoginBtn.setOnClickListener(this);

    // setp3 绑定数据
    mLoginViewModel.loginResult.observe(this, mLoginObserver);
}
 
Example 4
Project: MVVMArms   File: WeatherDailyFragment.java   View source code 6 votes vote down vote up
@Override
public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //获取 Activity 的ViewModel 来共享数据
    mWeatherViewModel = ViewModelProviders.of(getActivity(), mViewModelFactory).get(WeatherViewModel.class);
    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(WeatherDailyViewModel.class);
    mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_weather_daily, container, false);
    //设置ViewModel
    mBinding.setViewModel(mViewModel);
    mBinding.retry.setViewModel(mViewModel);
    mBinding.retry.setRetry(mViewModel);
    mBinding.weatherSource.setViewModel(mViewModel);
    //RecyclerView设置Adapter
    mBinding.recyclerWeatherDaily.setAdapter(mAdapter);
    //设置Refresh
    mBinding.refresh.setColorSchemeColors(
            ContextCompat.getColor(getContext(), R.color.colorPrimary),
            ContextCompat.getColor(getContext(), R.color.colorAccent),
            ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
    return mBinding.getRoot();
}
 
Example 5
Project: friendlyeats-android   File: MainActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(mToolbar);

    // View model
    mViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);

    // Enable Firestore logging
    FirebaseFirestore.setLoggingEnabled(true);

    // Initialize Firestore and the main RecyclerView
    initFirestore();
    initRecyclerView();

    // Filter Dialog
    mFilterDialog = new FilterDialogFragment();
}
 
Example 6
Project: MVP-Architecture-Components   File: BaseActivity.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@CallSuper
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    BaseViewModel<V, P> viewModel = ViewModelProviders.of(this).get(BaseViewModel.class);
    boolean isPresenterCreated = false;
    if (viewModel.getPresenter() == null) {
        viewModel.setPresenter(initPresenter());
        isPresenterCreated = true;
    }
    presenter = viewModel.getPresenter();
    presenter.attachLifecycle(getLifecycle());
    presenter.attachView((V) this);
    if (isPresenterCreated)
        presenter.onPresenterCreated();
}
 
Example 7
Project: MVP-Architecture-Components   File: BaseFragment.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@CallSuper
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    BaseViewModel<V, P> viewModel = ViewModelProviders.of(this).get(BaseViewModel.class);
    boolean isPresenterCreated = false;
    if (viewModel.getPresenter() == null) {
        viewModel.setPresenter(initPresenter());
        isPresenterCreated = true;
    }
    presenter = viewModel.getPresenter();
    presenter.attachLifecycle(getLifecycle());
    presenter.attachView((V) this);
    if (isPresenterCreated)
        presenter.onPresenterCreated();
}
 
Example 8
Project: recyclerview-android   File: MultipleChoiceModeExampleActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_multiple_choice_mode_example);

    final PersonsViewModel viewModel = ViewModelProviders.of(this).get(PersonsViewModel.class);
    final Datasource<Person> datasource = viewModel.getDatasource();
    final CheckedPersonsAdapter adapter = new CheckedPersonsAdapter(datasource, true);

    mRecyclerView = (RecyclerView) findViewById(android.R.id.list);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setAdapter(adapter);

    mChoiceMode = new MultipleChoiceMode(savedInstanceState);
    mChoiceMode.setChoiceModeListener(this::onItemCheckedChanged);
    mChoiceModeHelper = new ChoiceModeHelper<>(adapter, mChoiceMode);
    mChoiceModeHelper.setRecyclerView(mRecyclerView);

    findViewById(R.id.action_clear_choices).setOnClickListener(v -> mChoiceMode.clearChoices());
    findViewById(R.id.action_get_checked_items).setOnClickListener(v -> showCheckedItems());
}
 
Example 9
Project: app-android   File: VmTestActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_vm_test);
    ButterKnife.bind(this);

    testViewModel = ViewModelProviders.of(this).get(TestViewModel.class);
    testViewModel.getMutableIntList().observe(this, list -> {
        Timber.d("trigger %s", list);
        if (list != null) {
            textNumList.setText(list.toString());
        }
    });

    setSupportActionBar(toolbar);
    if (getSupportActionBar() != null)
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}
 
Example 10
Project: recyclerview-android   File: SingleModalChoiceModeExampleActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_single_modal_choice_mode_example);
    
    mViewModel = ViewModelProviders.of(this).get(PersonsViewModel.class);
    final Datasource<Person> datasource = mViewModel.getDatasource();
    final ActivatedPersonsAdapter adapter = new ActivatedPersonsAdapter(datasource);
    
    mRecyclerView = (RecyclerView) findViewById(android.R.id.list);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setAdapter(adapter);
    
    final ActionModeCompat actionMode = ActionModeCompat.from(this);
    mChoiceMode = new SingleModalChoiceMode(actionMode, mModalChoiceModeListener, savedInstanceState);
    // mChoiceMode.setStartOnSingleTapEnabled(true);
    // mChoiceMode.setFinishActionModeOnClearEnabled(false);
    
    mChoiceModeHelper = new ChoiceModeHelper<>(adapter, mChoiceMode);
    mChoiceModeHelper.setOnItemClickListener(this::onItemClick);
    mChoiceModeHelper.setRecyclerView(mRecyclerView);
    
    findViewById(R.id.action_clear_choices).setOnClickListener(v -> mChoiceMode.clearChoices());
    findViewById(R.id.action_get_checked_item).setOnClickListener(v -> showCheckedItem());
}
 
Example 11
Project: android-instant-apps-demo   File: CartActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);
    viewModel = ViewModelProviders.of(this).get(CartViewModel.class);

    fab = (FloatingActionButton) findViewById(R.id.fab);
    toolbar = (Toolbar) findViewById(R.id.toolbar);

    setupToolbar();
    handleDeepLink();

    fab.setImageDrawable(VectorDrawableCompat.create(getResources(), R.drawable.ic_share_white_24dp, null));
    fab.setOnClickListener(view -> {
        String cartId = viewModel.getCartId().getValue();
        ShareCompat.IntentBuilder.from(this)
                .setText(String.format(Locale.US, "Check out my shopping cart now using Android Instant Apps! \n%s/cart/%s", ROOT_ENDPOINT, cartId))
                .setType("text/plain")
                .setChooserTitle(share_cart)
                .startChooser();
    });
}
 
Example 12
Project: EasyIPC   File: EasyIpcArchActivity.java   View source code 6 votes vote down vote up
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_test);
	RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler);
	recyclerView.setAdapter(adapter = new Adapter());

	viewModel = ViewModelProviders
			.of(this)
			.get(IpcViewModel.class)
			.init(MainService.class, BIND_AUTO_CREATE);

	viewModel.dispatchEvent(new EarlyData("sent from the activity")); // get's queued

	viewModel
			.getLiveData(Data.class)
			.observe(ProcessLifecycleOwner.get(), onData);

	viewModel
			.getLiveData(Data.List.class)
			.observe(this, onDataList);

	viewModel
			.getLiveData(EarlyData.class)
			.observe(this, onEarlyData);

}
 
Example 13
Project: RoomDemo2017   File: ListFragment.java   View source code 6 votes vote down vote up
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    //Set up and subscribe (observe) to the ViewModel
    listItemCollectionViewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(ListItemCollectionViewModel.class);

    listItemCollectionViewModel.getListItems().observe(this, new Observer<List<ListItem>>() {
        @Override
        public void onChanged(@Nullable List<ListItem> listItems) {
            if (ListFragment.this.listOfData == null) {
                setListData(listItems);
            }
        }
    });

}
 
Example 14
Project: RoomDemo2017   File: DetailFragment.java   View source code 6 votes vote down vote up
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    //Set up and subscribe (observe) to the ViewModel
    listItemViewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(ListItemViewModel.class);

    listItemViewModel.getListItemById(itemId).observe(this, new Observer<ListItem>() {
        @Override
        public void onChanged(@Nullable ListItem listItem) {
            if (listItem != null) {
                dateAndTime.setText(listItem.getItemId());
                message.setText(listItem.getMessage());
                coloredBackground.setImageResource(listItem.getColorResource());
            }

        }
    });


}
 
Example 15
Project: android-architecture-components   File: UserFragment.java   View source code 6 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    userViewModel = ViewModelProviders.of(this, viewModelFactory).get(UserViewModel.class);
    userViewModel.setLogin(getArguments().getString(LOGIN_KEY));
    userViewModel.getUser().observe(this, userResource -> {
        binding.get().setUser(userResource == null ? null : userResource.data);
        binding.get().setUserResource(userResource);
        // this is only necessary because espresso cannot read data binding callbacks.
        binding.get().executePendingBindings();
    });
    RepoListAdapter rvAdapter = new RepoListAdapter(dataBindingComponent, false,
            repo -> navigationController.navigateToRepo(repo.owner.login, repo.name));
    binding.get().repoList.setAdapter(rvAdapter);
    this.adapter = new AutoClearedValue<>(this, rvAdapter);
    initRepoList();
}
 
Example 16
Project: app-android   File: MainActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    //UI elements setup
    setSupportActionBar(toolbar);

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    navigationView.setNavigationItemSelectedListener(this);


    //Init shared usermodels
    ViewModelProviders.of(this).get(SharedUserViewModel.class);


    //Init nav, Load dashboard fragment
    NavigationController.init(this);
    NavigationController.getInstance().navigateToDashboard();
}
 
Example 17
Project: Android-CleanArchitecture-Java   File: WikiEntryActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //WikiEntry feature component scope start here
    ((CleanArchApp)getApplication()).buildWikiEntryComponent();

    setContentView(R.layout.activity_main);

    title = (EditText) findViewById(R.id.entryTitle);
    TextView extract = (TextView) findViewById(R.id.entryDetails);
    Button submitButton = (Button) findViewById(R.id.submitButton);
    submitButton.setOnClickListener(submitButtonOnClickListener);

    progressBar = (ContentLoadingProgressBar) findViewById(R.id.progressBar);

    wikiEntryViewModel = ViewModelProviders.of(this).get(WikiEntryViewModel.class);
    wikiEntryViewModel.getWikiEntry().observe(this, wikiEntry -> {

        Log.d(TAG, "received update for wikiEntry");
        extract.setText(wikiEntry.getExtract());
        progressBar.hide();
    });
}
 
Example 18
Project: mvvm-template   File: ContributorsFragment.java   View source code 6 votes vote down vote up
@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        adapter.setContributor(true);
        adapter.setFilter(false);
        recyclerView.addKeyLineDivider();
        RepoDetailViewModel repoDetailViewModel = ViewModelProviders.of(getActivity()).get(RepoDetailViewModel.class);
        repoDetailViewModel.getOnDataReady().observe(this, ready -> {
            if (ready != null && ready) {
                // noinspection ConstantConditions
                viewModel.initRepoDetail(repoDetailViewModel);
            }
        });
        setNoDataText("No Contributors");
        viewModel.getContributorsCount().observe(this, count -> {
            int n = count != null ? count : 0;
            Fragment fragment = getParentFragment();
            if (fragment != null && fragment instanceof TabBadgeListener) {
//                ((TabBadgeListener) fragment).setBadge(1, n);
            }
        });
    }
 
Example 19
Project: mapbox-navigation-android   File: NavigationView.java   View source code 5 votes vote down vote up
private void initViewModels() {
  try {
    locationViewModel = ViewModelProviders.of((FragmentActivity) getContext()).get(LocationViewModel.class);
    routeViewModel = ViewModelProviders.of((FragmentActivity) getContext()).get(RouteViewModel.class);
    navigationViewModel = ViewModelProviders.of((FragmentActivity) getContext()).get(NavigationViewModel.class);
  } catch (ClassCastException exception) {
    throw new ClassCastException("Please ensure that the provided Context is a valid FragmentActivity");
  }
}
 
Example 20
Project: SampleAppArch   File: FeedActivityModule.java   View source code 5 votes vote down vote up
/**
 * Created by Charles Ng on 26/9/2017.
 */


@Provides
FeedEntryListViewModel provideViewModel(FeedEntry feedEntry, FeedActivity feedActivity,
    FeedEntryListViewModelFactory factory) {
  FeedEntryListViewModel viewModel = ViewModelProviders.of(feedActivity, factory)
      .get(FeedEntryListViewModel.class);
  viewModel.getFeedEntry().set(feedEntry);
  return viewModel;
}
 
Example 21
Project: SampleAppArch   File: SimpleListActivityModule.java   View source code 5 votes vote down vote up
@Provides
SimpleMasterDetailShareViewModel provideVm(SimpleListActivity simpleListActivity,
    SimpleMasterDetailShareViewModelFactory factory) {
  return ViewModelProviders
      .of(simpleListActivity, factory).get(SimpleMasterDetailShareViewModel.class);

}
 
Example 22
Project: ArchitectureComponents   File: MainActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    viewModel = ViewModelProviders.of(this).get(FilmsViewModel.class);
    viewModel.init();
    lstFIlms = (ListView) findViewById(R.id.lstFilms);

    subscribeUi(viewModel);

    getLifecycle().addObserver(this);
}
 
Example 23
Project: DataBindingDemos   File: CounterActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    CounterViewModel viewModel = ViewModelProviders.of(this).get(CounterViewModel.class);

    ActivityCounterBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_counter);
    binding.setViewModel(viewModel);
}
 
Example 24
Project: PADC-MyanmarAttractions-AC   File: AttractionListActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_attraction_list);
    ButterKnife.bind(this, this);

    setActionBar(toolbar);

    ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setTitle(getString(R.string.app_title_mm));
    }

    mAttractionAdapter = new AttractionAdapter(getApplicationContext(), this);
    rvAttractions.setAdapter(mAttractionAdapter);

    LinearLayoutManager verticalSingleColumnLM = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
    rvAttractions.setLayoutManager(verticalSingleColumnLM);

    mAttractionsModel = ViewModelProviders.of(this).get(AttractionsModel.class);
    mAttractionsModel.initDatabase(getApplicationContext());
    mAttractionsModel.getAttractions().observe(this, new Observer<List<AttractionVO>>() {
        @Override
        public void onChanged(@Nullable List<AttractionVO> attractionVOs) {
            mAttractionAdapter.setNewData(attractionVOs);
        }
    });
}
 
Example 25
Project: RxRedux   File: UserListActivity.java   View source code 5 votes vote down vote up
@Override
public void initialize() {
    eventObservable = Observable.empty();
    viewModel = ViewModelProviders.of(this,
            new ViewModelFactory(DataServiceFactory.getInstance())).get(UserListVM.class);
    if (viewState == null) {
        eventObservable = Single.<BaseEvent>just(new GetPaginatedUsersEvent(0))
                .doOnSuccess(event -> Log.d("GetPaginatedUsersEvent", FIRED)).toObservable();
    }
}
 
Example 26
Project: MVVMArms   File: WeatherActivity.java   View source code 5 votes vote down vote up
@Override
public int initView(Bundle savedInstanceState) {
    //创建ViewModel
    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(WeatherViewModel.class);
    if (savedInstanceState != null) {
        //Restore data
        mReplace = savedInstanceState.getInt(EventBusTags.ACTIVITY_FRAGMENT_REPLACE);
    }
    return R.layout.activity_weather;
}
 
Example 27
Project: Android-ArchComponents   File: MainActivity.java   View source code 5 votes vote down vote up
private void callLocationListener() {
    ViewModelProviders.of(this)
            .get(MainActivityViewModel.class)
            .getLocation(this)
            .observe(this, location -> {
                // Update UI
            });
}
 
Example 28
Project: Android-Code-Demos   File: LoginActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ViewModelFactory factory = ViewModelFactory.getInstance(getApplication());
    final LoginViewModel loginViewModel =
            ViewModelProviders.of(this, factory).get(LoginViewModel.class);

    final ActivityLoginBinding binding =
            DataBindingUtil.setContentView(this, R.layout.activity_login);
    binding.setViewmodel(loginViewModel);

    loginViewModel.getOpenUserList().observe(this, new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            Intent intent = new Intent(LoginActivity.this, UserListActivity.class);
            intent.putExtra("token", s);
            startActivity(intent);
            finish();
        }
    });

    loginViewModel.getSnackbarMessage().observe(this, new SnackbarMessage.SnackbarObserver() {
        @Override
        public void onNewMessage(String message) {
            SnackbarUtil.showSnackbar(binding.getRoot(), message);
        }
    });

    findViewById(R.id.submit).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loginViewModel.login();
        }
    });
}
 
Example 29
Project: FitnessHabits   File: MainActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    viewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
    viewModel.init(FitnessHabitsApplication.application.getParamRepository());
}
 
Example 30
Project: permission-bitte   File: ArchitectureComponentsActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	findViewById(R.id.button).setOnClickListener(this);
	vm = ViewModelProviders.of(this).get(ArchitectureComponentsViewModel.class);
	vm.getState().observe(this, this);
	vm.shouldAskPermission(PermissionBitte.shouldAsk(this, vm));

}
 
Example 31
Project: DaggerAndroidMVVM   File: LobbyActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    AndroidInjection.inject(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lobby_activity);

    ButterKnife.bind(this);

    viewModel = ViewModelProviders.of(this, viewModelFactory).get(LobbyViewModel.class);

    viewModel.response().observe(this, response -> processResponse(response));
}
 
Example 32
Project: Moneycim   File: AddAndEditSpendingFragment.java   View source code 5 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    viewModel = ViewModelProviders.of(this).get(AddAndEditSpendingViewModel.class);
    subscribeSpendingGroups();
    if(spendingGroupList != null){
        fillSpinner(groupSpinner, spendingGroupList);
    }
}
 
Example 33
Project: LabDayApp   File: LoginFragment.java   View source code 5 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    viewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(LoginViewModel.class);

    observeLogin();
}
 
Example 34
Project: GmArchMvvm   File: RtoFragment.java   View source code 5 votes vote down vote up
@Override
public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(RtoViewModel.class);
    mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_rto, container, false);
    mBinding.setViewModel(mViewModel);//Set ViewModel
    return mBinding.getRoot();
}
 
Example 35
Project: android-persistence   File: BooksBorrowedByUserActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.db_activity);
    mBooksTextView = findViewById(R.id.books_tv);

    // Get a reference to the ViewModel for this screen.
    mViewModel = ViewModelProviders.of(this).get(BooksBorrowedByUserViewModel.class);

    // Update the UI whenever there's a change in the ViewModel's data.
    subscribeUiBooks();
}
 
Example 36
Project: android-persistence   File: TypeConvertersActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.db_activity);
    mBooksTextView = findViewById(R.id.books_tv);

    // Get a reference to the ViewModel for this screen.
    mViewModel = ViewModelProviders.of(this).get(TypeConvertersViewModel.class);

    // Update the UI whenever there's a change in the ViewModel's data.
    subscribeUiBooks();
}
 
Example 37
Project: Inshorts   File: ArticleListActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_article_list);

    ButterKnife.bind(this);

    mRootView = findViewById(R.id.root);

    //Getting the ApiService
    ApiService apiService = NetworkInstance.getInstance(this).getApiService();

    //Getting the Database
    AppDatabase database = Room.databaseBuilder(getApplicationContext(),
            AppDatabase.class, AppDatabase.DB_NAME).build();

    //Getting the ViewModel
    ListActivityViewModel.Factory factory = new ListActivityViewModel.Factory(getApplication(),
            new RepositoryImpl(apiService, database));
    mViewModel = ViewModelProviders.of(this, factory).get(ListActivityViewModel.class);

    rvArticleList.setLayoutManager(new LinearLayoutManager(this));

    NetworkInfo.getInstance(this).observe(this, connectedToInternet -> {
        if (!connectedToInternet) {
            //offline
            showMsg(getString(R.string.no_internet));
        } else {
            //online fetch the list if not fetched already
            mViewModel.fetchListIfNotFetched();
        }
    });
}
 
Example 38
Project: android-persistence   File: BooksBorrowedByUserActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.db_activity);
    mBooksTextView = findViewById(R.id.books_tv);

    // Get a reference to the ViewModel for this screen.
    mViewModel = ViewModelProviders.of(this).get(BooksBorrowedByUserViewModel.class);

    // Update the UI whenever there's a change in the ViewModel's data.
    subscribeUiBooks();
}
 
Example 39
Project: lead-management-android   File: ContactsFragment.java   View source code 5 votes vote down vote up
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_contacts, container, false);
    setHasOptionsMenu(true);
    mUnbinder = ButterKnife.bind(this, view);

    mViewModel = ViewModelProviders.of(this).get(ContactsFragmentViewModel.class);
    mViewModel.getContacts().observe(this, contacts -> {
        mAdapter.replaceData(contacts);
    });

    final MainActivity activity = (MainActivity) getActivity();
    if (activity != null) {
        activity.initFab();
    }

    mAdapter = new ContactsAdapter(this);
    recyclerView.setAdapter(mAdapter);

    textView.setVisibility(View.GONE);

    swipeToRefresh.setOnRefreshListener(() -> {
        mAdapter.replaceData(mViewModel.getContacts().getValue());
        swipeToRefresh.setRefreshing(false);
    });
    return view;
}
 
Example 40
Project: recyclerview-android   File: ListDatasourceExampleActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_datasource_example);

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

    final Datasource<Person> datasource = mViewModel.getDatasource();
    final PersonsAdapter adapter = new PersonsAdapter(datasource);

    mRecyclerView = (RecyclerView) findViewById(android.R.id.list);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setAdapter(adapter);

    // Add click support to RecyclerView. Adapter implements ItemClickHelper.Callback
    mItemClickHelper = new ItemClickHelper<>(adapter);
    mItemClickHelper.setOnItemClickListener(this::onItemClick);
    mItemClickHelper.setOnItemLongClickListener(this::onItemLongClick);
    mItemClickHelper.setRecyclerView(mRecyclerView);

    // Add enable view holder behavior. Adapter implements SimpleEnableBehavior.Callback
    mViewHolderTracker = new ViewHolderTracker();
    mViewHolderTracker.registerViewHolderObserver(new RecursiveEnableBehavior(adapter));
    mViewHolderTracker.setRecyclerView(mRecyclerView);

    findViewById(R.id.action_add_item).setOnClickListener(v -> mViewModel.addSingleItem());
    findViewById(R.id.action_add_multiple_items).setOnClickListener(v -> mViewModel.addMultipleItems());
}